Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible conditional check a item's attribute exist

Tags:

ansible

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.

like image 651
CSJ Avatar asked Mar 04 '17 17:03

CSJ


People also ask

How is it possible to check if a variable is defined in Ansible?

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.

How do you know if a variable is empty in Ansible?

I use | trim != '' to check if a variable has an empty value or not.

How do you validate Ansible syntax?

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.


1 Answers

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 }}"
like image 110
gile Avatar answered Oct 29 '22 22:10

gile