DEV Community

Enrique Matta-Rodriguez
Enrique Matta-Rodriguez

Posted on

Use Ansible to add users

This will be a short but sweet dive into setting up users in your EC2 container with only their GitHub handles and ansible. I am expecting you have some ansible knowledge, so I won't dive deep into a beginner's tutorial. For that, I would suggest Ansible's own docs to get started.

Github

Every single GitHub user out there has access to their public key via curl. Don't believe me? Go to https://github.com/[your_handle].keys and voila your pub key is there for the taking. Here is mine. So, now that you have that bit of knowledge in your head, let's move on.

Ansible Playbook

vars

Step 1 is to create a vars file for the users. I've chosen the following structure for vars/users.yaml:

---
create_users: true

account_names:
  - { user: 'enriquem', key: 'https://github.com/ematta.keys' }
Enter fullscreen mode Exit fullscreen mode

Add as many users you need to manage your EC2 instance. In this example, it's just me.

Users Role

Defaults

In your defaults folder you should add a main.yml file loaded with:

---
create_users: true
Enter fullscreen mode Exit fullscreen mode

Files (sudoers)

Add the following under files/sudoers:

%sudo ALL=(ALL) NOPASSWD:ALL
Enter fullscreen mode Exit fullscreen mode

Main Task main.yaml

Finally, you add this as your tasks for the users role.

--------
- name: Verify you have wheel
  group:
    name: wheel
    state: present
  become: yes
  tags:
    - users

- name: Set wheel to passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
  become: yes
  tags:
    - users

- name: Create all users accounts
  user:
    name: "{{ item.user }}"
    shell: "/bin/bash"
    groups: 
      - users
      - wheel
    system: yes
    state: present
    append: yes
  with_items:
    - "{{ account_names }}"
  become: yes
  tags:
    - users

- name: Add ssh key for creted 
  authorized_key:
    user: "{{ item.user }}"
    key: "{{ item.key }}"
    state: present
  with_items:
    - "{{ account_names }}"
  become: yes
  tags:
    - users
Enter fullscreen mode Exit fullscreen mode

Now, with all that in, just add users to your site.yaml file and poof you now have an easy way of adding users to an existing EC2 container.

Top comments (0)