Variable inside quotes

470 Views Asked by At

I'm trying to pass a variable into an Ansible playbook.

ansible-playbook script.yml --extra-vars "status=false"

Here is my playbook:

  

- name: Enable fact
    set_fact:
      facts: '{{ facts | combine({ "configured_status": "{{status}}" })}}'
    vars:
      facts: '{{ facts_raw.content|b64decode }}'

  - debug:
      var: facts

However, The debug output is:

 "configured_status": "{{status}}"

Instead of:

"configured_status": "false"

Anyone knows what could be the issue?

2

There are 2 best solutions below

2
On BEST ANSWER

Try

facts: '{{ facts | combine({ "configured_status": status })}}'

Why are you decoding facts? If you used slurp then

  - name: Enable fact
    set_fact:
      facts: "{{ facts_raw.content|b64decode|from_json|default([])| combine({ 'configured_status': status }) }}"

  - debug:
      var: facts
0
On

Because of the way you are passing your variables to extra-vars this can be as simple as

facts: '{{ facts | combine({ "configured_status": status }) }}'

This is actually pointed in the documentation:

Values passed in using the key=value syntax are interpreted as strings. Use the JSON format if you need to pass in anything that shouldn’t be a string (Booleans, integers, floats, lists etc).

Source: https://docs.ansible.com/ansible/2.9/user_guide/playbooks_variables.html#passing-variables-on-the-command-line

So you don't even have to protect you from Ansible treating it as a boolean, as in the playbook below.


Now, would you pass it as a real boolean:

ansible-playbook script.yml --extra-vars '{ "status": false }'

Then, nesting Jinja delimiters would never lead you to any good.

Here, what you want to use is the contatenation operator of Jinja ~, so you can concatenate a string and the variable that status holds.

Given the playbook, play.yml:

- hosts: all
  gather_facts: no
      
  tasks:
    - debug: 
        msg: '{{ facts | combine({ "configured_status": "" ~ status ~ "" })}}'
      vars:
        facts: 
          foo: bar

Run with the command

ansible-playbook play.yml --extra-vars "status=false"

This yields the recap:

PLAY [all] *******************************************************************************************************

TASK [debug] *****************************************************************************************************
ok: [localhost] => {
    "msg": {
        "configured_status": "false",
        "foo": "bar"
    }
}

PLAY RECAP *******************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0