Tasks based on variable definition 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.
It's a duplicate of Ansible - Use default if a variable is not defined

version: "{{ ver | default('default_version') }}"


To use default_version in case ver is empty

- set_fact:
    version: "{{ default_version }}"
  when: ver == ""


or (Ansible Galaxy warning-free option)

  when: ver | length &gt; 0