Ansible:当条件为with_items时

时间:2017-05-03 09:53:47

标签: ansible

我有一个剧本的一部分,工作正常:

- name: "Copy solrconfig.xml"
  copy:
    src: "{{role_path}}/files/{{item.path}}"
    dest: "{{solr_jmx_config}}/solrconfig.xml"
  with_items:
    - path: solrconfig_master.xml
  when: inventory_hostname == "{{ solr_master }}"
  become: yes
  become_user: solr

- name: "Copy solrconfig.xml"
  copy:
    src: "{{role_path}}/files/{{item.path}}"
    dest: "{{solr_jmx_config}}/solrconfig.xml"
  with_items:
    - path: solrconfig_slave.xml
  when: inventory_hostname != "{{ solr_master }}"
  become: yes
  become_user: solr

但是,我希望它看起来更好,并做类似的事情:

- name: "Copy solrconfig.xml"
  copy:
   src: "{{role_path}}/files/{{item.path}}"
   dest: "{{solr_jmx_config}}/solrconfig.xml"
  with_items:
   - path: solrconfig_master.xml -> when: inventory_hostname == "{{ solr_master }}"
   - path: solrconfig_slave.xml ->  when: inventory_hostname != "{{ solr_master }}"
  become: yes
  become_user: solr

如何为每个特定项目应用“何时”条件?

祝你好运, 马立克

1 个答案:

答案 0 :(得分:0)

为什么在这里需要with_itemsrole_path?试试这个:

- name: "Copy solrconfig.xml"
  copy:
    src: "{{ 'solrconfig_master.xml' if inventory_hostname == solr_master else 'solrconfig_slave.xml' }}"
    dest: "{{solr_jmx_config}}/solrconfig.xml"
  become: yes
  become_user: solr

with_通常用于循环,单个元素不需要它 在角色内部调用任务时,文件模块的搜索路径包括<role_path>/files/...