Skip to content
profile for CodeWizard at Stack Overflow, Q&A for professional and enthusiast programmers ![Visitor Badge](https://visitor-badge.laobi.icu/badge?page_id=nirgeier) [![Linkedin Badge](https://img.shields.io/badge/-nirgeier-blue?style=flat&logo=Linkedin&logoColor=white&link=https://www.linkedin.com/in/nirgeier/)](https://www.linkedin.com/in/nirgeier/) [![Gmail Badge](https://img.shields.io/badge/-nirgeier@gmail.com-fcc624?style=flat&logo=Gmail&logoColor=red&link=mailto:nirgeier@gmail.com)](mailto:nirgeier@gmail.com) [![Outlook Badge](https://img.shields.io/badge/-nirg@codewizard.co.il-fcc624?style=flat&logo=microsoftoutlook&logoColor=blue&link=mailto:nirg@codewizard.co.il)](mailto:nirg@codewizard.co.il) discord contributors license Pull Requests If you appreciate the effort, Please this project

Lab 002 - No inventory example

01. “Clear” the inventory

  • Lets clear the inventory from previous steps and walk thorough what is inventory

01.01. Create the inventory file

Ansible Inventory

  • An Ansible inventory is a file or collection of files that defines the [hosts] and [groups] of hosts upon which Ansible will operates.
  • It’s simply a list of servers that Ansible can connect to and manage.

Key features of Ansible inventory

  • Can be in various formats, with INI, JSON, YAML and more.
  • YAML is the most common format
  • inventory defines the target hosts for playbook execution
  • inventory organizes hosts into logical groups for easier management
  • inventory can store host-specific variables and group variables
  • inventory supports nested groups (groups of groups)

    inventory samples

    • INI format
      [webservers]
      web1.example.com
      web2.example.com
      
      [database]
      db1.example.com
      
    • YAML format
      all:
          hosts:
              web1.example.com:
              web2.example.com:
          children:
              database:
              hosts:
                  db1.example.com:
      
    • JSON format
      {
      "all": {
          "hosts": {
          "web1.example.com": {
              "ansible_port": 2222,
              "http_port": 80
          },
          "web2.example.com": {
              "ansible_port": 2223,
              "http_port": 8080
          }
          },
          "children": {
          "database": {
              "hosts": [
              "db1.example.com"
              ]
            }
          }
        }
      }
      

inventory types in Ansible

  1. Static Inventory

    • This is generally a simple text file (usually in INI or YAML format) that lists your hosts and their corresponding groups.
  2. Dynamic Inventory

    • This is generated by a script or a program that retrieves host information from an external source, such as cloud providers (like AWS, Azure, etc.), LDAP, or a database.
    • This allows for real-time updates and adaptability as environments change.

      • Example of generating Dynamic inventory using python code fetching data form datable
        #!/usr/bin/env python
        import sqlite3
        import json
        
        def get_inventory():
            conn = sqlite3.connect('servers.db')
            cursor = conn.cursor()
        
            cursor.execute('SELECT hostname, group_name, ansible_user FROM servers')
            rows = cursor.fetchall()
        
            inventory = {'all': {'hosts': [], 'vars': {}}}
        
            for row in rows:
                hostname, group_name, ansible_user = row
        
                if group_name not in inventory:
                    inventory[group_name] = {'hosts': [], 'vars': {}}
        
                inventory['all']['hosts'].append(hostname)
                inventory[group_name]['hosts'].append(hostname)
                inventory[group_name]['vars']['ansible_user'] = ansible_user
        
            conn.close()
            return inventory
        
        if __name__ == "__main__":
            print(json.dumps(get_inventory()))
        

Lab

  • Lets create the inventory configuration we will use for the labs:

    ### File Location: $RUNTIME_FOLDER/labs-scripts/inventory
    ###
    ### List of servers which we want ansible to connect to
    ### The names are defined in the docker-compose
    ###
    
    [servers]
    # No server will be defined at this step
    

01. No inventory invocation

  • Once all is ready lets check is the controller can connect to the servers with the using ping

    # Ping the servers and check that they are "alive"
    docker exec ansible-controller sh -c "cd /labs-scripts && ansible all -m ping"
    
    ## Output
    ## -------------------------------------------------------------------------------
    [WARNING]: provided hosts list is empty, only localhost is available. Note that
    the implicit localhost does not match 'all'
    

02. inventory invocation

  • Fill in the inventory based upon the prevoius labs configuration and test it.
  • Verify that the inventory is defined correctly with:
    ansible-inventory -i <inventory_file> --graph
    
  • Test the inventory file with
    ansible -i <inventory_file> -m ping
    
  • Suggested Solution

    ###
    ### List of servers which we want ansible to connect to
    ### The names are defined in the docker-compose
    ###
    
    [servers]
      linux-server-1 ansible_ssh_common_args='-o UserKnownHostsFile=/root/.ssh/known_hosts'
      linux-server-2 ansible_ssh_common_args='-o UserKnownHostsFile=/root/.ssh/known_hosts'
      linux-server-3 ansible_ssh_common_args='-o UserKnownHostsFile=/root/.ssh/known_hosts'
    


:arrow_backward: /Labs/001-verify-ansibleBack to labs list/Labs/003-modules :arrow_forward: