How to Create User using Ansible Playbook?
Last Updated :
18 Jun, 2024
In the domain of IT mechanization, overseeing client accounts across various servers can be a drawn-out and mistake-inclined task. Ansible, a strong mechanization device, offers a smoothed-out answer for this test by empowering clients to make, design, and oversee client accounts effectively and reliably across different frameworks.
By using the Ansible playbooks we can efficiently work on user management, and organizations can ensure consistency, reliability, and scalability in their IT operations. Ansible's simplicity, flexibility, and extensive module library make it an ideal choice for automating user account management tasks in modern IT environments. Utilizing Ansible, framework administrators can characterize undertakings to make client accounts, set passwords, relegate authorizations, and oversee other client attributes across numerous servers and devices easily. Ansible's agentless engineering permits it to speak with remote hosts over SSH (Secure Shell) or other transport protocols, executing assignments in parallel across distributed environments.
In this guide, we will explore how to use Ansible and create users using the playbook on Linux systems, empowering administrators to maintain framework trustworthiness and effectiveness easily.
What is Ansible?
Ansible is a collection of software tools that enables configuring systems, deploying software, and orchestrating advanced workflows to support application deployment, system updates, and more. Ansible is an open-source automation platform that automates IT tasks, simplifies complex workflows, and accelerates the delivery of infrastructure and applications. We can manage and configure other servers called slave servers from a single server called the master server.
When we install Ansible on the master server, a file is created called Hosts, also known as the inventory path. Inside this inventory path, we give details of slave servers, such as IP addresses, key pair paths, and hostnames. With this, we create a bridge between slave and master to manage configuration.
Developed by Red Hat, Ansible utilizes a simple YAML-based language (YAML Ain't Markup Language) to define automation playbooks, enabling users to describe the desired state of their systems and automate tasks across a wide range of environments, from on-premises servers to cloud platforms. With its agentless architecture and powerful module ecosystem, Ansible empowers organizations to automate repetitive tasks, enforce consistency, and improve scalability, making it an indispensable tool for DevOps teams, system administrators, and network engineers alike. Ansible's ease of use, flexibility, and robust features make it a popular choice for automating infrastructure management, configuration management, application deployment, and continuous delivery pipelines.
They are two working methods in Ansible:

What Are Ansible Ad-hoc Commands?
Ad-hoc command are one-line and short commands. which are executed from ansible command line tool to automate a single task on one or more managed nodes/slave servers these commands are quick and easy but not reusable. Here is the structure of ad-hoc command written as
ansible [group_name or host_name] -m(module) command -a(argument) "parameters"
What Are Ansible Playbooks ?
- Playbooks are ansibles' configuration and orchestration language written in yaml.
- Playbooks are ansible execution files in which files there are steps of tasks defined and it plays a plays like number of tasks are there.
- Playbooks serves as the primary for automating the tasks and orchestration management.
- Playbooks allow you to define the desired state of your infrastructure, and Ansible takes care of ensuring that the systems reach that state.
Ansible Playbook Example
The following is the example of writing playbook:
- name: Install and start Nginx
hosts: web_servers
become: yes
tasks:
- name: Install Nginx package
yum:
name: nginx
state: present
- name: Ensure Nginx service is running
service:
name: nginx
state: started
enabled: yes
Why use Ansible Playbooks?
The following are the some of the reasons to use ansible playbooks:
- Automation: Playbooks helps in automating the complex tasks and workflows. It facilitates in maintaining the consistent and reliable configuration management across systems.
- Declarative Syntax: Ansible's YAML-based playbooks provide a simple, human-readable syntax to define tasks, making it easy to understand and maintain infrastructure as code.
- Idempotency: Playbooks helps in ensuring the idempotent execution, where tasks can be run multiple times without causing unintended changes, ensuring desired state configuration.
How to Create User using Ansible Playbook: A Step-By-Step Guide
Here, we are going to create user using ansible playbook in aws EC2 instance.
Step 1: Create An AWS account And launch EC2 instance
Launch An Instance With these below Configuration:
- AMI- amazon Linux 2
- Instance type- t2.micro
- Security group- allow SSH(22),HTTP(80), HTTPS(443) traffic from anywhere
- Configure storage - 8gb with root volume type gp2
- Connect the ec2 instance with the terminal with the help of ssh.
ssh -i "keypair-pem file" ec2-user@<instance-public-ip address>compute-1.amazonaws.com

Step 2: Installing Ansible
- Install Ansible with amazon-linux-extras and the version of ansible is 2.9.23.
sudo amazon-linux-extras install ansible2

Step 3: Hosts file configuration
- After installed the ansible in /etc/ansible directory a hosts file is created.
- we need to configure this file called hosts.
sudo vi /etc/ansible/hosts

- Configure the inventory file or hosts file located at /etc/ansible/hosts with slave server's details such as host_name,ansible_host,ansible_user, ssh_private_key_file path.....
- For this create one group name as [localhost] you can configure this group name as you wish.
- Below this group localhost we add the slave server details and set the permissions to the keypair with read access only
sudo chmod 400 keypair_name.pem
- Define the inventory file in the Ansible Manage Node as show in the below one.
[group_name]
host_name ansible_host=<Private-IP> ansible_user=ec2-user ansible_ssh_private_key_file path=/parh/to/keypair

Step 4: Check Connection Between the Master and Slave server
- Now we need to check the connection to this slave server with the ping module.
ansible [host_name] -m ping

Step 5: Create a Playbook file to Create User
- To write a playbook we need to create file for this playbook
sudo vi filename.yml

- Write the Playbook Code in yaml file as shown in below:
- name: To create a User using ansible playbook
hosts: localhost
become: yes # Use sudo privileges if required for user creation
tasks:
- name: Adding the user
user:
name: Vamsi # Replace with the username you want to create
state: present
shell: /bin/bash # Specify the shell for the user (optional)
comment: "surname is KANAKALA" # Add a comment for the user (optional)
createhome: yes # Create the user's home directory (optional)

- You can check the playbook syntax error with the following command:
ansible-playbook <playbook_filename> --syntax-check
Step 6: Execute the Playbook
- Execute the playbook file playbook.yml which has yaml script.
ansible-playbook adduser.yml

- The above screenshot illustrates about the playbook's successful execution.
Step 7: Verifying User Creation
- We need to make sure the user is successfully created or not.
- We can check the user id and users' details from this ansible by using ad-hoc command.
ansible localhost -m command -a "id Vamsi"

User Roles in Ansible
The following are the some of the roles of user in providing the modular and components for managing tasks effectively:
- Modular Structure: Roles helps in breaking down the complex configurations into smaller, manageable units, enhancing playbook organization.
- Code Reusability: These Roles helps to promote reuse of tasks, variables, and handlers across different projects, reducing duplication of effort.
- Encapsulated Functionality: Each role encapsulates specific responsibilities like configuring services or deploying applications, ensuring clear separation of concerns.
- Dependency Management: Roles can depend on other roles, facilitating structured execution order and enhancing playbook flexibility.
- Variable Scoping: Roles define clear boundaries for variables, minimizing conflicts and improving playbook reliability and predictability.
Similar Reads
How To Install Docker Using Ansible Playbook ?
Docker is a software platform that allows you to build, test and deploy applications that use OS-Level virtualization to deliver software in packages called "containers". Containers - Docker package software into standardized units called "Containers". Docker is a stand-alone tool. which means no ne
7 min read
How to Install Helm using Ansible Playbook?
Managing various infrastructure and applications under different conditions in the present dynamic IT landscape can challenge. Automation tools like Ansible assist with smoothing out these undertakings by providing a basic yet amazing method to automate configuration management, application deployme
8 min read
How to Dry Run Ansible Playbook
Another core aspect of IT automation is the ability to ensure that configurations and deployments are correct before they are applied to production. One of the most widely recognized automation tools, Ansible, has features associated with a "dry run" or "check mode" that display the changes it would
8 min read
How To Install Python Using Ansible Playbook ?
Automation is now absolutely necessary for the effective management of software deployment and infrastructure in IT landscape. Ansible emerges as a main automation tool, eminent for its effortlessness, simplicity, and flexibility. Software installation, configuration management, and application depl
7 min read
How To Install Tomcat Using Ansible Playbook?
Automating software installation and configuration tasks is fundamental for efficient DevOps practices. Ansible, an open-source automation tool, works on this interaction by permitting you to characterize the framework as code and automate tasks across various servers. In this article, we will zero
7 min read
How To Install Java Using Ansible PlayBook ?
In today's dynamic IT landscape, effective management and automation of software installations across various servers are pivotal for maintaining consistency, dependability, and versatility. Ansible, an open-source automation tool, has acquired huge popularity for its simplicity and flexibility in a
7 min read
How To Install HTTPD Using Ansible Playbook ?
Ansible is an open-source automation tool that improves IT orchestration, the design of the board, and application deployment. It works over SSH and requires no agent to be installed on a managed host. It is lightweight, efficient, and easy to set up, making it suitable for automating tasks on a var
8 min read
How To Install MYSQL Using Ansible Playbook ?
Introducing MySQL physically on different servers can be a tedious and mistake-inclined process. Be that as it may, with Ansible, an open-source mechanization apparatus, you can computerize the establishment and setup of MySQL across your framework effectively and proficiently. By allowing you to de
6 min read
How to generate a unique username using Python
A username is a unique name that is mainly used on websites and apps. A username is used to identify a person. For example, if your name is Akshay and you want to create your account on any social media app, here we need a username such that another person can find us. It is not possible to search b
4 min read
How to Install Git Using Ansible ?
Git is a powerful and broadly utilized version control system that assumes a crucial role in current software development work processes, it gives developers a powerful structure for tracking changes in source code, planning cooperative work, and managing project chronicles proficiently. With its co
6 min read