![ansible 从另一个变量构造变量名](https://linux22.com/image/750770/ansible%20%E4%BB%8E%E5%8F%A6%E4%B8%80%E4%B8%AA%E5%8F%98%E9%87%8F%E6%9E%84%E9%80%A0%E5%8F%98%E9%87%8F%E5%90%8D.png)
我有一个 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) }}"