【问题标题】:How to check whether an item is present in an Ansible array?如何检查一个项目是否存在于 Ansible 数组中?
【发布时间】:2015-03-20 07:12:12
【问题描述】:

假设我有以下示例,将所有 git config 值存储在 Ansible 变量中:

- shell: git config --global --list
  register: git_config_list

Ansible 将此命令的结果存储在 git_config_list 变量中,其中一项是 stdout_lines,其中包含条目数组中的命令输出,例如

[
"user.name=Foo Bar",
"user.email=foo@example.com"
]

如何检查是否已经设置了某个值,例如用于验证user.name 是否有值?

有没有办法在数组上调用contains 之类的东西,结合正则表达式,让我找到我正在寻找的值?还是我必须遍历 stdout_lines 条目才能找到我要查找的内容?

将不胜感激提供有关如何执行此类操作的示例。

【问题讨论】:

    标签: ansible


    【解决方案1】:

    简单的python in 就可以了,注意我使用stdout 而不是stdout_lines

    - debug: git_config_list contains user.name
      when: "'user.name=' in '{{git_config_list.stdout}}'"
    

    总之ansible 对编程来说太可怕了。尝试在剧本之外尽可能多地做,并且只在剧本中编写编排逻辑。以下是一些示例,您可以如何使用git--get 选项来做到这一点。

    - hosts: localhost
      tags: so
      gather_facts: False
      tasks:
      - shell: git config --global --get user.name
        register: g
        changed_when: False
        failed_when: False
      - debug: msg="config has user.name"
        when: "0 == {{g.rc}}"
    
    - hosts: localhost
      tags: so
      gather_facts: False
      tasks:
      - name: assert user.name is set
        shell: git config --global --get user.name
        changed_when: False
    
    # git config --global --unset user.name
    # ansible pb.yml -t so
    # git config --global --add user.name 'Kashyap Bhatt'
    # ansible pb.yml -t so
    

    【讨论】:

      【解决方案2】:

      理论上,这应该可以通过组合过滤器matchselect 来实现。后者仅返回那些通过另一个过滤器的列表元素。然后你可以测试结果的长度。

      理论上。我刚刚对其进行了测试,但无法使其正常工作。通常select(以及reject)过滤器会返回一个类似<generator object _select_or_reject at 0x10531bc80> 的字符串,即使使用简单的过滤器(例如文档中的odd 示例)也是如此。还没有找到解决办法。也许你会取得更大的成功。

      虽然您可以简单地将join 列表转换为字符串,然后使用match 在字符串中搜索。虽然它很丑,但它确实有效。

      git_config_list.stdout_lines | join("|") | match("user.name=[^|]+")
      

      【讨论】:

      • select 中的字符串可以使用列表过滤器转换为列表:| list
      【解决方案3】:

      使用选择和匹配(乌冬面的扩展答案):

      git_config_list.stdout_lines | select('match', 'user\.name=.+') | list
      

      【讨论】:

        猜你喜欢
        • 2021-10-26
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        • 2011-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-11
        相关资源
        最近更新 更多