jessefournier
jessefournier

Reputation: 193

Ansible - Set variable based on condition

I have a role called kernel. In its vars file kernel/vars/main.yml, is it possible to set the values of variables based on a condition?

For example, say I have a playbook like this that calls my kernel role:

---
- hosts: webservers
  roles:
    - role: kernel
      vars:
        version: '4.3'

is it possible to do something like this in kernel/vars/main.yml?:

---
if 'version' == '4.3':
  kernel_dir:  "/mnt/public/kernel/4.3"
  kernel_headers: "linux-headers-4.3.deb"
  kernel_image: "linux-image-4.3.deb"
  kernel_libc: "linux-libc-dev_4.3.deb"
  kernel_version: "Ubuntu, with Linux 4.3"
if 'version' == '4.2':
  kernel_dir: "/mnt/public/kernel/4.2"
  kernel_headers: "linux-headers-4.2.deb"
  .. and so on

Also, is it possible to set a default value, so that if the role has been called with no value for version, it would get the vars for 4,3?

Thanks ahead!

Upvotes: 1

Views: 2632

Answers (2)

U880D
U880D

Reputation: 12124

Since I had a similar requirement in the past I came to following approach

- name: Initialize VERSION
  set_fact:
    VERSION: "4.3"
  when: VERSION == ''

since the variable is initialized for sure it is than possible to use

kernel_dir: "/mnt/public/kernel/{{ VERSION }}"
kernel_headers: "linux-headers-{{ VERSION }}.deb"
kernel_image: "linux-image-{{ VERSION }}.deb"
kernel_libc: "linux-libc-dev_{{ VERSION }}.deb"
kernel_version: "Ubuntu, with Linux {{ VERSION }}"

Upvotes: 2

Vladimir Botka
Vladimir Botka

Reputation: 68189

Put the options into separate files, e.g.

shell> cat roles/kernel/vars/4.2.yml 
kernel_dir:  /mnt/public/kernel/4.2
kernel_headers: linux-headers-4.2.deb

shell> cat roles/kernel/vars/4.3.yml 
kernel_dir:  /mnt/public/kernel/4.3
kernel_headers: linux-headers-4.3.deb

Then include the variables by version, e.g.

shell> cat roles/kernel/tasks/main.yml
- include_vars: "{{ version }}.yml"
- debug:
    var: kernel_dir

For example, the playbook

shell> cat playbook.yml
- hosts: webservers
  roles:
    - role: kernel
      vars:
        version: '4.3'

gives

ok: [webservers] => 
  kernel_dir: /mnt/public/kernel/4.3

Notes

If the path is relative and the task is inside a role, it will look inside the role's vars/ subdirectory.

Upvotes: 2

Related Questions