How to use ansible variables in a role

How to use ansible variables in a role

Example using a local role, and the defaults variables of the role

I will showcase an example of an ansible role using a variable to determine which task to call.

/

Let's assume I want to use the role one_api in my playbook. But I currently have two ways of installing this software, and it depends on the version that I want to install.

This is how my directory structure looks like

📦roles
 ┣ 📂one_api
 ┃ ┣ 📂defaults
 ┃ ┃ ┗ 📜main.yml
 ┃ ┗ 📂tasks
 ┃ ┃ ┣ 📜main.yml
 ┃ ┃ ┣ 📜one_api_2021_4.yml
 ┃ ┃ ┗ 📜one_api_2022.yml

And these are the contents of the tasks for each version of the software

As you can see, they are fairly similar, but still, what should go in the main.yml or how can we choose which one we want to run?

First, I will create a variable file in the folder defaults called main.yml.

The variable will be called version, and the default value would be the latest version of the software: 2022.3. And to avoid ansible to interpret it as a float, we'll add quotes.

--- 
version: "2022.3"

Now, in my main.yml of the tasks folder I will use a conditional statement.

- name: Install Intel One API 2022
  include_tasks: 
    file: one_api_2022.yml
  when: version == "2022.3"

- name: Install Intel One API 2021
  include_tasks:
    file: one_api_2021_4.yml
  when: version == "2021.4"

Since the default value, is already declared as 2022.3, if I call the role in a playbook.yml, the task that will be called is the installation of 2022.

---
- hosts: all
  remote_user: azureuser

  roles:
    - role: one_api

If I want to overwrite the version variable, to install the 2021 version, it would look like this.

---
- hosts: all
  remote_user: azureuser

  roles:
    - role: one_api
      vars: 
        version: "2021.4"