首页 > 解决方案 > 我尝试在 when 语句中使用“with_items”但失败了

问题描述

- hosts: 22rrvgndns01
  gather_facts: no
  vars_files:
    - /etc/ansible/dnschange/dns_resource_record.yml
  tasks:
- shell: grep "{{item.name}}" check_result.txt
    args:
      chdir: /cluster/dnschange
    when: "{{item.action}}" is match("delete")
    with_items: "{{resource_record}}"

这是资源记录:

- resource_record:
    - name: test.201.apn.epc.mnc002.mcc505.3gppnetwork.org
      record_type: naptr
      action: create
      view: MME
      ttl: 300
      order: 100
      preference: 999
      flags: s
      service: x-3gpp-pgw:x-gn:x-gp:x-s5-gtp
      replacement: wip-ows-pgw-e-NSW.node.epc.mnc002.mcc505.3gppnetwork.org

执行脚本时出现错误

违规行似乎是:

chdir: /cluster/dnschange
when: "{{item.action}}" is match("delete")
                        ^ here

我可能是错的,但这看起来可能是缺少引号的问题。当它们开始一个值时,总是引用模板表达式括号。例如:

with_items:
  - {{ foo }}

应该写成:

with_items:
  - "{{ foo }}"

谁能帮我吗?

标签: ansible

解决方案


我猜你的缩进是错误的,并且在什么情况下会改变。你可以尝试如下

- shell: grep "{{item.name}}" check_result.txt
  args:
    chdir: /cluster/dnschange
  when: item.action == 'delete'
  with_items: "{{resource_record}}"

推荐阅读