Skip to Content

2 ways to create users with Ansible

In the realm of IT automation, Ansible has emerged as a powerful tool for streamlining various administrative tasks.

Among these tasks, user management stands out as a common and often repetitive process. Ansible provides two primary approaches for creating users: ad-hoc commands and playbooks.

This article aims to shed light on both ad-hoc commands and playbooks as means to create users with Ansible.

We will explore their distinctive features, use cases, and considerations, enabling you to make informed decisions when it comes to user management in your infrastructure.

Get Your Free Linux training!

Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career! Learn Linux for Free!

Understanding user module in Ansible

The user module in Ansible is a powerful tool that allows you to manage user accounts on Linux and Unix-based systems.

With this module, you can create, modify, and delete user accounts, set user attributes, manage SSH keys, and more.

The user module simplifies user management tasks by abstracting the underlying system-specific commands and configurations.

The user module provides a wide range of options to customize user creation and management. Some of the key options include:

  • name: Specifies the username.
  • state: Defines the desired state of the user account (e.g., present to create or ensure the user exists, absent to remove the user).
  • uid: Sets the user’s numerical ID.
  • groups: Adds the user to specific groups.
  • shell: Defines the user’s default shell.
  • home: Specifies the user’s home directory.
  • password: Sets the user’s password (can be provided as a plain text or encrypted value).
  • append: Appends the user to existing groups instead of removing them from other groups.
  • move_home: Indicates whether to move the user’s home directory when the username changes.

 

In addition to the above options, the user module supports various other features such as managing SSH keys, setting expiration dates for passwords, managing login and logout scripts, and more.

By utilizing the user module in Ansible, you can automate user management tasks, enforce consistent user configurations, and ensure the security and integrity of user accounts across multiple systems.

Please note that the available options and functionalities may vary depending on the version of Ansible and the target operating system. It’s recommended to refer to the Ansible documentation for detailed information on the user module and its usage.

Create users with Ansible ad-hoc command

Firstly, we will delve into ad-hoc commands, which provide a quick and straightforward way to perform one-time tasks.

With a concise syntax and minimal setup, ad-hoc commands allow administrators to execute user creation tasks directly from the command line.

We will demonstrate the usage of ad-hoc commands for creating users and discuss their advantages and limitations.

To create a user using an ad-hoc command with Ansible, you can use the ansible command-line tool along with the user module. Here’s an example of how to do it:

Inventory: Create an inventory file that lists the target hosts where you want to create the users. Here’s an example inventory file:

[all:vars]
ansible_ssh_user=howtouselinux
ansible_ssh_pass='yourpassword'
ansible_become_pass= 'yourpassword'
ansible_ssh_common_args='-o StrictHostKeyChecking=no'
become_user= root
ansible_connnection= ssh
ansible_become_method= sudo
[target_hosts]
192.168.1.100
192.168.1.101

Then we need to run the following command.

ansible -i inventory target_hosts -m user -a "name=john1 password={{ newpassword|password_hash('sha512') }} state=present createhome=yes" -b --extra-vars "newpassword=Nihao"

In the above command:

  • target_hosts refers to the group or specific hosts defined in your inventory file.
  • -m user specifies that you want to use the user module.
  • -a is used to provide arguments to the module. Here, you specify the user details such as name, password, state, and createhome.
  • -b option allows you to execute commands or tasks with escalated privileges, typically using the sudo or su command. It enables you to perform operations that require root or administrative access on the target hosts.
  • The –extra-vars option allows you to pass additional variables or parameters to the Ansible ad-hoc command. These variables can be used in the command or task execution, providing dynamic inputs or customization options.

 

Replace target_hosts with the appropriate host or group name from your inventory file. Adjust the name, password, state, and createhome values to match your requirements.

When you execute the command, Ansible will connect to the target hosts and create the specified user with the provided details.

howtouselinux.com | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 50303,
"home": "/home/john",
"name": "john",
"password": "NOT_LOGGING_PASSWORD",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 50301

Please note that using ad-hoc commands is suitable for simple tasks or one-time operations. For more complex or repetitive tasks, it’s recommended to use Ansible playbooks, as they provide better structure, reusability, and maintainability.

Create users with Ansible playbook

Next, we will shift our focus to Ansible playbooks, which offer a more structured and scalable approach to user management. Playbooks allow you to define user creation tasks as reusable and automated procedures.

We will provide a step-by-step guide to creating a playbook that creates users, covering essential concepts such as inventory, tasks, and variables. By leveraging playbooks, you can efficiently manage user creation tasks across multiple hosts and ensure consistent user configurations.

