Ansible: overriding boolean values using extra-vars at runtime

If you are using “–extra-vars” at runtime to override a boolean variable, then you should use the JSON syle (instead of key-value pairs) to avoid type conversion issues.

For example, if there is a boolean variable named “myflag” that is default to true in your playbook and you attempt to override it like below, it will not work as expected.

# this boolean override  will probably work as expected
ansible-playbook my-playbook.yml --extra-vars "myflag=false"

The problem is the value will be passed as the string “false”, which will not automatically be sensed as a Truthy/Falsy value.  Ansible will only see that the string is non-empty and that equates to true.

This can be avoided by using the JSON version of extra-vars.

# this boolean override works
ansible-playbook my-playbook.yml --extra-vars '{"myflag": false}'

If you insist on using key-value pairs, then it would require you to provide an empty value, which evaluates to false.

# this empty value will evaluate to false
my-playbook.yml --extra-vars "myflag="

Another way to avoid this issue is to use an explicit “bool” filter cast everywhere the value is used in your playbook.

 - debug:
     msg: "myflag is false when using explicit boolean conversion"
   when: not myflag|bool

You can find a full example I wrote in github as playbook-pass-extra-vars.yml

 

REFERENCES

ansible, extra-vars at runtime