Search code examples
automationyamlansiblejinja2configuration-management

Remove quotes from Ansible variable output


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}

Solution

  • 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. :)