Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set variable if empty or not defined with ansible

Tags:

ansible

In my ansible vars file, I have a variable that will sometimes be set and other times I want to dynamically set it. For example, I have an RPM that I want to install. I can manually store the location in a variable, or if I don't have a particular one in mind, I want to pull the latest from Jenkins. My question is, how can I check if the variable is not defined or empty, and if so, just use the default from Jenkins (already stored in a var)?

Here is what I have in mind:

...code which gets host_vars[jenkins_rpm]
- hosts: "{{ host }}"
  tasks:
  - name: Set Facts
    set_fact:
      jenkins_rpm: "{{ hostvars['localhost']['jenkins_rpm'] }}"

  - name: If my_rpm is empty or not defined, just use the jenkins_rpm
    set_fact: my_rpm=jenkins_rpm
    when: !my_rpm | my_rpm == ""
like image 555
user3270760 Avatar asked Jun 20 '17 14:06

user3270760


People also ask

How to test if a variable exists in Ansible?

In Ansible playbooks, it is often a good practice to test if a variable exists and what is its value. Particularity this helps to avoid different “ VARIABLE IS NOT DEFINED ” errors in Ansible playbooks. In this context there are several useful tests that you can apply using Jinja2 filters in Ansible.

How to avoid “variable is not defined ” errors in Ansible playbooks?

In Ansible playbooks, it is often a good practice to test if a variable exists and what is its value. Particularity this helps to avoid different “ VARIABLE IS NOT DEFINED ” errors in Ansible playbooks.

What is the difference between set_facts and host_VARs in Ansible?

Includes vars added by ‘vars plugins’ as well as host_vars and group_vars which are added by the default vars plugin shipped with Ansible. When created with set_facts’s cacheable option, variables have the high precedence in the play, but are the same as a host facts precedence when they come from the cache.

How do I override previous versions of variables in Ansible?

In general, Ansible gives precedence to variables that were defined more recently, more actively, and with more explicit scope. Variables in the the defaults folder inside a role are easily overridden. Anything in the vars directory of the role overrides previous versions of that variable in the namespace.


1 Answers

There is default filter for that:

- set_fact:
    my_rpm: "{{ my_rpm | default(jenkins_rpm) }}"
like image 186
Konstantin Suvorov Avatar answered Oct 28 '22 14:10

Konstantin Suvorov