首页 > 解决方案 > Ansible 条件查找

问题描述

我有一本剧本,其中的任务如下所示。两者push_configimport_consul都没有通过,所以默认情况下有 false。

  - name: checkout config-tibco repository
      git:
        repo: ssh://git@bitbucket.corp.contingo.com:7999/gwa/config-tibco.git
        dest: "/opt/awx/tmp/config-tibco/"
      when: "{{ push_config | default(false) | bool }} or {{ import_consul | default(false) | bool }}"
...
....
.....

 - name: Update Consul KV Store
   shell: curl --request PUT -d "{{item.split('=',1) [1]}}" "http://{{ consul_host }}:{{ consul_port }}/v1/kv//TEST/{{ bw_application_name.stdout }}/{{ app_profile }}/{{item.split('=',1) [0]}}"
   loop: "{{ lookup('file', '/opt/awx/tmp/config-tibco/properties/*.properties').splitlines() }}"
   when: "{{ import_consul | default(false) | bool }}"

我期待第二个任务 -更新 Consul KV Store应该被简单地忽略,因为条件应该是错误的。第二个任务中预期的查找文件将仅在条件为真时下载/检出(即import_consul),因此它在第一个任务中从 GIT 检出并可供第二个任务使用。

但是我在查找文件方面遇到了异常。这里的问题是,当条件已经设置为 false 时,为什么还要尝试评估任务模块。

fatal: [host machine]: FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /opt/awx/tmp/config-tibco/properties/*.properties"}

有什么建议么?

标签: ansible

解决方案


问:原始消息:在查找中找不到文件:/opt/awx/tmp/config-tibco/properties/*.properties

答:when必须在每次迭代中评估条件,因为条件可能取决于item. 因此,loop必须在 之前评估when


笔记

  • 文件插件不适用于通配符。请改用fileglob

  • 为避免错误,请检查文件是否存在,如果文件不存在则终止播放。

  • 始终至少创建一个空文件default.properties

  • 条件(第when一个和第二个)将导致警告

[警告]:条件语句不应包含 jinja2 模板分隔符,例如 {{ }} 或 {% %}。找到:{{ import_consul|default(false)|bool }}

修复它(第一个同上)

when: import_consul|default(false)|bool

推荐阅读