ansible条件检查项的属性存在

时间:2017-03-04 17:51:08

标签: ansible

我想使用ansible创建用户,并希望设置他们的shell和sudo权限。

现在我有vars/main.yml如下:

users: [{'name': 'user1', 'shell': '/bin/bash', 'sudo': 'user1 ALL=(ALL) NOPASSWD: ALL'}, {'name': 'user2', 'shell': '/bin/zsh', 'sudo': 'user2 ALL=NOPASSWD:/bin/systemctl *start nginx'}, {'name': 'user3', 'shell': '/bin/fish'}]

在任务Set sudo permission for users上 因为不是每个用户都有sudo权限,我需要检查sudo属性是否存在。

- name: Set sudo permission for users
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^{{ item.name }}'
    line: "{{ item.sudo }}"
    backup: true
  when: "{{ item.sudo }}"
  with_items:
    - "{{ users }}"

我收到如下错误:

TASK [createUsers : Set sudo permission for users] ***************************
fatal: [ubuntu]: FAILED! => {"failed": true, "msg": "The conditional check '{{ item.sudo }}' failed. The error was: expected token 'end of statement block', got 'ALL'\n  line 1\n\nThe error appears to have been in '/Users/csj/proj/roles/createUsers/tasks/main.yml': line 26, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Set sudo permission for users\n  ^ here\n"}

我尝试了许多关于引用的东西,但它没有帮助。

1 个答案:

答案 0 :(得分:10)

应该有效

 when: item.sudo is defined

所以任务是

  - name: Set sudo permission for users
    lineinfile:
      dest: /etc/sudoers
      state: present
      regexp: '^{{ item.name }}'
      line: "{{ item.sudo }}"
      backup: true
    when: item.sudo is defined
    with_items:
      - "{{ users }}"