大网数据广告活动
服务器运维问答

Avoid repeating 'with_items' in Ansible role

· 52CE 我爱测

I've got an Ansible role with several tasks that I run for several virtual hosts. My playbook works, and it looks like this: --- - name: Create vhost configuration # action with_items: vhosts - name: Ensure vhost is enabled # act…

问题原文

原帖链接 · Andrew Moss · CC BY-SA 3.0

I've got an Ansible role with several tasks that I run for several virtual hosts. My playbook works, and it looks like this:

---

- name: Create vhost configuration
  # action
  with_items: vhosts

- name: Ensure vhost is enabled
  # action  
  notify: restart apache2
  with_items: vhosts

# (Many more actions)

Is there a way to avoid having to write with_items for every action? Can I iterate over the vhost items for the whole playbook rather than running each command for all vhosts sequentially? (as I am with the above code)

社区高分解答

原帖链接 · Bruce P · CC BY-SA 3.0

From what you're asking, it sounds like you just want to specify the vhosts group as the hosts to run a specific role on. So your playbook should start something like this:

---
- hosts: vhosts
  name: Tasks run on vhosts
  roles:
    - { role: somerole }

Keep in mind that you can have multiple plays in your playbook, so it's perfectly fine to do something like this:

---
- hosts: all
  name: Run roles for all servers
  roles:
    - { role: role1 }
    - { role: role2 }
    - etc.

- hosts: vhosts
  name: Run roles specific to vhosts
  roles:
    - { role: vhost-role }

- hosts: all
  name: Post-vhost roles for all servers
  roles:
    - { role: role3 }
    - etc.

If you have a single playbook that you want to run on different host groups at different times then you can use a variable for the hosts entry:

---
- hosts: "{{ somevar }}"
  name: Run roles against a user specified set of hosts
  roles:
    - { role: foo }

And then you'd invoke this last one in one of these ways:

$ ansible-playbook playbook.yml --extra-vars "somevar=vhosts"

$ ansible-playbook playbook.yml --extra-vars "somevar=host1,host2"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2014-10-25)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。