Ansible:根据库存变量使用不同的成为选项

Ansible: use different become option according to inventory variable

我想根据某些库存变量值调用特权用户或不调用某些角色

类似的东西:

- name: Example1 execute under privilege user if inventory.variable is true
  hosts: some_host
  become_user: user
  roles:
    - { role: configure/crypt,   when: inventory.variable == true}

- name: Example2 execute under current user if inventory.variable is false
  hosts: some_host
  become: no
  roles:
    - { role: configure/crypt,   when: inventory.variable == false}

但是当我使用 -become 选项执行剧本时,这段代码不起作用。 如果值 inventory.variable == false 角色在 example1 失败并出现错误:

无法设置 Ansible 在成为非特权用户时需要创建的临时文件的权限

因此,尽管表达式为 false,ansible 仍会尝试提升权限。

下面的单曲涵盖了这两种情况。您可以在角色级别声明升级

- name: Execute as admin if ivar is true else as the current user
  hosts: localhost
  roles:
    - role: crypt
      become: "{{ ivar|d(false)|bool }}"
      become_user: "{{ ivar|d(false)|bool|ternary('admin', 'nobody') }}"

,或剧中级别

- name: Execute as admin if ivar is true else as the current user
  hosts: localhost
  become: "{{ ivar|d(false)|bool }}"
  become_user: "{{ ivar|d(false)|bool|ternary('admin', 'nobody') }}"
  roles:
    - role: crypt