Write a task that creates multiple users with SSH keys from a list.
BeginnerHands-onWrite-an-Ansible-playbook tasks
Answer
vars:
devs:
- { name: alice, key: "ssh-ed25519 AAAA... alice@laptop" }
- { name: bob, key: "ssh-ed25519 AAAA... bob@laptop" }
tasks:
- name: Create users
ansible.builtin.user:
name: "{{ item.name }}"
groups: sudo
append: true
shell: /bin/bash
loop: "{{ devs }}"
- name: Add SSH keys
ansible.posix.authorized_key:
user: "{{ item.name }}"
key: "{{ item.key }}"
loop: "{{ devs }}"
Key trick → append: true adds the group without removing the user's existing groups. Without it, groups: replaces the whole list.
More on Write-an-Ansible-playbook tasks
Write a playbook that installs and starts Nginx on Ubuntu web servers.BeginnerWrite an inventory with groups, a group of groups, and per-group variables.BeginnerWrite a playbook that deploys a config file from a Jinja2 template and restarts the service only if it changed.BeginnerWrite a role structure for a Node.js app and show what goes in each folder.IntermediateWrite a rolling deploy playbook: 2 servers at a time, removed from the load balancer during the update.AdvancedEncrypt a database password with Ansible Vault and use it in a playbook.Beginner