Skip to main content

Ansible - Create Users from a Dictionary

Creating users is typically straightforward as the documentation for the required Ansible modules is comprehensive and easy to navigate. However, working with dictionaries instead of lists can introduce some additional complexity. 
For example, let's assume the following dictionary structure is given:
 usergroups:  
   group1:  
     gid: 10001  
     name: group1  
   group2:  
     gid: 10002  
     name: group2  
   group3:  
     gid: 10003  
     name: group3  
   group4:  
     gid: 10004  
     name: group4  
 users:  
   user1:  
     uid: 1985  
     name: user1  
     groups:  
       - group1  
       - group2  
     sshkeys:  
       - ssh-ed25519 AAAA0  
       - ssh-ed25519 AAAA1  
   user2:  
     uid: 1986  
     name: user2  
     groups:  
       - group4  
       - group1  
     sshkeys:  
       - ecdsa-sha2-nistp384 AAAA0  
Ansible provides the dict2items filter which transforms a dictionary into a list of key-value pairs. This transformation allows you to iterate over a list created from the dictionary and access all attributes for use within your Ansible modules:
 - name: create usergroups  
   with_items: "{{ users | ansible.builtin.dict2items }}"  
   ansible.builtin.group:  
     gid: "{{ item['value']['uid'] }}"  
     name: "{{ item['value']['name'] }}"  
     state: present  
     system: false  
Same goes for the groups:
 - name: create groups  
   with_items: "{{ usergroups | ansible.builtin.dict2items }}"  
   ansible.builtin.group:  
     gid: "{{ item['value']['gid'] }}"  
     name: "{{ item['value']['name'] }}"  
     state: present  
     system: false  

For user creation, additional logic is required to generate and hash strong passwords. Each user will be assigned a unique password with the following characteristics:

  • Length: 96 characters
  • Character set: A combination of uppercase letters, lowercase letters, and digits
 - name: create users  
   with_items: "{{ users | ansible.builtin.dict2items }}"  
   ansible.builtin.user:  
     uid: "{{ item['value']['uid'] }}"  
     name: "{{ item['value']['name'] }}"  
     comment: "{{ item['value']['full_name'] | default(item['value']['name']) | capitalize }}"  
     append: false  
     create_home: true  
     generate_ssh_key: false  
     group: "{{ item['value']['name'] }}"  
     groups: "{{ item['value']['groups'] }}"  
     home: "/home/{{ item['value']['name'] }}"  
     move_home: false  
     password: "{{ lookup('ansible.builtin.password', '/dev/null', length=96, chars=['ascii_lowercase','ascii_uppercase','digits']) | password_hash('sha512_crypt') }}"  
     update_password: on_create  
     shell: "{{ item['value']['shell'] | default('/bin/bash') }}"  
     state: present  
     system: false  
You might have noticed that passwords are generated for each user, but not returned to the user as they're returned to '/dev/null'. Instead of relying on passwords for authentication, the SSH keys specified in each user's 'sshkeys' attribute will be used to configure passwordless SSH access using the 'authorized_key' module from the 'ansible.posix' collection:
 - name: configure ssh keys  
   with_items: "{{ users | ansible.builtin.dict2items }}"  
   ansible.posix.authorized_key:  
     user: "{{ item['value']['name'] }}"  
     exclusive: true  
     state: present  
     key: "{{ item['value']['sshkeys'] | join('\n') }}"  
The authorized_key module requires the key attribute to be a string. Therefore, we'll need to combine the list of SSH keys specified for each user into a single string using the join() filter before applying them to the user's authorized_keys file.

The completed playbook looks like this:
 ---  
 - name: create users on test hosts  
   hosts: test  
   become: true  
   gather_facts: true  
   vars:  
     usergroups:  
       group1:  
         gid: 10001  
         name: group1  
       group2:  
         gid: 10002  
         name: group2  
       group3:  
         gid: 10003  
         name: group3  
       group4:  
         gid: 10004  
         name: group4  
     users:  
       user1:  
         uid: 1985  
         name: user1  
         groups:  
           - group1  
           - group2  
         sshkeys:  
           - ssh-ed25519 AAAA0  
           - ssh-ed25519 AAAA1  
       user2:  
         uid: 1986  
         name: user2  
         groups:  
           - group4  
           - group1  
         sshkeys:  
           - ecdsa-sha2-nistp384 AAAA0  
   collections:  
     - ansible.builtin  
     - ansible.posix  
   tasks:  
     - name: create usergroups  
       with_items: "{{ users | ansible.builtin.dict2items }}"  
       ansible.builtin.group:  
         gid: "{{ item['value']['uid'] }}"  
         name: "{{ item['value']['name'] }}"  
         state: present  
         system: false  
     - name: create groups  
       with_items: "{{ usergroups | ansible.builtin.dict2items }}"  
       ansible.builtin.group:  
         gid: "{{ item['value']['gid'] }}"  
         name: "{{ item['value']['name'] }}"  
         state: present  
         system: false  
     - name: create users  
       with_items: "{{ users | ansible.builtin.dict2items }}"  
       ansible.builtin.user:  
         uid: "{{ item['value']['uid'] }}"  
         name: "{{ item['value']['name'] }}"  
         comment: "{{ item['value']['full_name'] | default(item['value']['name']) | capitalize }}"  
         append: false  
         create_home: true  
         generate_ssh_key: false  
         group: "{{ item['value']['name'] }}"  
         groups: "{{ item['value']['groups'] }}"  
         home: "/home/{{ item['value']['name'] }}"  
         move_home: false  
         password: "{{ lookup('ansible.builtin.password', '/dev/null', length=96, chars=['ascii_lowercase','ascii_uppercase','digits']) | password_hash('sha512_crypt') }}"  
         update_password: on_create  
         shell: "{{ item['value']['shell'] | default('/bin/bash') }}"  
         state: present  
         system: false  
     - name: configure ssh keys  
       with_items: "{{ users | ansible.builtin.dict2items }}"  
       ansible.posix.authorized_key:  
         user: "{{ item['value']['name'] }}"  
         exclusive: true  
         state: present  
         key: "{{ item['value']['sshkeys'] | join('\n') }}"  
 ...  
