linux ansible中的Map环境变量出错

plicqrtu  于 2022-12-22  发布在  Linux
关注(0)|答案(1)|浏览(180)

我尝试在ansible中导出环境变量,其中变量是一个map变量,如下所示。
例如,

Variable_123: 
   VAR23='
   global:
     string: abcd
   environment:
     local:
       version: 2.32
   '

使用ansible中的environment函数进行设置时,如下所示:

- name: Run tests
  environment: {{ Variable_123 }}

给出错误

mapping values are not allowed in this context
yb3bgrhw

yb3bgrhw1#

  • environment* 是字典。例如,
environment:
    NVM_DIR: /var/local/nvm
    PATH: /var/local/nvm/versions/node/v4.2.1/bin:{{ ansible_env.PATH }}

在您的情况下,您可能希望在变量 Variable_123 中创建这样的环境字典,其中环境变量 VAR23 将YAML字典作为字符串保存

Variable_123:
    VAR23: |
      global:
        string: abcd
      environment:
        local:
          version: 2.32

您可以使用此环境

- command: echo $VAR23
      environment: "{{ Variable_123 }}"
      register: out

给予

out.stdout: |-
    global:
      string: abcd
    environment:
      local:
        version: 2.32

可以将字符串转换为字典

VAR23: "{{ out.stdout|from_yaml }}"

给予

VAR23:
    environment:
      local:
        version: 2.32
    global:
      string: abcd

完整的测试行动手册示例

- hosts: localhost

  vars:

    Variable_123:
      VAR23: |
        global:
          string: abcd
        environment:
          local:
            version: 2.32

    VAR23: "{{ out.stdout|from_yaml }}"

  tasks:

    - command: echo $VAR23
      environment: "{{ Variable_123 }}"
      register: out
    - debug:
        var: out.stdout

    - debug:
        var: VAR23
    - debug:
        var: VAR23.environment.local.version

给予

PLAY [localhost] *****************************************************************************

TASK [command] *******************************************************************************
changed: [localhost]

TASK [debug] *********************************************************************************
ok: [localhost] => 
  out.stdout: |-
    global:
      string: abcd
    environment:
      local:
        version: 2.32

TASK [debug] *********************************************************************************
ok: [localhost] => 
  VAR23:
    environment:
      local:
        version: 2.32
    global:
      string: abcd

TASK [debug] *********************************************************************************
ok: [localhost] => 
  VAR23.environment.local.version: '2.32'

PLAY RECAP ***********************************************************************************
localhost: ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

相关问题