【问题标题】:Ansible 2.8: Access a list object elementAnsible 2.8:访问列表对象元素
【发布时间】:2019-11-15 09:09:07
【问题描述】:

在 Ansible 2.8 中,我需要在 Ubuntu Server VM 上部署和配置 Bind 9 DNS。我有一个:

  1. DNS Ansible 角色进行安装和配置,
  2. 每个域区域的变量列表(如 DNS 记录类型、域名、dns 条目……)。直到这里,它才起作用,当我试图让它接受下一个要求时,问题就出现了:
  3. 可能会在同一个调用中配置多个域区域,因此,我向它发送了一个包含变量组的列表(在 2 中提到)。

现在,在 shell 中,我用 1 个元素列表调用它,使用:

--extra-vars "{"dns_entry_conf": 
     [domain=example.gal ip=192.168.167.166 
     nameserver1=example.gal nameserver1_ip=192.168.167.164 
     dns_record1_type=A ...]}"

在角色内部,roles/dns/tasks/configure.yml 文件接收到正确的值,但后面的文件没有:它说“列表对象没有属性”,我在 configure.yml 文件中开始调试,但我我不确定如何访问列表对象项:

---
- debug:
    msg: "{{dns_entry_conf}}"
- debug:
        msg: "{{dns_entry_conf | json_query(\"domain\") }}"

第一行打印它应该打印的内容,但第二行没有...我如何访问该值

ASK [dns : debug] **********************************************************************************
task path: /etc/ansible/roles/dns/tasks/configure.yml:2
ok: [ubuntuServer16_test] => {
    "msg": [
        "domain=example.gal ip=192.168.167.166 nameserver1=example.gal nameserver1_ip=192.168.167.164 
        dns_record1_type=A ...
    ]
}

TASK [dns : debug] **********************************************************************************
task path: /etc/ansible/roles/dns/tasks/configure.yml:4
ok: [ubuntuServer16_test] => {
    "msg": ""
}

在调试中,尝试使用 msg 的:"{{ dns_entry_conf.domain }}""{{ dns_entry_conf.0 }}""{{dns_entry_conf | json_query(\"domain\") }}""{{ dns_entry_conf.list | json_query('[*].domain') }}" 和其他语法错误的,但它永远不会输出我想要的。

可能还有更多错误的地方(我不是 Ansible 专家),但是,目前只是尝试一一调试和修复,所以,我只想知道如何访问“dns_entry_conf.域”项目,请...一些想法?

【问题讨论】:

    标签: ansible ansible-2.x


    【解决方案1】:

    选项1: 额外变量如下:

     --extra-vars '{"dns_entry_conf":{"domain":example,"ip":1.2.3.4}}'
    

    剧本:

      - debug:
         msg: "{{dns_entry_conf.domain}}"
    
    

    输出:

    好的:[本地主机] => { “味精”:“示例” }

    选项2
    额外的变量如下:

    --extra-vars '{"dns_entry_conf":["domain":example,"ip":1.2.3.4]}'
    

    在 Playbook 中如下:

      - debug:
         msg: "{{dns_entry_conf[0].domain}}"
    
    
    

    输出:

    好的:[本地主机] => { “味精”:“示例” }

    选项 3: 传递剧本中的变量。

      vars:
       dns_entry_conf:
        domain: example
        ip: 1.2.34.4
      tasks:
      - debug:
         msg: "{{dns_entry_conf.domain}}"
    

    输出:

    好的:[本地主机] => { “味精”:“示例” }

    【讨论】:

    • 选项 1 有效,谢谢。我还没有测试过第二个
    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 2013-06-22
    • 2014-10-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2017-04-23
    相关资源
    最近更新 更多