Ansible Python API - Невозможно загрузить групповые переменные - PullRequest
0 голосов
/ 02 октября 2018

Ansible Версия: 2.3.1.0

Версия Python: 2.7.5

Команда: ansible-playbook -i инвентаризация / DEV / playbooks / patching.yml -e "ticketnum = 12345 execute_action= stop ansible_ssh_user = abc "-k

Настройка:

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

Книга воспроизведения прекрасно работает, как часть автоматизации, при вызове книги воспроизведения из Python API [engine.py], он не может получить переменные, определенные в group_vars и host_vars.

вот код:

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

Приведенный выше код не может получить переменные, определенные в group_vars и host_vars, определенные в описи / [DEV или QA]

Пожалуйста, помогите мне загрузить эти многоступенчатые переменные среды.

Ответы [ 2 ]

0 голосов
/ 17 января 2019

Чтобы получить доступ к переменным хоста, определенного в группе в файле инвентаризации Ansible, вы должны сделать это следующим образом.

Файл: 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

Файл: 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))

Вывод:

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

Надеюсь, это поможет вам, это работаетдля меня.

0 голосов
/ 05 октября 2018

Мне удалось загрузить групповые переменные с помощью приведенного ниже кода.

variable_manager.add_group_vars_file(groupvarfile, loader)
...