ansible - 通过剧本根据主机运行不同的任务

标签 ansible

我对 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

最佳答案

一种方法是在您的库存中使用变量:

[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
...

关于ansible - 通过剧本根据主机运行不同的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29014124/

相关文章:

ansible - 如何使用 Ansible 或 Jinja2 转义变量名中的冒号 (":")?

Ansible 将 Python 脚本读取为 JSON

ssh - Ansible:当包版本大于或等于时执行某些操作

list - 如何在 Ansible 中连接两个字典列表

kubernetes - Ansible - 迭代项目并在值不存在时执行任务

无法从外部主机访问 Docker 部署的镜像

jquery - 使用 Jquery (jmespath) 从 Ansible 获取 API 调用

regex - 在 Ansible 中提取 {{ inventory_hostname }} 的一部分以在 playbook 中使用

Ansible - 按照我的意愿与主机一起玩

ansible - 从远程服务器复制文件并使用 ansible 替换字符串