Priyanka
Priyanka

Reputation: 55

Ansible PLaybook: Escape '$' in Linux path

I have a path which looks like this -

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

When I try to set this path in Ansible playbook, it throws error. If add \$ to escape '\', it throws unexpected failure error.

Playbkook -

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

Result -

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

Upvotes: 2

Views: 138

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68124

The next option is to use the Single-Quoted Style. See the example below

- 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\$'

Upvotes: 0

Zeitounator
Zeitounator

Reputation: 44740

As explained in the debug module documentation, the var option is expecting a variable name, not a scalar for output. You are getting an error because \ is not expected in a variable name. Running the playbook with -vvv will give you a little more explanations.

In this case you need to use the msg option.

- 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/"

Result

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

Upvotes: 1

Related Questions