Ansible PLaybook:在 Linux 路径中转义“$”

Ansible PLaybook: Escape '$' in Linux path

我有一条看起来像这样的路径 -

base_dir/123/path/to/G$/subdirectory/html/

当我尝试在 Ansible 剧本中设置此路径时,它会抛出错误。如果添加 \$ 来转义 '\',它会抛出意外的失败错误。

Playbkook -

- hosts: localhost
  vars:
    account_id: 123
  tasks:
  - name: Add \ to path
    debug:
      var: "base_dir/{{ account_id }}/path/to/G\$/subdirectory/html/"

结果-

TASK [Gathering Facts] *************************************************************************************************************************************************
task path: /playbooks/example_path.yml:2
ok: [localhost]
META: ran handlers

TASK [Add \ to path] ***************************************************************************************************************************************************
task path: /playbooks/exmaple_path.yml:6
fatal: [localhost]: FAILED! => {
    "msg": "Unexpected failure during module execution."
}

PLAY RECAP *************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1

debug 模块文档中所述,var 选项需要一个变量名,而不是用于输出的标量。您收到错误消息是因为 \ 不应出现在变量名称中。 运行带有-vvv的剧本会给你更多的解释。

在这种情况下,您需要使用 msg 选项。

- hosts: localhost
  gather_facts: false
  vars:
    account_id: 123
  tasks:
    - name: Add \ to path
      debug:
        msg: "base_dir/{{ account_id }}/path/to/G\$/subdirectory/html/"

结果

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

TASK [Add \ to path] ***********************************************************
ok: [localhost] => {
    "msg": "base_dir/123/path/to/G\$/subdirectory/html/"
}

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

下一个选项是使用 Single-Quoted Style。请参阅下面的示例

- hosts: localhost
  vars:
    my_dir1: "/scratch/tmp/G1\$"
    my_dir2: '/scratch/tmp/G2$'
  tasks:
    - file:
        state: directory
        path: "{{ item }}"
      loop:
        - "{{ my_dir1 }}"
        - "{{ my_dir2 }}"

# ls -1 /scratch/tmp/
'G1$'
'G2$'