If possible, using a list of users, each containing the relevant attributes (username, uid, groups, SSH keys, etc.), would significantly simplify the playbook and improve its readability.

Feel free to comment and / or suggest a topic.

Comments

Popular posts from this blog

Dynamic DNS with BIND and ISC-DHCP

I personally prefer to work with hostnames instead of ip-addresses. If you have anything like freeipa or active directory, it will do that for you by registering the client you added to your realm to the managed dns and edit the records dynamically. We can achieve the same goal with just bind and isc-dhcp. I'll use a raspberry pi with raspbian 9 for this setup. So here is a quick tutorial on how to configure the isc-dhcp-server to dynamically update bind. First set a static ip to your server. [archy@ddns ~]$ sudo vim /etc/network/interfaces # interfaces(5) file used by ifup(8) and ifdown(8) # Please note that this file is written to be used with dhcpcd # For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf' # Include files from /etc/network/interfaces.d: source-directory /etc/network/interfaces.d auto eth0 iface eth0 inet static address 172.31.30.5 network 172.31.30.0 broadcast 172.31.30.255 netmask 255.255.255.0 ...

LACP-Teaming on CentOS 7 / RHEL 7

What is teaming? Teaming or LACP (802.3ad) is a technique used to bond together multiple interfaces to achieve higher combined bandwith. NOTE: every clients speed can only be as high as the single link speed of one of the members. That means, if the interfaces I use in the bond have 1 Gigabit, every client will only have a maximum speed of 1 Gigabit. The advantage of teaming is, that it can handle multiple connections with 1 Gigabit. How many connections depends on the amount of your network cards. I'm using 2 network cards for this team on my server. That means I can handle 2 Gigabit connections at full rate on my server provided the rest of the hardware can deliver that speed. There also exists 'Bonding' in the Linux world. They both do the same in theory but  for a detailed comparison check out this  article about teaming in RHEL7 . To create a teaming-interface, we will first have to remove all the interface configurations we've done on the (soon to be) sla...

Push logs and data into elasticsearch - Part 2 Mikrotik Logs

This is only about the setup of different logging, one being done with Filebeat and the other being done with sending logging to a dedicated port opened in Logstash using the TCP / UDP Inputs. Prerequesites: You'll need a working Elasticsearch Cluster with Logstash and Kibana. Start by getting the Log Data you want to structure parsed correctly. Mikrotik Logs are a bit difficult since they show you Data in the interface which is already enriched with Time / Date. That means a message that the remote logging will send to Logstash will look like this: firewall,info forward: in:lan out:wan, src-mac aa:bb:cc:dd:ee:ff, proto UDP, 172.31.100.154:57061->109.164.113.231:443, len 76 You can check them in the grok debugger and create your own filters and mapping. The following is my example which might not fit your needs. Here are some custom patterns I wrote for my pattern matching: MIKROTIK_DATE \b(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?...

FreeIPA - Integrating your DHCPD dynamic Updates into IPA

I recently went over my network configuration and noticed that the dhcp-leases were not pushed into the IPA-DNS yet. So I thought, why not do it now. The setup is very similar to setting it up on a single bind instance not managed by IPA (I've already written a guide about this here ). My setup is done with the following hosts: ipa01.archyslife.lan - 172.31.0.1 inf01.archyslife.lan - 172.31.0.5 First of all, create a rndc-key: [archy@ipa01 ~]$ sudo rndc-confgen -a -b 512 This will create the following file '/etc/rndc-key' [archy@ipa01 ~]$ sudo cat /etc/rndc.key key "rndc-key" { algorithm hmac-md5; secret "secret_key_here=="; }; We also need to make named aware of the rndc-key and allow our remote dhcp server to write dns entries: [archy@ipa01 ~]$ sudo vim /etc/named.conf ... include "/etc/rndc-key"; controls { inet 172.31.0.1 port 953 allow { 172.31.0.5; } keys ...

SSSD - Debugging PAM permission denied

Sometimes there's weird errors in IT that occur on random chance. I've had such an encounter with SSSD in combination with IPA(+AD-Trust) recently, where only sometimes, a connection to one of the IPA-Servers would fail with this error: Jul 13 13:36:42 ipa02.archyslife.lan sshd[3478]: pam_sss(sshd:account): Access denied for user runner: 4 (System error) Jul 13 13:36:42 ipa02.archyslife.lan sshd[3478]: fatal: Access denied for user runner by PAM account configuration [preauth] In my case, it was only happening sometimes when running a basic system setup role using ansible on every host in the entire environment. This way, there was no consistent pattern besides being the same host every time if it failed. First up, add the 'debug_level=X' to every section required in the /etc/sssd/sssd.conf where X is a number from 1 to 10 with 10 being the most verbose. Afterward, restart sssd and check the logs for any obvious problems. 1) If you are using local users, check the...