7

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 == ""

1 Answer 1

9

There is default filter for that:

- set_fact:
    my_rpm: "{{ my_rpm | default(jenkins_rpm) }}"
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly was I was looking for. Thanks! I just couldn't quite figure out how the default filter worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.