24

Is there a way to destroy the variable in Ansible?

Actually, I have a {{version}} variable being used in my all roles for respective packages. When I run multiple roles, the version value of one role is passed to another - this is due to for some role I am not giving version value so that it can install the default version of that package available for respective m/c like ubuntu/redhat etc.

Here is my role template. The value of {{version}} from mysql is being passed to rabbitmq.

    roles:
- { role: mysql }
- { role: rabbitmq}

If I can destory/delete the value of version in every role, it should solve the problem, I believe.

peterh
  • 5,017
MMA
  • 425

7 Answers7

18

As already pointed out it is not possible to unset a variable in Ansible.

Avoid this situation by adding a prefix to your variable names like rabbitmq_version and so on. IMHO this a best practice.

Beside avoiding the situation you ran into, this will add clarity to your host_vars and group_vars.

8

No, there is no way to unset a variable (top level) in Ansible.

The only thing you can do, is to create a dictionary and store the variable as a key in this dictionary. Clearing the "parent" dictionary will essentially make the dictionary.key is defined conditional expression work.

techraf
  • 4,403
8

To unset a variable, try running a set_fact task setting the variable to null, like:

- name: Unset variables
  set_fact:
    version:
    other_var:

If you have a full dictionary that could just override the dict with null, like:

- name: Set dict
  set_fact:
    dict:
      rabbitmq_version: 1
      other_version: 2

- name: override dict to null
  set_fact:
    dict:

Something like other_var: just is "other_var": null in JSON. That is how you can unset variables in Ansible. Have a nice day.

6

you should use variable per role instead:

  roles:
    - role: mysql
      version: mysql_version
    - role: rabbitmq
      version: rabbitmq_version

or

  roles:
    - { role: mysql, version: mysql_version }
    - { role: rabbitmq, version: rabbitmq_version }
4

In Ansible 2.12 use undef() function like this:

airflow_pip_version: "{{ undef() }}"  # unsets default: 20.2.4

After that the following task is skipped:

- name: Airflow | Install pip "{{ airflow_pip_version }}" version
  pip:
    name: pip
    version: "{{ airflow_pip_version }}"
  when: airflow_pip_version is defined

This was the desired behaviour for me. Docs:

https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_templating_undef.html

1

In Ansible 2.12 and later, use the undef() function. Here is an example:

- hosts: all
  vars:
    version: 1.0
  tasks:
    - assert:
        that: version is defined
    - assert:
        that: version is not defined
      vars:
        version: "{{ undef() }}"
Martin Wilck
  • 191
  • 4
-3

You can set it to nothing. I'm currently using it like that:

variable_name: ''
Rafal
  • 1