# How to use ansible variables in a 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

```plaintext
📦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

%[https://gist.github.com/danibyay/1cebaa3d1a194be7c99ccfccdeb65300] 

%[https://gist.github.com/danibyay/495db42fe72999e6a0ec30db1525593b] 

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.

```yaml
--- 
version: "2022.3"
```

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

```yaml
- 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.

```yaml
---
- 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.

```yaml
---
- hosts: all
  remote_user: azureuser
   
  roles:
    - role: one_api
      vars: 
        version: "2021.4"
```
