DevOps Classroom Series – 24/Oct/2021

Ansible Dynamic Inventory

  • Ansible Dynamic inventory is a script in any language which when called with argument
    • –list: should return something like
      {
          "group001": {
              "hosts": ["host001", "host002"],
              "vars": {
                  "var1": true
              },
              "children": ["group002"]
          },
          "group002": {
              "hosts": ["host003","host004"],
              "vars": {
                  "var2": 500
              },
              "children":[]
          },
          "_meta": {
              "hostvars": {
    
              }
          }
    
      }
    
    • –host <hostname>: should return
      {
          "VAR001": "VALUE",
          "VAR002": "VALUE",
      }
    
  • So look into this example for dummy inventory
#!/usr/bin/env python3
import os
import sys
import argparse
import json


def read_cli_args():
    """
    This method is used to read the command line args

    Returns
        args
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("--list", action='store_true')
    parser.add_argument("--host", action='store')
    args = parser.parse_args()
    return args

def example_list():
    """
    This method will return the example list
    """
    return {
        'group': {
            'hosts': ['localhost', '172.31.17.152', '172.31.29.133'],
            'vars': {
                'message': 'hello'
            }
        },
        '_meta': {
            'hostvars': {}
        }
    }

def empty_inventory():
    return { '_meta': { 'hostvars': {} }}

if __name__ == '__main__':
    args = read_cli_args()
    if args.list:
        print(json.dumps(example_list()))
    else:
        print(json.dumps(empty_inventory()))
  • Ansible expects inventory to be executable file.

Ansible Parallelism

  • Ansible establishes parallel connection with node which is called as fork.
  • By default ansible uses 5 forks
  • We can set the default number of forks in /etc/ansible/ansible.cfg file
[defaults]
forks = 50
  • We can also set number of forks by passing -f with ansible-playbook and ansible command line
ansible-playbook -i hosts play.yml -f 100
ansible -f 1 -m ping all

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Please turn AdBlock off
Floating Social Media Icons by Acurax Wordpress Designers

Discover more from Direct DevOps from Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading

Visit Us On FacebookVisit Us On LinkedinVisit Us On Youtube