Ansible Automation: Variables Introduction & How to Create Bulk Users in CentOS Linux Using Variables? (Step By Step)
To store values in Playbooks, Ansible provides the facility of using variables. With the use of Ansible variables, the creation and maintenance of Ansible projects becomes very easy.
The Ansible variables can be used in many ways, some of which are listed below:
1- Package Installation/Removal
2- User Creation/Deletion
3- Files Copying/Removal
4- Services Start/Stop
Variable names can be a combination of letters, numbers and underscores only. It is important to note that the variable names can only start with letters only.
The global scope Ansible variables are set by:
The host scope Ansible variables are directly associated with individual hosts, for example:
3. Play Scope Variables
The play scope Ansible variables are set in the play or in the related structures.
Following is the Ansible variable precedence (from highest to lowest):
Note: For detailed description of Ansible variable precedence, please visit Ansible Documentation
Note: In this article, we have used one user “fakhar” on all three nodes. Its SSH keys have been generated at control node and shared on both managed hosts.
Step-1: Create an inventory file at control node (i.e. CentOS-Ctrl-Node), containing the host names of both managed servers, as shown in below image:
Step-2: Write an Ansible playbook, to create bulk users using variables, as shown below:
Step-3 (Optional): Run the ‘tree’ command at control node, where your playbook is placed (this is just to show you as how the files are placed/organized). See image below:
Step-4 (Optional): On both managed hosts, check the status of users before the execution of playbook. See image below, no such users already exist:
Step-5: Run the playbook using command ‘ansible-playbook -i inventory createUsers.yml’ at control node. See image below.
The playbook has been executed successfully.
Step-6: Check the result on the target managed hosts. All the users (i.e. user1, user2, user3, user4, user5) have been created successfully. See image below: