Ansible :如何在一个特定主机中运行角色



>我有一个剧本,它调用多个角色并在多个主机中执行它们:

我的剧本:

---
- 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'}

我的目的是:

我只想在本地主机/或特定的主机上运行第三个角色

我该怎么做??

曾尝试在该角色中为我的任务添加"hosts: localhost",但失败了,我也尝试了delegate_to: localhostlocal_action,但所有这些都失败了。

建议?

您需要列出清单文件中的所有主机,例如本地主机

[sandbox]
localhost    ansible_connection=local
other1.example.com    ansible_connection=ssh
other2.example.com    ansible_connection=ssh

然后在您的剧本中,您需要按索引引用本地主机,在我的例子中,本地主机的索引为 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]'}

因此,第三个角色将仅在本地主机上运行,其他角色将不会在本地主机上运行。

最新更新