使用ansible中with_items的变量过滤主机

时间:2017-11-03 13:24:54

标签: amazon-ec2 ansible ansible-inventory

我为Ansible设置了以下内容,我想参数化一个将循环的过滤器,并过滤掉特定的主机。

- name: run on hosts
  hosts: "{{ item }}"

  roles: 
    - directory/role-name

  with_items:
    - us-east-1a
    - us-east-1b
    - us-east-1c

结果是名为role-name的角色首先在us-east-1a个主机上运行,​​然后us-east-1b等等。

上述简单错误

ERROR! 'with_items' is not a valid attribute for a Play

有没有办法完成我想要做的事情,即将我的主机列表分组成组,并对它们运行相同的角色,一次一个?

以下是我所寻求的结果,但是很笨重,而且不够动态。

- name: run on us-east-1a
  hosts: "us-east-1a"
  roles:
    - my-role


- name: run on us-east-1b
  hosts: "us-east-1b"
  roles:
    - my-role


- name: run on us-east-1c
  hosts: "us-east-1c"
  roles:
    - my-role

2 个答案:

答案 0 :(得分:2)

我认为(1)拥有公共代码和(2)每组主机的串行播放执行(组内并行运行目标)的唯一方法是将你的剧本分成两部分:

playbook-main.yml

---
- import_playbook: playbook-sub.yml
  vars:
    host_group_to_run: us-east-1a
- import_playbook: playbook-sub.yml
  vars:
    host_group_to_run: us-east-1b
- import_playbook: playbook-sub.yml
  vars:
    host_group_to_run: us-east-1c

playbook-sub.yml

- hosts: "{{ host_group_to_run }}"
  roles:
    - my-role

  # other common code

如果你想为每个主机进行序列化,那么serial declaration可以与this suggestion一起使用,但是尽管你有评论和编辑,但它还不清楚,因为一旦你提到us-east-1a以单数形式作为“主持人”,有时作为“主机组”或“可用区”。

答案 1 :(得分:0)

host patterns完成这项工作吗?:

- name: run on us-east-1a
  hosts: us-east-1a,us-east-1b,us-east-1c
  roles:
    - my-role

更新:@techraf以他的评论开启了我的眼睛 - 仅靠主持人的模式将无法完成这项工作 它将连接所有组中的所有主机 但是以可预测的方式,在某些情况下可以用来分别迭代每个组中的主机。
有关详细信息,请参阅this answer

相关问题