I want to create users using ansible and want to set their shell and sudo permissions.
Now I have vars/main.yml
as below:
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'}]
On the task Set sudo permission for users
because not every user have sudo permission, which I need to check if the sudo
attribute is exist or not.
- 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 }}"
I got error as below:
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"}
I tried many about quote things but it didn't help.
As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword. Show activity on this post.
I use | trim != '' to check if a variable has an empty value or not.
Use this command to run a playbook: $ ansible-playbook <playbook. yml> Use this command to check the playbook for syntax errors: $ ansible-playbook <playbook. yml> --syntax-check.
It should work
when: item.sudo is defined
so the task is
- 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 }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With