ANSIBLE:循环环境变量



我想在Ansible中扮演一个带有多个环境变量的shell模块。我想循环一个在变量中注册的列表。剧本是这样的:

vars:  
tcd_environment_variable:  
- { abc_variable: "MSG" , abc_value: "HelloWorld" }  
- { abc_variable: "REP_USER" , abc_value: "/home/user" }  
tasks:  
- name: "Test command with environment variables registered"  
shell: "echo $MSG >> $REP_USER/test_env.log"  
environment:   
"{{ item.abc_variable }}": "{{ item.abc_value }}"  
loop: "{{ abc_environment_variable }}"  
become: yes  
become_user: user  

我不能让它工作,只有这个工作:

tasks:  
- name: "Test command with environment variables registered"  
shell: "echo $MSG >> $REP_USER/test_env.log"  
environment: 
REP_USER: /home/user
MSG: "HelloWorld"
become: yes  
become_user: user 

但是我想循环Ansible变量。
谢谢你的帮助

使用items2dict将列表转换为字典,例如

- hosts: localhost
vars:
abc_environment_variable:
- {abc_variable: "MSG", abc_value: "HelloWorld"}
- {abc_variable: "REP_USER", abc_value: "/tmp"}
tasks:
- name: "Test command with environment variables registered"
shell: "echo $MSG >> $REP_USER/test_env.log"
environment: "{{ abc_environment_variable|
items2dict(key_name='abc_variable',
value_name='abc_value') }}"

shell> cat /tmp/test_env.log 
HelloWorld

请参见"设置远程环境"。使参数和升级符合您的需求。

最新更新