Creating a list of Users on Remote Servers using Ansible

If you are tasked to create multiple users on remote users and copy the ssh keys to the remote servers. Ansible would come very handy to accomplish the tasks:

The following Ansible playbook is based on the assumption:

  1. Users are not present on the remote servers
  2. SSK Keys are already create on the Ansible Control Servers
  3. All the Users are going to the use the shared key

The users.yml contains the list of the users to be created and its included in the main playbook using include_vars module

---
users:
- username: demo03
- username: demo02
- username: demo01
- username: demo04

In the main playbook the encrypted password has been entered instead of  cleartext. Refer the Ansible documentation to generate the crypted password. Also make sure to create a subdirectory (keyfiles) to and copy the SSH keys for the each user.

---
- name: Create a New User and Copy the SSH Keys on the remote servers
hosts: as-rhel02 as-rhel01

tasks:
- name: Include users.yml
  include_vars: users.yml
- name: Create the users
  user:
    name: "{{ item.username}}"
    shell: /bin/bash
    group: wheel
    state: present
    generate_ssh_key: yes
    ssh_key_file: .ssh/id_rsa
    password: $6$iy2g1ICmPsdhuMnx$k6yYulqAXn2rk4BEAlQ70nBLCGHE4gdSqy3ViJh.n7IEcDzRjTOWgxVgArpOHXc4IqEGTBwa3TqowBgfr05Gk0
  loop: "{{users }}"

- name: Set Authorized Key for user
  authorized_key:
    user: "{{ item.username }}"
    key: "{{ lookup('file', 'keyfiles/' + '{{ item.username }}' + '.pub') }}"
    path: "/home/{{ item.username }}/.ssh/authorized_keys"
    state: present
  loop: "{{users}}"

 

 

Share

You must be logged in to post a comment.

Proudly powered by WordPress   Premium Style Theme by www.gopiplus.com