我有一个 ansible 变量定义,想知道是否可以根据运行时定义的变量获取变量值
vars:
test:
user: ""
dirs:
base: ""
logs: ""
libs: ""
region:
- name: debug
debug:
msg: "{{ newvar }}"
ansible-playbook playbook.yml -e "newvar=test"
上述执行应该打印“测试”变量中定义的所有值。
答案1
我将在 yaml 中使用关联数组。
剧本.yml
- hosts: localhost
gather_facts: false
vars:
my_environments:
test:
user: "user_test"
dirs:
base: "/x"
logs: "/y"
libs: "/z"
region:
prod:
user: "user_prod"
dirs:
base: "/a"
logs: "/b"
libs: "/c"
region:
tasks:
- name: debug
debug:
msg: "{{ my_environments[newvar] }} "
你可以用以下方法运行它:
ansible-playbook -ilocalhost, playbook.yml -e "newvar=test"
答案2
尝试查找瓦尔斯
- name: debug
debug:
msg: "{{ lookup('vars', newvar) }}"