To create users with Ansible, you can follow these steps:

1. Playbook: Create an Ansible playbook to define the tasks for creating users. Use a text editor to create a .yml or .yaml file. Here’s an example playbook:

- name: Create users
  hosts: target_hosts
  become: yes  # Run tasks with root/sudo privileges

  tasks:
    - name: Create user
      user:
        name: john  # Username
        password: "{{ 'mypassword' | password_hash('sha512') }}"  # Encrypted password
        state: present  # Ensure the user is present
        createhome: yes  # Create the user's home directory

 

In the above example, replace target_hosts with the name of the group defined in your inventory file. Modify the name and password fields as per your requirements.

2. Run the playbook: Save the inventory file and playbook, and run the playbook using the ansible-playbook command. Here’s an example command:

ansible-playbook -i inventory your_playbook.yml

When you execute the playbook, Ansible will connect to the target hosts and create the specified users. The users will have the provided username, encrypted password, and their respective home directories.

Note: Ensure that the Ansible control node has SSH connectivity to the target hosts and has sufficient privileges to create users.

In the playbook example provided earlier, the password field is used to specify the password for the user being created.

However, it’s important to note that storing passwords in plain text is not a recommended practice for security reasons.

To address this, Ansible provides a built-in filter called password_hash that allows you to encrypt the password before storing it in the playbook. The password_hash filter takes the plain-text password as input and generates a hashed representation of it.

Here’s how the password field is used in the playbook example:

password: "{{ 'mypassword' | password_hash('sha512') }}"

In the above example, ‘mypassword’ is the plain-text password that you want to encrypt.

The password_hash filter is applied to the plain-text password, specifying the hashing algorithm (sha512 in this case) to generate the hashed representation of the password.

When the playbook is executed, Ansible will generate the hashed password based on the provided plain-text password and store it in an encrypted format. This helps to protect the passwords from being exposed in the playbook or during the execution.

It’s worth mentioning that the password_hash filter is a one-way hash function, meaning that the original plain-text password cannot be derived from the hashed representation. When authenticating users, you would typically compare the provided password with the stored hashed password for verification.

It’s recommended to use a secure method, such as Ansible Vault, to store sensitive information like passwords in an encrypted format. Ansible Vault allows you to encrypt entire files or specific variables, providing an added layer of security for sensitive data.

how to verify the new user with Ansible

Here’s an example of an Ansible script to verify a user in Linux:

---
- name: Verify user in Linux
hosts: <target-host>
become: true
tasks:
- name: Check if user exists
command: id <username>
register: user_check
ignore_errors: true

- name: Display user information
debug:
msg: "User '{{ username }}' exists."
when: user_check.rc == 0

- name: Display error message if user doesn't exist
debug:
msg: "User '{{ username }}' does not exist."
when: user_check.rc != 0

 

Replace <target-host> with the hostname or IP address of the target Linux system you want to verify the user on. Also, replace <username> with the actual username you want to verify.

In this script, the id command is used to check if the specified user exists. The register keyword saves the output of the command in the user_check variable. The ignore_errors option is set to true to prevent the script from failing if the user doesn’t exist.

The subsequent tasks use the debug module to display messages based on the result of the user verification. If the user exists (exit code 0), it will display a message indicating that the user exists. If the user doesn’t exist (non-zero exit code), it will display a message stating that the user doesn’t exist.

Make sure you have Ansible installed and the necessary SSH connectivity to the target host before executing this script. Modify it as per your requirements and environment.

Create users with more options 

Here’s an updated Ansible script to create a user in Linux with the options for password expiration:

---
- name: Create user in Linux
  hosts: <target-host>
  become: true
  tasks:
    - name: Create user
      user:
        name: <username>
        state: present
        shell: /bin/bash
        groups: <additional-groups>
        password: <encrypted-password>
        expires: -1
        password_expire_min: <min-days>
        password_expire_max: <max-days>
      when: user_check.rc != 0

 

In this updated script, the user module includes the following additional options related to password expiration:

  • expires: An expiry time for the user in epoch, it will be ignored on platforms that do not support this.
  • password_expire_min: Specifies Minimum number of days between password change. Replace <min-days> with the desired minimum number of days.
  • password_expire_max: Specifies Maximum number of days between password change. Replace <max-days> with the desired maximum number of days.

 

Make sure you adjust the script according to your specific requirements and environment. Ensure you have Ansible installed and the necessary SSH connectivity to the target host before executing the script.