ansibleyamlansible-vault

Is there a way to set an Ansible encrypted var and preserve all special characters?


I have a variable set in an encrypted ansible vault yaml file which has multiple special characters, including < { , " ' [ and %.

my_var: <X%X[X{,"<X'L

I need Ansible to take the variable as a raw string, but it's inserting a \ before the double-quote (") - at least that is what debug shows.

ok: [10.10.10.10] => {
    "my_var": "<X%X[X{,\"<X'L"
}

How can I get ansible to treat the variable as a raw string?


Solution

  • What you see depends on the callback. No quotation and/or escaping is needed

    shell> cat my_var.yml 
    my_var: <X%X[X{,"<X'L
    

    To test it, use yaml callback and iterate the string character by character

    - hosts: localhost
    
      vars_files:
        - my_var.yml
    
      tasks:
    
        - debug:
            msg: |
              {% for i in range(my_var|length) %}
              {{ i % 10 }}{% endfor %}
    
              {% for c in my_var %}
              {{ c }}{% endfor %}
    

    gives (ANSIBLE_STDOUT_CALLBACK=yaml)

      msg: |-
        0123456789012
        <X%X[X{,"<X'L
    

    You'll get the same result when you encrypt the file

    shell> ansible-vault encrypt my_var.yml
    Encryption successful