Remove quotes from Ansible variable output

11,984

Actually the quotes do not come from the variable, but are right there in your string:

%w{'{{ role }}'}

Now the solution is little bit tricky though. Because you can not simply remove the quotes like that:

%w{{{ role }}}

This would result into a parse error, since {{ starts an expression...

The solution is to write the outer parentheses, which are meant to be in the string, as an expression themselves.

So to output { you would instead write {{'{'}} and instead of } you would write {{'}'}}. Does that make sense? You're instructing the template engine (Jinja2) to output the parentheses to avoid the parsing error:

%w{{'{'}}{{ role }}{{'}'}}

But since role is an expression already, you just also can group it together into one single expression:

%w{{ '{'+role+'}' }}

Your whole task would then read like this:

- lineinfile:
    dest: "{{ ansible_env.HOME }}/{{ deploy_dir }}/config/deploy/{{ stage_name }}.rb"
    insertbefore: "# role-based syntax"
    line: "server '{{ ip_addr }}', user: '{{ user_name }}', roles: %w{{ '{'+role+'}' }}"

This also is converted into proper YAML syntax because this quoted k=v format is just really hard to read. :)

Share:
11,984
Prem Sompura
Author by

Prem Sompura

DevOps Engineer is what I'm known for. Automation, configuration management, deployment, CI, AWS makes me fancy. Love to code in Python. Crazy video gamer.

Updated on June 04, 2022

Comments

  • Prem Sompura
    Prem Sompura almost 2 years

    I'm using this task to add a line to a file:

    lineinfile: "dest={{ ansible_env.HOME }}/{{ deploy_dir }}/config/deploy/{{ stage_name }}.rb
                  insertbefore='# role-based syntax'
                  line='server "'{{ ip_addr }}'", user: "'{{ user_name }}'", roles: %w{'{{ role }}'}'"
    

    Which adds this line:

    server '172.16.8.11', user: 'vagrant', roles: %w{'api'}
    

    But I don't want the quotes around api. Instead I want this output:

    server '172.16.8.11', user: 'vagrant', roles: %w{api}