0
votes

Ansible Version : 2.3.1.0

Python Version : 2.7.5

Command : ansible-playbook -i inventories/DEV/ playbooks/patching.yml -e "ticketnum=12345 perform_action=stop ansible_ssh_user=abc" -k

Setup:

project

 |_____ pythonengine

            |______ engine.py

 |_____ playbooks

            |_____ patching.yml

 |_____ inventories

            |_____ DEV
                    |____hosts
                    |____group_vars
                             |____all
                                    |___ all.yml
                    |____host_vars
                             |____host1
                                    |___ all.yml
            |_____ QA
                    |____hosts
                    |____group_vars
                             |____all
                                    |___ all.yml
                    |____host_vars
                             |____host2
                                    |___ all.yml

The playbook executes perfectly fine, As part of automation while calling the playbook from Python API [ engine.py ], Its unable to get the variables defined under group_vars and host_vars.

here is the code :

def runPlaybook(self, playbookYML, hostfile, remoteUser, remoteUserpwd, ticketnum, patchAction, envt):
    try:
        loader = Dataloader()
        inventory = Inventory(loader=loader, variable_manager=VariableManager(), host_list=hostfile)
        variable_manager = VariableManager()
        variable_manager.extra_vars = { 'ticketnum': ticketnum, 'perform_action': patchAction, 'ansible_ssh_user': remoteUser }
        options = namedtuple('Options', ['listtags','listtasks', 'listhosts', 'syntax', 'connection', 'module_path', 'fork', 'remote_user', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'verbosity', 'check', 'diff', 'become', 'become_method','become_user'])
        options = Options(listtags=False,listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, fork=100, remote_user=remoteUser, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, verbosity=None, check=False, diff=False, become=False, become_method=sudo,become_user=remoteUser)
        passwords = {'conn_pass': remoteUserPwd}
        pbex = PlaybookExecutor(playbook=[playbookYML], inventory=inventory, variable_manager=variable_manager, loader=loader, option=options, passwords=passwords)
        results = pbex.run
   except Exception as e:
       logger.error(traceback.print_exc())
       raise

The above code is failing to get the variables defined under group_vars and host_vars, defined under the inventories/[DEV or QA ]

Please help me in getting these multi stage environment variables to get loaded.

2

2 Answers

0
votes

I was able to load the group vars with the below code.

variable_manager.add_group_vars_file(groupvarfile, loader)
0
votes

To access the variables of a host defined in a group in the Ansible inventory file, you must do it in the following way.

File: inventory.ini

[all]
host_00 ansible_host=00.01.02.03 custom_variable=aaa
host_01 ansible_host=04.05.06.07 custom_variable=bbb
host_02 ansible_host=08.09.10.11 custom_variable=ccc
host_03 ansible_host=12.13.14.15 custom_variable=ddd
host_04 ansible_host=16.17.18.19 custom_variable=eee
host_05 ansible_host=20.21.22.23 custom_variable=fff
host_06 ansible_host=24.25.26.27 custom_variable=ggg

[group-one]
host_00
host_01

[group-two]
host_02
host_03
host_04

[group-three]
host_05
host_06

File: test.py

from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager

# Set inventory filename.
inventoryFile = 'inventory.ini'

# Set groups of interest.
groups = ['group-one', 'group-three']

# Use ansible module for Python 3.
loader = DataLoader()
inventory = InventoryManager(loader=loader, sources=inventoryFile)

for group in groups:

    # Set hosts list.
    hostsList = inventory.groups[group].get_hosts()

    for host in hostsList:

        # If you want to print all host attributes you can do this:
        # print(host.__dict__)

        # Set some variables for each host from inventory.
        name            = host.name
        inGroups        = host.groups
        ansible_host    = host.vars['ansible_host']
        custom_variable = host.vars['custom_variable']

        print('name = {}, inGroups = {}, ansible_host = {}, custom_variable = {}'.format(name, inGroups, ansible_host, custom_variable))

Output:

name = host_00, inGroups = [all, group-one], ansible_host = 00.01.02.03, custom_variable = aaa
name = host_01, inGroups = [all, group-one], ansible_host = 04.05.06.07, custom_variable = bbb
name = host_05, inGroups = [all, group-three], ansible_host = 20.21.22.23, custom_variable = fff
name = host_06, inGroups = [all, group-three], ansible_host = 24.25.26.27, custom_variable = ggg

I hope it helps you, it works for me.