【问题标题】:Ansible looping over nested variables嵌套变量的 Ansible 循环
【发布时间】:2016-05-22 13:58:15
【问题描述】:

我有一组定义 FQDN 的变量。

domains:
  - erp: erp.mycompany.com
  - crm: crm.mycompany.com
  - git: git.mycompany.com

确实,我都需要遍历它们并访问它们(在模板文件中)。所以像domains.erp那样访问它们就像一个魅力。但是我无法遍历这些。

显然,如果我这样做:

- name: Print domains
  debug:
    msg: test {{ item }}
  with_items:
    - "{{ domains }}"

它会打印键和值……如果我这样做:

- name: Print domains
  debug:
    msg: test {{ domains[{{ item }}] }}
  with_items:
    - "{{ domain }}"

但这不起作用。我还尝试了文档中提到的hashes form,但也没有运气……

【问题讨论】:

  • Ansible 的嵌套列表似乎相当复杂,请在此处查看我的问题:stackoverflow.com/questions/36206551/…。也许剧本不应该被过度设计,或者你应该实现一些自定义插件,因为语法变得非常讨厌。

标签: loops variables ansible


【解决方案1】:

最后,我不得不使用字典。

第一次没有成功,因为与 with_items 不同,with_dict 是一个没有 - 在循环元素之前的单行。

domains:
  erp:
    address: erp.mycompany.com
  crm:
    address: crm.mycompany.com
  git:
    address: git.mycompany.com

# used by letsencrypt
webserverType: apache2
withCerts: true

tasks:

- name: Print phone records
  debug:
    msg: "{{ item.value.address }}"
  with_dict: "{{ domains }}"

# I can still access a given domain by its name when needed like so:
{{ domains.erp.address }}

【讨论】:

    【解决方案2】:

    看来您已经解决了问题。您最初的尝试使用了不包含相同键的字典列表,因此难以在每个列表项中统一访问值。

    您的第二个解决方案创建一个字典,其中的键引用其他字典。

    如果您仍想使用列表,则不是您发布的其他解决方案:

        - hosts: localhost
          vars:
            domains:
              - name: erp
                address: erp.mycompany.com
              - name: crm
                address: crm.mycompany.com
              - name: git
                address: git.mycompany.com
          tasks:
            - name: Print phone records
              debug:
                msg: "{{ item.address }}"
              with_items: "{{ domains }}"
    

    对我来说,这种方法更简单,但您的第二种方法也适用。

    【讨论】:

    • 谢谢你的答案。然而,使用这种方法,我似乎无法按名称引用我的域。如果在我的剧本的其他部分,我需要例如访问 erp 的域名,我该如何解决? domains.0.address 真的很容易出错。
    • 啊,你是对的。我误解了你的用例。如果您需要单独获取域项而不是循环遍历它们,那么您的方法可能是最可靠的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多