【问题标题】:In ansible search test is there a way to test more than one value using a boolean OR operator?在 ansible 搜索测试中,有没有一种方法可以使用布尔 OR 运算符测试多个值?
【发布时间】:2021-07-16 21:27:48
【问题描述】:

我正在 ansible 版本 2.9 中处理 ansible playbook 任务,我有一个循环与 when 条件配对,我希望对两个值进行条件测试,而不仅仅是一个(这对我有用)。有没有办法在 when 语句中使用 search() 测试来执行布尔 OR?

这是我使用的有效方法(仅测试一个值):

- name: Test Interface Looping
  hosts: test
  vars:
    desc_search: "test"
    desc_search_c: "TEST"
  tasks:
    - name: IOS Facts
      ios_facts:
        gather_subset:
          - '!all'
          - '!min'
        gather_network_resources:
          - 'interfaces'
      register: result
    - debug: var=result
    - name: Update all descriptions
      ios_interfaces:
        config:
          - name: "{{ item.key }}"
            description: "Test Done"
        state: replaced
      loop: "{{ ansible_net_interfaces|dict2items }}"
      when: item.value.description is search(desc_search)

如果可能的话,这是我想做的事情(到目前为止还没有工作):

- name: Test Interface Looping
  hosts: test
  vars:
    desc_search: "test"
    desc_search_c: "TEST"
  tasks:
    - name: IOS Facts
      ios_facts:
        gather_subset:
          - '!all'
          - '!min'
        gather_network_resources:
          - 'interfaces'
      register: result
    - debug: var=result
    - name: Update all descriptions
      ios_interfaces:
        config:
          - name: "{{ item.key }}"
            description: "Test Done"
        state: replaced
      loop: "{{ ansible_net_interfaces|dict2items }}"
      when: item.value.description is search(desc_search) or search(desc_search_c)

我也尝试在when 语句的末尾添加| bool,但在这两种情况下我都会收到错误:The conditional check 'item.value.description is search(desc_search) or search(desc_search_c)' failed. The error was: error while evaluating conditional (item.value.description is search(desc_search) or search(desc_search_c)): 'search' is undefined...

有可能做我想做的事情吗?对于我可能使用的任何不正确的术语,我深表歉意。我是一名网络工程师,因此没有接受过 ansible 或编程/脚本方面的正式教育。

【问题讨论】:

    标签: ansible cisco cisco-ios


    【解决方案1】:

    您的问题有 3 个答案,从您收到的错误开始:search is not a jinja2 "filter" it's a "test",这意味着它必须与 isis not 关键字一起使用(正如你在when 的前半部分所做的那样):

          when: item.value.description is search(desc_search) or item.value.description is search(desc_search_c)
    

    第二个答案是,由于您关心的似乎是不区分大小写的搜索,您可以通过 (?i) regex modifier, or the ignorecase=True kwarg 指定它

          when: item.value.description is search(desc_search, ignorecase=True)
    

    作为替代方案,如果您真的只想要 testTEST(这意味着我对 ignorecase 的假设是错误的),并且您确实关心这种情况,但只想要这两个字符串,您可以使用| 正则表达式替换字符:

          when: item.value.description is search(desc_search+"|"+desc_search_c)
    

    就像编程中的很多事情一样,有很多方法可以实现这个目标,你应该选择最容易让你和你的团队在下个月查看这段代码时推理的方法 :-)

    【讨论】:

    • 谢谢!我认为这将满足我在这里的需要。感谢详细且内容丰富的回复!
    • 如果您发现确实如此,请考虑将答案标记为已接受,让其他人知道它解决了您的问题。祝你好运!
    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多