如何使用条件变量在一组特定主机上运行剧本
vars_file.yml
deployment: blue
hosts_file.yml
[east1]
127.0.0.1
127.0.0.2
[west2]
127.0.0.3
127.0.0.4
playbook.yml
---
hosts: all
vars_files:
- 'vars_file.yml'
tasks:
- copy: src=config dest=/tmp/
hosts: {{ east1[0] if deployment == "blue" else west2[0]}}
vars_files:
- 'vars_file.yml'
tasks:
- shell: "./startup_script restart"
注意:我不能通过命令行传递变量,我不能将任务隔离到一个新的剧本。
您可以通过针对另一台主机的hostvars
字典键来访问在该主机上定义的变量。
为了做到这一点,您需要在主机上注册变量,使用set_fact
,导入它是不够的。
下面是一个给定库存的例子:
all:
children:
east1:
hosts:
east_node_1:
ansible_host: node1
east_node_2:
ansible_host: node4
west2:
hosts:
west_node_1:
ansible_host: node2
west_node_2:
ansible_host: node3
和剧本:
- hosts: localhost
gather_facts: no
vars_files:
- vars_file.yml
tasks:
- set_fact:
deployment: "{{ deployment }}"
- hosts: >-
{{ groups['east1'][0]
if hostvars['localhost'].deployment == 'blue'
else groups['west2'][0]
}}
gather_facts: no
tasks:
- debug:
这将产生重播:
当vars_file。ymlPLAY [localhost] ******************************************************************************************************************* TASK [set_fact] ******************************************************************************************************************** ok: [localhost] PLAY [east_node_1] ***************************************************************************************************************** TASK [debug] *********************************************************************************************************************** ok: [east_node_1] => { "msg": "Hello world!" } PLAY RECAP ************************************************************************************************************************* east_node_1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
deployment: blue
- ,
当vars_file。ymlPLAY [localhost] ******************************************************************************************************************* TASK [set_fact] ******************************************************************************************************************** ok: [localhost] PLAY [west_node_1] ***************************************************************************************************************** TASK [debug] *********************************************************************************************************************** ok: [west_node_1] => { "msg": "Hello world!" } PLAY RECAP ************************************************************************************************************************* west_node_1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
deployment: red
另一个等效的结构,使用模式来瞄准组,只会看到主机目标更改为:
- hosts: >-
{{ 'east1[0]'
if hostvars['localhost'].deployment == 'blue'
else 'west2[0]'
}}