How do you define hosts in the inventory file?

076

In an Ansible inventory file, hosts can be defined in several ways, depending on the format used (INI or YAML). Here are examples of how to define hosts in both formats:

INI Format

In the INI format, you can define hosts directly under groups. Here's an example:

[webservers]
web1.example.com
web2.example.com

[databases]
db1.example.com
db2.example.com

[local]
localhost ansible_connection=local

YAML Format

In the YAML format, the inventory file is structured with more readability. Here's an example:

all:
  hosts:
    web1.example.com:
    web2.example.com:
  children:
    databases:
      hosts:
        db1.example.com:
        db2.example.com:
    local:
      hosts:
        localhost:
          ansible_connection: local

Key Points:

  • Groups: Hosts can be organized into groups (e.g., [webservers], [databases]), allowing you to apply tasks to multiple hosts at once.
  • Variables: You can assign variables to hosts or groups directly in the inventory file (e.g., ansible_connection=local for localhost).
  • Dynamic Inventory: You can also use dynamic inventory scripts to generate host lists from external sources, such as cloud providers.

By defining hosts in the inventory file, you enable Ansible to target specific machines for automation tasks effectively.

0 Comments

no data
Be the first to share your comment!