我有一个剧本,它调用多个角色并在多个主机中执行它们:
我的剧本:
---
- hosts: all
gather_facts: true
vars:
- selected_APIS: "{{ RCD_APIS.split(',') }}"
pre_tasks:
- name : Display selected micro-services
run_once: true
debug:
msg: "{{selected_APIS}}"
roles:
- { role: pullDockerImages , when: '"PULL" in DEPL_MODE'}
- { role: stopDockerContainers , when: '"STOP" in DEPL_MODE'}
- { role: pullDockerConFiles , when: '"START" in DEPL_MODE'} // THIS ROLE
- { role: prepareDirectoriesTree , when: '"START" in DEPL_MODE'}
- { role: startDockerContainers , when: '"START" in DEPL_MODE'}
我的目的是:
我想仅在 localhost /或特定主机上运行第三个角色
我该怎么办?
我尝试将"hosts: localhost"
添加到我担任该角色的任务中,但是失败了,我也尝试了delegate_to: localhost
和local_action
,但所有失败都是。
建议?
答案 0 :(得分:1)
您需要列出库存文件中的所有主机,也需要列出localhost,例如
[sandbox]
localhost ansible_connection=local
other1.example.com ansible_connection=ssh
other2.example.com ansible_connection=ssh
然后在你的剧本中,你需要通过索引引用localhost,在我的情况下,localhost有一个索引0,这就是我们可以这样写的原因
---
- hosts: all
gather_facts: true
vars:
- selected_APIS: "{{ RCD_APIS.split(',') }}"
pre_tasks:
- name : Display selected micro-services
run_once: true
debug:
msg: "{{selected_APIS}}"
roles:
- { role: pullDockerImages , when: '"PULL" in DEPL_MODE and inventory_hostname != play_hosts[0]'}
- { role: stopDockerContainers , when: '"STOP" in DEPL_MODE and inventory_hostname != play_hosts[0]'}
- { role: pullDockerConFiles , when: '"START" in DEPL_MODE and inventory_hostname == play_hosts[0]'} // THIS ROLE
- { role: prepareDirectoriesTree , when: '"START" in DEPL_MODE and inventory_hostname != play_hosts[0]'}
- { role: startDockerContainers , when: '"START" in DEPL_MODE and inventory_hostname != play_hosts[0]'}
因此,第3个角色将仅在localhost上运行,其他角色不会在localhost上运行。