1

How do I call the particular host and group for that inventory file?

Example: main.yml

hosts: group
roles:
  - java_installation

My usage:

ansible-playbook inventory main.yml

I don't want to add the host inside the main.yml host and group should decided at run time.
How to pass the input to this example_inventory()? Is it possible to pass inventory when I am running the ansible-playbook inventory main.yml ?
Ex: In database for group have 5 server. But I want to pick single server form the group and ran the roles

[group]
10.2.3.4.
10.2.3.5

I want to run the role in 10.2.3.5 Can you please help me on that. Sorry if there is problem on my communication.

Example code:

#!/usr/bin/env python

'''
Example custom dynamic inventory
'''

import os
import sys
import argparse

try:
    import json
except ImportError:
    import simplejson as json

class ExampleInventory(object):

    def __init__(self):
        self.inventory = {}
        self.read_cli_args()

        # Called with `--list`.
        if self.args.list:
            self.inventory = self.example_inventory()
        # Called with `--host [hostname]`.
        elif self.args.host:
            # Not implemented, since we return _meta info `--list`.
            self.inventory = self.empty_inventory()
        # If no groups or vars are present, return an empty inventory.
        else:
            self.inventory = self.empty_inventory()

        print json.dumps(self.inventory);

    # Example inventory for testing.
    def example_inventory(self):
        my_array = ['xx.xx.xxx', 'xx.xx.xxx']
        return {
            'group': {
                'hosts': my_array,
                'vars': {
                    'ansible_ssh_user': 'username'
                }

            },
            '_meta': {
                'hostvars': {
                    'xx.xx.xxx': {
                        'ansible_ssh_pass':'password'
                    },
                    'xx.xxx.xx': {
                        'ansible_ssh_pass':'password'
                    }
                }
            }
        }

    # Empty inventory for testing.
    def empty_inventory(self):
        return {'_meta': {'hostvars': {}}}

    # Read the command line args passed to the script.
    def read_cli_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('--list', action = 'store_true')
        parser.add_argument('--host', action = 'store')
        self.args = parser.parse_args()

# Get the inventory.
ExampleInventory()
Alexey Vazhnov
  • 1,291
  • 17
  • 20
pavan
  • 11
  • 1
  • 1
    Possible duplicate of [Safely limiting Ansible playbooks to a single machine?](https://stackoverflow.com/questions/18195142/safely-limiting-ansible-playbooks-to-a-single-machine) – Konstantin Suvorov Jul 06 '17 at 13:44
  • I am looking through coding. I need to add the host entry at run time in the inventory python code. which i added in description. – pavan Jul 11 '17 at 06:35

0 Answers0