ManoDestra ManoDestra - 3 years ago 153
YAML Question

How to escape a $ sign in an Ansible host_vars file

I have a Ansible playbook (YAML) that deploys an web application and, as part of the deployment process, it creates and initializes various databases and some data in certain tables.

Playbook Task:

- name: insert Meter Managers to mdm_connection
shell : "psql -d {{ mdm_config_db }} -c \"insert into mdm_connection (mdm_connection_type_id, name, db_type, host, port, catalog, username, password) values (3, '{{ }}', '{{ item.db_type }}', '{{ }}', {{ item.port }}, '{{ item.catalog }}', '{{ item.username }}', '{{ item.password }}');\""
with_items: "{{ meter_managers }}"
when: item != ""
sudo_user: postgres
- initDB


- name: SAMPLE
db_type: ""
host: ""
port: -1
catalog: ""
username: csa1
password: "Example$Example"

You can ignore most of the parameters above, but the part that isn't working is the password field, as it contains a $ sign.

It comes out as Example, truncated after the $ sign.

I have tried to escape it as a double $$ instead, as per this link: How can I escape a $ dollar sign in a YAML string?

However, that does not result in the right output. It comes out as


Where the number in between is different each time I run my playbook. I have no idea where that number is coming from. It seems to be some kind of tick, or something like that, but the link seems to suggest that $$ is the way to escape a single $ and so I don't see why that's coming out like that.

I have also tried with and without enclosing " marks and also tried with or without ' marks, but to no avail.

Any idea as to how to properly escape this so that I can get the value Example$Example ready for insertion into my database table?

Answer Source

You feed the string with $ into bash.
In bash $ is a variable prefix.
And $$ is a special variable with current PID number, which is different every time you run playbook.

In bash when you use double quotes $ should appear as \$. I see you use double quotes in YAML as well, so you should try to escape slash as well, so try with password: "Example\\$Example".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download