【问题标题】:Ansible Python API - Unable to load group varsAnsible Python API - 无法加载组变量
【发布时间】:2019-01-17 23:44:09
【问题描述】:

Ansible 版本:2.3.1.0

Python 版本:2.7.5

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

设置:

项目

 |_____ 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下定义的变量,定义在inventories/[DEV or QA]下

请帮助我加载这些多阶段环境变量。

【问题讨论】:

    标签: python ansible ansible-inventory


    【解决方案1】:

    我能够使用以下代码加载组变量。

    variable_manager.add_group_vars_file(groupvarfile, loader)
    

    【讨论】:

    • 我在 VariableManager 类中看不到 add_group_vars_file 并且它返回属性错误。我正在使用 ansible 2.9.6
    【解决方案2】:

    要访问 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
    

    希望对你有帮助,对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多