Ansible - 根据条件设置变量

Ansible - Set variable based on condition

我有一个名为 kernel 的角色。在它的vars文件中kernel/vars/main.yml,是否可以根据条件设置变量的值?

例如,假设我有这样一个调用我的内核角色的剧本:

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

是否可以在 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

此外,是否可以设置一个默认值,这样如果在 version 没有值的情况下调用角色,它将获得 4,3 的变量?

提前致谢!

由于我过去有过类似的需求,所以我采用了以下方法

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

因为变量已经初始化,所以可以使用

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 }}"

将选项放入单独的文件中,例如

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

然后include变量版本,例如

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

例如剧本

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

给予

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

备注

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