Ansible for Users, Groups, Vault and sudo

User tasks on the exam combine a variable file of users, a vault file of passwords and conditions on group membership.

yaml - name: Developers hosts: dev,test varsfiles: - userlist.yml users: [{name, job, uid}] - secret.yml vault: devpass tasks: - ansible.builtin.group: { name: webdev, state: present } - ansible.builtin.user: name: "{{ item.name }}" uid: "{{ item.uid }}" groups: webdev append: true password: "{{ devpass | passwordhash('sha512') }}" updatepassword: oncreate loop: "{{ users }}" when: item.job == 'developer'

password must be a hash, never plain text: passwordhash('sha512') makes one. Its random salt makes the task report changed on every run; updatepassword: oncreate (or a fixed salt) avoids that. groups without append: true replaces all supplementary groups. Create groups before users that need them.

Vault. ansible-vault create secret.yml (or encrypt an existing file) with a password file: --vault-password-file secret.txt, or vaultpasswordfile = secret.txt in ansible.cfg. Keep the password file mode 0600 and out of Git. ansible-vault view, edit and rekey work on the encrypted file.

SSH keys. ansible.posix.authorizedkey appends a key to a user's authorizedkeys and creates ~/.ssh with the right modes:

yaml - ansible.posix.authorizedkey: user: anika key: "{{ lookup('file', 'files/anika.pub') }}"

sudo. Drop a file in /etc/sudoers.d and let visudo check it before it is moved into place. A broken sudoers file can lock Ansible out (become stops working), so validate is not optional:

yaml - ansible.builtin.copy: content: "%opsmgr ALL=(ALL) NOPASSWD: ALL\n" dest: /etc/sudoers.d/opsmgr mode: "0440" validate: /usr/sbin/visudo -cf %s

Removing an account: user: name: olduser state: absent remove: true (remove deletes home and mail spool).

Checking your work. ansible dev,test -m command -a 'id anika' shows uid and groups; ansible prod -m command -a 'id anika' must fail. sudo -l -U dmitri on a node lists the sudo rule. To prove the password, log in once with ssh anika@node1 or compare hashes with a small python3 -c check.

Pitfalls. Creating users on every host instead of the named groups. Plain-text passwords in password. Forgetting the vault password at run time. Writing to /etc/sudoers itself instead of sudoers.d.