Search code examples
ansibleansible-role

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!


Solution

  • 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.