首页 > 解决方案 > Ansible 中的变量替换

问题描述

我正在寻找有关 Ansible 变量替换如何工作的解释。我想将变量作为字符串而不是数组。

这是一些示例代码:

test.yml

---

- name: Debug
  hosts: localhost
  strategy: debug
  vars:
    an_ansible_variable: 'an_ansible_variable'
    test:
      'wrong_output_with_variable': "['{{ an_ansible_variable }}']"
      'wrong_output_with_raw': "{%- raw -%}['{{ not_an_ansible_variable }}']{%- endraw -%}"
      'correct_output_with_unsafe': !unsafe "['{{ not_an_ansible_variable }}']"
  tasks:
    - debug:
        var: test

输出:

TASK [debug] ****************************************************************************************************************************************************************************************
ok: [localhost] => {
    "test": {
        "correct_output_with_unsafe": "['{{ not_an_ansible_variable }}']", 
        "wrong_output_with_raw": [
            "{{ not_an_ansible_variable }}"
        ], 
        "wrong_output_with_variable": [
            "an_ansible_variable"
        ]
    }
}

我不明白为什么变量是数组而不是字符串。

谢谢和亲切的问候,

曼弗雷德

标签: ansible

解决方案


问:我不明白为什么变量是数组而不是字符串。

A:因为它们是封闭在括号中的[]。例如

- hosts: localhost
  vars:
    var1: var
    var2: [var]
  tasks:
    - debug:
        msg:
          - "var1: {{ var1 }} type: {{ var1|type_debug }}"
          - "var2: {{ var2 }} type: {{ var2|type_debug }}"

给出(删节)

  msg:
  - 'var1: var type: AnsibleUnicode'
  - 'var2: [''var''] type: list'

推荐阅读