首页 > 解决方案 > 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 变量。
谢谢你的帮助

标签: loopsansible

解决方案


使用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

请参阅“设置远程环境”。根据您的需要调整参数和升级。


推荐阅读