根据主机通过playbook运行不同的任务

时间:2015-03-12 15:40:35

标签: ansible ansible-playbook

我对ansible很新,如果这是一个明显的问题,请保持温和。我有一个剧本,用于在安装后执行CentOS系统的初始配置/强化。我有3组不同的服务器,它们都以大致相同的方式配置,配置文件只有一些差异。特别是,每组服务器都需要获得自己独特的iptables配置。如何使用单个playbook将iptables1发送到hostgroup1,将iptables2发送到hostgroup2,将iptables3发送到hostgroup3,并仍在每个服务器上运行所有其他任务?

---
 - name: Initial OS configuration
   hosts: all
   remote_user: myuser
   sudo: yes
   tasks:
    - name: Deploy sshd_config
      copy: src=/opt/ansible/files/sshd_config dest=/etc/ssh/sshd_config owner=root group=root mode=600
      register: sshd

    - name: Restart sshd service
      service: name=sshd state=restarted
      when: sshd.changed

    # HELP HERE
    - name: Deploy iptables
      copy: src=/opt/ansible/files/iptables1 dest=/etc/sysconfig/iptables owner=root group=root mode=600
      register: iptables

    - name: Restart iptables service
      service: name=iptables state=restarted
      when: iptables.changed

    - name: Set bash history timestamp
      copy: src=/opt/ansible/files/history.sh dest=/etc/profile.d/history.sh mode=644 owner=root group=root

    - name: Install screen
      yum: name=screen state=latest

2 个答案:

答案 0 :(得分:1)

一种方法是在您的广告资源中使用变量:

[group1:vars]
iptable_path=/opt/ansible/files/iptables1

[group2:vars]
iptable_path=/opt/ansible/files/iptables2

[group3:vars]
iptable_path=/opt/ansible/files/iptables3

然后,在剧本中:

...
- name: Deploy iptables
  copy: src={{ iptable_path }} dest=/etc/sysconfig/iptables owner=root group=root mode=600
  register: iptables
...

答案 1 :(得分:1)

这是我最终得到的,使用来自0xFC的“group_names”建议:

---
 - name: Initial OS configuration
   hosts: all
   remote_user: myuser
   sudo: yes
   tasks:

    ...

    - name: Deploy iptables to group1
      copy: src=/opt/ansible/files/iptables1 dest=/etc/sysconfig/iptables owner=root group=root mode=600
      register: iptables
      when: "'group1' in group_names"

    - name: Deploy iptables to group2
      copy: src=/opt/ansible/files/iptables2 dest=/etc/sysconfig/iptables owner=root group=root mode=600
      register: iptables
      when: "'group2' in group_names"

    - name: Deploy iptables to group3
      copy: src=/opt/ansible/files/iptables3 dest=/etc/sysconfig/iptables owner=root group=root mode=600
      register: iptables
      when: "'group3' in group_names"

    - name: Restart iptables service
      service: name=iptables state=restarted
      when: iptables.changed

    ...