Ansible中国用户组QQ群: 142851673
简单测试ansible的when在include中使用
1、需求
用到一个配置需求,对hosts中不同类型的主机进行各自的操作。
(1)实验环境:
客户端IP | 应用类型 | Hosts中名称 |
192.168.24.10 | 数据库 | db |
192.168.24.11 | 应用程序 | app |
(2)操作结果:
192.168.24.10 服务器/tmp下生成db.txt,192.168.24.11服务器/tmp下生成app.txt文件
2、测试结构
# tree test/
test/
├── hosts
├── install_client.yml
└── roles
└──install_client
├── files
├── tasks
│ ├── app.yml
│ ├── db.yml
│ └── main.yml
├── templates
(1)hosts
[db]
192.168.24.10
[app]
192.168.24.11
(2)install_client.yml
---
###
## laowafang2014-12-1
####
- hosts: '` hosts `'
user: ansible
sudo: yes
sudo_user:root
roles:
-install_client
(3)roles/install_client/tasks/ main.yml # 本次测试的关键地方
---
### agentd install
- include: db.yml
when: "hosts == 'db'"
- include: app.yml
when: "hosts == 'app'"
(4)roles/install_client/tasks/db.yml
---
- name: Touchdb file
shell: touch /tmp/db.txt
(5)roles/install_client/tasks/app.yml
---
- name: Touchdb file
shell: touch /tmp/db.txt
3、测试playbook
# cd/etc/ansible/test
[ansible@localhosttest]$ ansible-playbook -i ./hosts install_client.yml --extra-vars "hosts=db"
PLAY [db]*********************************************************************
GATHERING FACTS***************************************************************
ok: [192.168.24.10]
TASK: [install_client | Touch db file]****************************************
changed: [192.168.24.10]
TASK: [install_client | Touch app]********************************************
skipping: [192.168.24.10]
PLAY RECAP ********************************************************************
192.168.24.10 : ok=2 changed=1 unreachable=0 failed=0
[ansible@localhosttest]$ ansible-playbook -i ./hosts install_client.yml --extra-vars "hosts=app"
PLAY [app] ********************************************************************
GATHERING FACTS***************************************************************
ok: [192.168.24.11]
TASK: [install_client | Touch db file]****************************************
skipping: [192.168.24.11]
TASK: [install_client | Touch app]********************************************
changed: [192.168.24.11]
PLAY RECAP********************************************************************
192.168.24.11 : ok=2 changed=1 unreachable=0 failed=0
### 查看对应服务器IP地址分别生成各自文件。
Ansible中国用户组QQ群: 142851673
转载于:https://blog.51cto.com/laowafang/1588759