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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Random Forest Algorithm in Machine Learning
A Random Forest is a collection of decision trees that work together to make predictions. In this article, we'll explain how the Random Forest algorithm works and how to use it. Understanding Intuition for Random Forest AlgorithmRandom Forest algorithm is a powerful tree learning technique in Machin
7 min read
Spring Boot Interview Questions and Answers
Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read