How to escape a $ sign in an Ansible host_vars fil

2019-06-03 07:54发布

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.name }}', '{{ item.db_type }}', '{{ item.host }}', {{ item.port }}, '{{ item.catalog }}', '{{ item.username }}', '{{ item.password }}');\""
    with_items: "{{ meter_managers }}"
    when: item != ""
    sudo_user: postgres
    tags:
      - initDB

host_vars:

meter_managers:
  - name: SAMPLE
    db_type: ""
    host: "http://www.example.com/axis2/services/Example/"
    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 docker compose file?

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

Example15887Example

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?

UPDATE:

The referenced question would not have answered my question without additional explanation, however Anthon has described the simplification below in comments and assisted far better in THIS question.

标签: ansible yaml
2条回答
爷的心禁止访问
2楼-- · 2019-06-03 08:14

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

查看更多
叛逆
3楼-- · 2019-06-03 08:16

It does not look like a YAML issue ; you are using the shell module and it seems your dollar sign is not sufficiently escaped. Try adding a \ in front of it in the host_vars or adding one more level of quoting in the shell line.

As for the numbers, they are the PID of the shell process. See this.

查看更多
登录 后发表回答