简体   繁体   English

ansible中映射环境变量出错

[英]Error with map environment variables in ansible

I am trying to export environmental variables in ansible where the variable is a map variable as follows.我正在尝试在 ansible 中导出环境变量,其中变量是一个映射变量,如下所示。

Ex.前任。

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

This when set using environment function in ansible as below:这在 ansible 中使用environment函数设置时如下所示:

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

Gives error报错

mapping values are not allowed in this context 

environment is a dictionary. 环境是一本字典。 For example,例如,

  environment:
    NVM_DIR: /var/local/nvm
    PATH: /var/local/nvm/versions/node/v4.2.1/bin:{{ ansible_env.PATH }}

In your case, you probably want to create such an environment dictionary in the variable Variable_123 where the environment variable VAR23 keeps the YAML dictionary as a string在您的情况下,您可能希望在变量Variable_123中创建这样的环境字典,其中环境变量VAR23将 YAML 字典保存为字符串

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

You can use this environment你可以使用这个环境

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

gives

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

You can convert the string to the dictionary您可以将字符串转换为字典

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

gives

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

Example of a complete playbook for testing用于测试的完整剧本示例

- 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

gives

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM