我有主机,我可以在其中在单节点架构或分布式架构上设置应用程序。
所以我有一个库存。
[STG]
node1
[LIVE]
app_node
db_node
gateway_node
因此,默认值是的变量single
可以在 CLI 上更改为distributed
。
我有一个角色定义
- hosts:
gather_facts: no
roles:
- {role: setup, tags: ['setup', 'orchestra']}
所以我希望主机线根据地图值是动态的
- hosts: 'if single then host == STG else LIVE'
答案1
还有更多选择:
- 将逻辑代入表达式主持人:
shell> cat pb.yml
- hosts: "{{ (map_value == 'single')|ternary('STG', 'LIVE') }}"
tasks:
- debug:
var: ansible_play_hosts
run_once: true
给你想要的
shell> ansible-playbook pb.yml -e map_value=single
PLAY [single] ********************************************************************************
TASK [debug] *********************************************************************************
ok: [node1] =>
ansible_play_hosts:
- node1
PLAY RECAP ***********************************************************************************
node1: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
shell> ansible-playbook pb.yml -e map_value=distributed
PLAY [distributed] ***************************************************************************
TASK [debug] *********************************************************************************
ok: [app_node] =>
ansible_play_hosts:
- app_node
- db_node
- gateway_node
PLAY RECAP ***********************************************************************************
app_node: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
- 创造孩子们(组别名)
shell> cat hosts
[STG]
node1
[single:children]
STG
[LIVE]
app_node
db_node
gateway_node
[distributed:children]
LIVE
然后,剧本给出了相同的结果
shell> cat pb.yml
- hosts: "{{ map_value }}"
tasks:
- debug:
var: ansible_play_hosts
run_once: true
如果您无法更改库存文件,请将别名放入单独的文件中。例如,
shell> tree inventory/
inventory/
├── 01-hosts
└── 02-aliases
shell> cat inventory/01-hosts
[STG]
node1
[LIVE]
app_node
db_node
gateway_node
shell> cat inventory/02-aliases
[single:children]
STG
[distributed:children]
LIVE
然后,剧本给出了相同的结果
shell> ansible-playbook -i inventory pb.yml -e map_value=single
...
shell> ansible-playbook -i inventory pb.yml -e map_value=distributed
...
- 使用库存插件建。看
shell> ansible-doc -t inventory constructed
例如,库存
shell> tree inventory
inventory
├── 01-hosts
└── 02-constructed.yml
shell> cat inventory/01-hosts
[STG]
node1
[STG:vars]
map_group_value=single
[LIVE]
app_node
db_node
gateway_node
[LIVE:vars]
map_group_value=distributed
shell> cat inventory/02-constructed.yml
plugin: constructed
use_extra_vars: true
compose:
map_group: map_value
groups:
map_group: map_group == map_group_value
然后,剧本
- hosts: map_group
tasks:
- debug:
var: ansible_play_hosts
run_once: true
给出相同的结果
shell> ansible-playbook -i inventory pb.yml -e map_value=single
...
shell> ansible-playbook -i inventory pb.yml -e map_value=distributed
...
如果您坚持使用角色测试用例,请创建一个角色
shell> cat roles/setup/tasks/main.yml
- debug:
var: ansible_play_hosts
run_once: true
并在剧本中将其与您喜欢的任何标签一起使用
shell> cat pb.yml
- hosts: map_group
roles:
- role: setup