1
\$\begingroup\$

I am creating a playbook that takes a variable ver at runtime and then runs tasks based on that variable. If that ver is defined, it takes the version number and installs a version according to that. If the ver is not defined, it defaults to a default version.

My playbook for now looks like:

- name: Download Maven from remote repository.
  unarchive:
    src: "{{ baseurl }}/{{ versions[ver] }}"
    dest: /usr/local/
    remote_src: yes
  become: yes
  when: ver is defined

- name: Rename maven folder.
  command: mv /usr/local/apache-maven-{{ver}} /usr/local/maven-{{ver}}
  become: yes
  when: ver is defined

- name: Create symbolic link to maven folder.
  file:
    src: "/usr/local/maven-{{ver}}"
    dest: "/usr/local/maven"
    state: link
  become: yes
  when: ver is defined


- name: Download Default Maven from remote repository.
  unarchive:
    src: "{{ baseurl }}/{{ versions[default_version] }}"
    dest: /usr/local/
    remote_src: yes
    list_files: yes
  become: yes
  when: ver is not defined

- name: Rename maven folder.
  command: mv /usr/local/apache-maven-{{default_version}} /usr/local/maven-{{default_version}}
  become: yes
  when: ver is not defined

- name: Create symbolic link to maven folder.
  file:
    src: "/usr/local/maven-{{default_version}}"
    dest: "/usr/local/maven"
    state: link
  become: yes
  when: ver is not defined

As you can see, based on whether a variable is defined or not, I have to write whole new tasks for it.

The above works but I think it's not optimized as I'm writing too much code to get this to work. One idea that I have is to create have main.yaml invoke another task file when ver is defined and a separate task file when ver is not defined.

Is there another way to optimize this? I have many other tasks that deal with version number.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Use the filter default. For example

    - set_fact:
        version: "{{ ver | default(default_version) }}"

If you want to use default_version also in case ver is empty set the second parameter to true

        version: "{{ ver | default(default_version, true) }}"

See more detail at Ansible - Use default if a variable is not defined

\$\endgroup\$
2
  • \$\begingroup\$ Thanks. This worked. In this case, I was talking about whether a variable exists or not. But what if there is always a variable but now I need to see whether its value is set to something or if its null. If its null, then default to a default_value. Does ansible have any such capability ? \$\endgroup\$ Commented Aug 4, 2018 at 23:58
  • 1
    \$\begingroup\$ Ansible doco explains null value variables here. \$\endgroup\$ Commented Sep 16, 2021 at 2:05

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.