Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Static Inventory in Ansible

Introduction

In Ansible, an inventory is a collection of hosts that can be managed by Ansible. A static inventory is a simple and straightforward way to define your managed nodes. It is typically a text file that lists all the hosts and their groupings.

Basic Structure

The most basic form of a static inventory is a plain text file that lists the hostnames or IP addresses of the target machines. Here is an example:

inventory.txt

192.168.1.10
192.168.1.11
192.168.1.12
                

Grouping Hosts

Hosts can be grouped together to apply tasks to specific sets of servers. Groups are defined by enclosing the group name in square brackets. Here is an example of grouping hosts:

inventory.txt

[webservers]
192.168.1.10
192.168.1.11

[dbservers]
192.168.1.12
                

Defining Variables

You can define variables for hosts and groups within the inventory file. These variables can be used in your playbooks. Here is an example:

inventory.txt

[webservers]
192.168.1.10 http_port=80
192.168.1.11 http_port=8080

[dbservers]
192.168.1.12 db_port=3306
                

Host Variables

In addition to defining variables inline, you can also define host-specific variables in a separate file. Create a directory named host_vars and place your variable files there. Here is an example:

host_vars/192.168.1.10

http_port: 80
                

host_vars/192.168.1.11

http_port: 8080
                

Group Variables

Similar to host variables, you can define group-specific variables in a group_vars directory. Here is an example:

group_vars/webservers

common_http_port: 80
                

Using the Inventory in Playbooks

Once your inventory is defined, you can use it in your Ansible playbooks. Here is an example of a simple playbook that uses the static inventory:

simple_playbook.yml

- hosts: webservers
  tasks:
    - name: Ensure Apache is installed
      yum:
        name: httpd
        state: present
                

Running the Playbook

To run the playbook with the static inventory, use the following command:

ansible-playbook -i inventory.txt simple_playbook.yml
                

Conclusion

Static inventories are a simple and effective way to define the hosts and groups for your Ansible automation. They are easy to set up and manage, making them ideal for small to medium-sized environments. With the knowledge of how to structure your inventory, define variables, and use them in playbooks, you can effectively manage your infrastructure using Ansible.