仅在一台服务器上运行Ansible任务-AWS

时间:2020-08-10 10:43:05

标签: amazon-web-services ansible

我的ansible任务在所有api_servers中运行,因此我将其限制为仅在一个IP(api_server之一)上运行 我添加了run_once:true,但没有帮助。

请告知。 编辑:

以下内容会起作用吗?我有10个app_servers实例在运行,我希望任务仅在一台app_server上运行

run_once: true
when:
    - inventory_hostname == groups['app_servers'][0]

我的库存文件在哪里

[app_servers]
prod_app_[1:4]

2 个答案:

答案 0 :(得分:2)

我会这样写我的剧本:

 ---
 # Run on all api_servers
 - hosts: api_servers
   tasks:
   - name: do something on all api_servers
     #...

 # Run only on one api_server e.q. api_server_01
 - hosts: api_server_01
   tasks:
   - name: Gather data from api_server_01 
     #...

另一种选择是使用when:或使用--limit选项运行剧本

---
- hosts: all
  tasks:
  - name: do something only when on api_server_01
    #...
    when: inventory_hostname == "api_server_01"

编辑: 在一个示例中,您将看到所有选项:

---
- hosts: all
  tasks:
  - debug: msg="run_once"
    run_once: true
  - debug: msg=all
  - debug: msg="run on the first of the group"
    when: inventory_hostname == groups['app_servers'][0]

# Option with separated hosts, this one will be faster if gather_facts is not tuned.
- hosts: app_servers[0]
  tasks:
  - debug: msg="run on the first of the group"

答案 1 :(得分:0)

(由于我无法发表评论,所以我必须回答。)

delegate_to呢?将任务委派给特定主机的位置。

  hosts: all
  tasks:
    - name: Install vim on specific host 
      package:
        name: vim
        state: present
      delegate_to: staging_machine

如@ user2599522所述:--limit也可以使用:

您还可以使用--limit标志来限制特定运行中的目标主机。 (Patterns and ansible-playbook flags)