Ansible
////////////////////////////
////////////////////////////
How to write a multitask playbook in ansible
The biggest beauty of ansible playbook is we can perform multiple and complex task easily. So, use of multitask playbook become very useful when we want to perform multiple task at a time that’s why in this tutorial we are going to learn how to write multitask playbook in ansible.
Multitask playbook in Ansible
Let understand meaning of multitask with scenario suppose we have three groups backup, web, dev. In backup group suppose we take our daily routine backup and in web and dev group suppose we do package and build update on daily basis. So, in this scenario we have two option we can write three playbook and run one by one on every group that will consume our time as well our resources and another one is we can write multitask playbook.
In which we will define all task separately according to group like in backup group we will perform backup task and dev group we will do deploy and so on that will save our time means no need to run multiple playbook. We can perform our task by executing a singly playbook. Let take a demo how to write multitask playbook in ansible. First make inventory file with group accordingly as shown below.
1 | cat ansible-inventory |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | linuxdady.com [backup] linuxdady.com 172.17.0.2 [web] 172.17.0.2 172.17.0.3 [dev] 172.31.86.202 [db:children] backup web dev |
[Click & Read:– Ansible playbook example with explanation ]
[Click & Read:– Ansible ad hoc method in simple way for beginners]
After making inventory file we are going to write ansible playbook with name multitask.yml.
1 | vim multitask.yml |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | - name: Taking daily routine backup hosts: backup tasks: - name: Make zip file first archive: path: /etc dest: /opt/etc.tar.bz2 format: bz2 ################################################ - name: Web server package installtion hosts: web tasks: - name: Going to install httpd package yum: name: httpd state: present - name: Restart service httpd, in all cases service: name: httpd state: restarted ################################################# - name: Going to deploy code hosts: dev tasks: - name: Going to copy code copy: src: /opt/etc.tar.bz2 dest: /data - name: Going to unzip our code raw: tar -xvf /data/etc.tar.bz2 |
In this playbook we have written different task for different group as show in above fig. Now we are going to execute this playbook. First we will run in dry mode to check every thing is ok or not then we will run finally on all group as define in inventory file.
1 2 | ansible-playbook multitask.yml -C ansible-playbook multitask.yml |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | PLAY [Taking daily routine backup] *************************************************************************************************** TASK [Gathering Facts] *************************************************************************************************************** ok: [172.17.0.2] ok: [linuxdady.com] TASK [Make zip file first] *********************************************************************************************************** changed: [linuxdady.com] changed: [172.17.0.2] PLAY [Web server package installation] ************************************************************************************************ TASK [Gathering Facts] *************************************************************************************************************** ok: [172.17.0.2] ok: [172.17.0.3] TASK [Going to install httpd package] ************************************************************************************************ changed: [172.17.0.3] ok: [172.17.0.2] TASK [Restart service httpd, in all cases] ******************************************************************************************* changed: [172.17.0.2] changed: [172.17.0.3] PLAY [Going to deploy code] ********************************************************************************************************* TASK [Gathering Facts] *************************************************************************************************************** ok: [172.31.86.202] TASK [Going to copy code] ************************************************************************************************************ changed: [172.31.86.202] TASK [Going to unzip our code] ****************************************************************************************************** skipping: [172.31.86.202] PLAY RECAP *************************************************************************************************************************** 172.17.0.2 : ok=5 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 172.17.0.3 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 172.31.86.202 : ok=2 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 linuxdady.com : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 |
Conclusion
In this tutorial we have explained how to write multitask playbook in ansible and what are the benefit of using multitask playbook If anyone have query write me in comment box. I will try my best to resolve that query.
Interview question related to ansible playbook
- How many tasks we can define in a playbook?
Ans. We can define N number of tasks but be sure once with ansible control node configuration.
- What is fact in ansible?
Ans. Please write answer in comment box.
////////////////////////////////////////////////////////
Scenario based ansible playbook example
Ansible playbook example will help to understand the use case of playbook. But before doing example of ansible playbook we should understand the basic difference between ad hoc and playbook. Which one we should prefer between playbook and ad hoc method and why?
Playbook versus Ad hoc method
So, let’s be familiar with playbook and ad hoc method and differentiate it first.
Ansible playbook Format
From above diagram I think we are well known about ad hoc and playbook method. We can use anyone depends on our requirement. But for repetitive task playbook is more preferable method because to type command every time become hectic task in ad hoc method. So, before writing playbook we should try to understand its format means how to write playbook and its basic parameter. I have written a very simple playbook to explain all the parameters of playbook.
1 2 3 4 5 | - hosts: web tasks: - name: Will display action state in fly mode Module Name: Action: That we want to perform |
1 | - hosts: web |
hosts parameter have the list of host name or group name where we want to perform our task. For better understanding suppose we have web group with multiple machine then this parameter will look into all machines in web group only.
1 | name: This parameter will display action state in fly mode |
This parameter is used to display anything in fly mode while our playbook is running. Suppose we have three tasks in our playbook, and we want to print a message when our first task become complete then this parameter come in scenario. We can ignore this parameter depend on choice it’s not mandatory.
1 2 3 4 5 6 7 8 9 | tasks: - name: Create demo.txt file at all machine file: path: /tmp/demo.txt state: touch - name: Install ftp package with yum yum: name: ftp* state: present |
tasks parameter is used to define action that you want to perform on your host or host group. Suppose we want to install yum server that means we are installing our required package by yum module. This is a type of task. We can define N number of tasks depend on our requirement.
Ansible playbook example
Now we are going to take an example of ansible playbook. We will write our playbook and then learn how to run that playbook in change mode and dry mode.
Example 1
In this ansible playbook example we will create a very basic and simple playbook. By this playbook we will create a file demo.txt in /tmp directory on our all machine which belongs to web group then we will copy it into /mnt directory with example.txt name.
1 | vim p1.yml |
1 2 3 4 5 6 7 8 9 10 11 | - hosts: web tasks: - name: Going to create demo.txt file file: path: /tmp/demo.txt state: touch mode: 0777 - name: Copy demo.txt file into mnt directory copy: src: /tmp/demo.txt dest: /mnt/exmple.txt |
We created our first playbook now there are two way to execute this playbook.
- Dry Mode (Check Mode)
- Change Mode
Dry Mode
In ansible playbook dry mode is also called check mode. For better understanding about dry mode let’s take an example. Suppose I have write a playbook and I am not sure how to react this playbook on managed node or you can say I am in doubt this playbook will run properly or not on manage nodes. So, in my mind a question raised I should execute this playbook on managed node, but my playbook changes should not impact on mange node means dry mode is a way by which we can execute playbook in fly mode without doing any changes on manage nodes.
1 | ansible-playbook p1.yml –check |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | PLAY [web] *************************************************************************************************************************** TASK [Gathering Facts] *************************************************************************************************************** ok: [172.17.0.2] ok: [linuxdady.com] TASK [Ping all the machine] ********************************************************************************************************** ok: [linuxdady.com] ok: [172.17.0.2] TASK [Copy demo.txt file into mnt directory] ***************************************************************************************** changed: [linuxdady.com] changed: [172.17.0.2] PLAY RECAP *************************************************************************************************************************** 172.17.0.2 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 linuxdady.com : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 |
We can also use -C option to execute the playbook in dry mode.
1 | ansible-playbook p1.yml –C |
Change Mode
Change mode means suppose we have write a playbook and we are sure about that playbook action then we will run that playbook on change mode. For better understanding you can say if you will run playbook in change mode then it will make the changes on our manage node. Wrong or write action does not matter it will perform action that will be written in playbook.
1 | ansible-playbook p1.yml |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | PLAY [web] *************************************************************************************************************************** TASK [Gathering Facts] *************************************************************************************************************** ok: [172.17.0.2] ok: [linuxdady.com] TASK [Going to create a file on all machines] **************************************************************************************** changed: [linuxdady.com] changed: [172.17.0.2] TASK [Copy demo.txt file into mnt directory] ***************************************************************************************** changed: [linuxdady.com] changed: [172.17.0.2] PLAY RECAP *************************************************************************************************************************** 172.17.0.2 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 linuxdady.com : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 |
Ansible playbook example 2
Suppose we want to install postfix package on all machines in web group as well we want to enable and restart the service of postfix.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | - hosts: web gather_facts: false user: centos become: true tasks: - name: This is demo of postfix installation yum: name: postfix* state: installed - name: Now we are going to start postfix service service: name: postfix state: restarted enabled: yes |
When write a playbook be careful about indentation of yml language because if we will do indentation wrong then while executing playbook it will show syntax error.
[Click & Read:– Ansible basic modules that should be learn must]
[Click & Read:– Ansible ad hoc method in simple way for beginners]
Ansible playbook example 3
Now lets move a little bit next and take a scenario suppose I want to install webserver on 1000 host and I want to configure it on port 80 as well add port into firewall service.
1 | vim p3.yml |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | - name: This sets up an httpd webserver hosts: web tasks: - name: Install apache packages yum: name: httpd state: present - name: ensure httpd is running service: name: httpd state: started - name: Open port 80 for http access firewalld: service: http permanent: true state: enabled - name: Restart the firewalld service to load in the firewall changes service: name: firewalld state: restarted |
Conclusion
In this tutorial we have tried to cover ansible playbook example and playbook basic format that will help to make easy to understand concept of ansible playbook. But still anyone have queries write me in comment box. I will try my best to resolve them.
Ansible scenario based interview question.
- What are the difference between dry mode and change mode ?
- Interviewer always ask scenario base interview question on playbook. Like in my last interview interviewer asked Deepak does you have any idea about how to write playbook. Then I told him yes. Then he told me his requirement.
- He has 1000 server and he want to add user with name MAX on all server.
- After adding user on all server there is a file demo.txt give its ownership to MAX and add any content into this file but before adding content take backup of current file.
- Second question interviewer asked me Deepak we cannot open ssh port then should I prefer ansible or not and why?
- The next interview create a scenario related to server. He want to install ftp package over 1000 server but ssh port is not allowed to open in his company is it possible to install ftp package if yes, how and if not then why?
ANS. Please write your answer in comment box.
////////////////////////////////////////////////////////
Understand basic modules in ansible
What are the use cases of modules in ansible and why you cannot say I am perfect in ansible without knowledge of modules? How many modules should I know to say I am perfect in ansible. All these stuffs we are going to discuss in this tutorial. So, before moving next all these stuffs should be clear because ansible modules play very important role in life of devops engineers.
Which modules in ansible should I learn?
There are tons of modules in ansible and no need to learn all these modules because suppose we are using ansible only for OS level then why we should learn switch, router, firewall modules. So now my question is after how many modules can I say yes I can work very well on ansible.
If I know 15-20 modules then can I say yes, I am perfect in ansible. There are lots of question that’s raising in my mind. But to be perfect in ansible is depend on you infra not on count of modules. Suppose in you infra you are using only 15 modules then you can say our infra requirement is this and we are using this module for this task.
Prerequisite for lab
Control Node IP :– linuxdady.com (172.31.86.202)
Manage Node IP :– 172.17.0.2, 172.17.0.3, 172.17.0.4
Ansible should be installed on Control node.
Control node and Mange node should be password less.
[Click & Read:– How to install ansible step by step very easy]
[Click & Read:– Ansible ad hoc method in simple way for beginners]
Now we are going to create a simple inventory file to perform lab. Kindly have a look of below static inventory file and change it accordingly.
1 2 3 4 5 6 7 8 9 10 11 | linuxdady.com [web] linuxdady.com 172.17.0.2 [dev] 172.17.0.2 172.17.0.3 172.17.0.4 [db:children] web dev |
Remember one thing when you will install package of ansible all default modules will install automatically. Suppose if we need any particular module then we can write our custom module. Here we are going to discuss basic modules in ansible that we are using in our daily routine. Let’s do basic modules of ansible.
Module 1: Command modules in ansible
The command module have the capability to execute command on manage or targeted nodes. We can run all our OS level commands parallelly from control node to multiple or single manage node as required. Suppose we want to create a directory on all manage node then simply we can create with the help of mkdir command no need to go on individually machine. Just we will execute this command from control node and command will executed on all managed nodes automatically. Syntax of command module.
1 | ansible <Name of group or machine IP> -m <module> <your command that want to execute> <options> |
1 2 3 | ansible web -m command -a 'uptime' -k ansible dev -m command -a 'uptime' -u centos -k ansible dev -m command -a 'uptime' |
-k :- Use -k option if your machine is not password less.
-u :- Option is use for username from that user we are going to perform action on manage node
Example 1
Now we are going to push changes on single machine you can push changes on group or over the group just change IP address with your group name in below commands.
1 2 3 4 | ansible 172.17.0.4 -m command -a 'uptime' -k SSH password: 172.17.0.4 | CHANGED | rc=0 >> 01:32:53 up 13 min, 1 user, load average: 0.00, 0.08, 0.08 |
1 2 3 4 | ansible 172.17.0.4 -m command -a 'uptime' -k -u centos SSH password: 172.17.0.4 | CHANGED | rc=0 >> uid=1001(centos) gid=1001(centos) groups=1001(centos) |
1 2 3 4 | ansible 172.17.0.4 -m command -a 'free -m' 172.17.0.4 | CHANGED | rc=0 >> total used free shared buff/cache available Mem: 989 305 86 6 597 533 Swap: 819 0 819 |
Suppose we are not well aware about any module in ansible then we can read docs related to that module. Ansible is providing their official docs related to modules. Suppose we want to read command module then use below ansible syntax.
1 2 3 4 | ansible-doc <Name of module> ansible-doc command ansible-doc copy ansible-doc shell |
So, we can take help of ansible docs to explore any module.
Module 2: raw module
raw module is also used to execute command on targeted node. But the workflow of raw module is little bit different from command module means raw module is not depend on python without python we can execute our commands simply on targeted node by establishing ssh connection. But in case of command module python should be installed on targeted nodes. Raw module also have one more beauty we can also run multiple command at a time. Let’s understand it by example.
Example 1
As shown in below example. We have executed three commands at a time on web group means we can execute multiple command at a time according to our requirement.
1 | ansible web -m raw -a 'uptime; free -m; date' |
Module 3: Shell module
Shell module is identical to command module. But with the help of shell command we can run highly complex command with special shell operator like < > | ; & $HOME etc. But command module is more secure as compare to shell modules. So, give preference to command module while execute command. Shell module is mainly used to execute script means suppose you want to execute a script on all manage node then copy it and use shell module to execute that scrips.
1 2 3 4 5 6 7 8 9 10 11 12 | ansible web -m shell -a "ls -lrt|awk '{print $9}'|sed '/^$/d' > /tmp/demo.txt; cat /tmp/demo.txt" linuxdady.com | CHANGED | rc=0 >> total 12 drwxrwxr-x 2 centos centos 27 Nov 25 23:14 all-inventory drwxrwxr-x 2 centos centos 6 Nov 25 23:28 r drwxrwxr-x 2 centos centos 27 Nov 28 03:26 Prod-Inventory -rw-r--r-- 1 centos centos 6368 Dec 1 20:58 i1q -rw-r--r-- 1 root root 44 Dec 1 22:25 text 172.17.0.2 | CHANGED | rc=0 >> total 4 -rw-r--r-- 1 root root 44 Dec 2 03:25 text |
Command VS raw VS shell modules in ansible with difference
Let’s have a difference between command, raw and shell modules. Because these modules create lots of confusion.
Module 4: Copy module
Ansible copy module is used to copy files and directory from the local machine to remote/managed node. We can manage lot of task with copy modules like copy, backup, permission, ownership, group ownership, can insert content into file etc. This is versatile and easy to use modules.
Example 1
For example, suppose we want to copy a file from remote server to all destination hosts.
1 | ansible web -m copy -a 'src=test.sh dest=/opt' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | [centos@linuxdady ~]$ ansible web -m copy -a 'src=test.sh dest=/opt' linuxdady.com | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "checksum": "1a51ef27431fc7adb97802a137372d4bbf59d582", "dest": "/opt/test.sh", "gid": 0, "group": "root", "md5sum": "01868fb498ba0bf57f8c05fc88b0df30", "mode": "0644", "owner": "root", "size": 21, "src": "/home/centos/.ansible/tmp/ansible-tmp-1575264572.98-255556825944559/source", "state": "file", "uid": 0 } 172.17.0.2 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "checksum": "1a51ef27431fc7adb97802a137372d4bbf59d582", "dest": "/opt/test.sh", "gid": 0, "group": "root", "md5sum": "01868fb498ba0bf57f8c05fc88b0df30", "mode": "0644", "owner": "root", "size": 21, "src": "/home/centos/.ansible/tmp/ansible-tmp-1575264572.97-124505758463934/source", "state": "file", "uid": 0 } |
This command copy test.sh file on all machine which is list in web group. Login to all machine and check our file has been copied or not properly.
1 | ansible web -m command -a 'ls -ltrh /opt' |
As shown in below diagram file has been copied as required. Let’s have a look of below diagram.
Example 2
Suppose we have edit some content into file and we want to copy this file at manage node. Suppose file is already existed at remote destination. Now we are going to copy this and then we will take backup of existing file.
1 | ansible web -m copy -a 'src=test.sh dest=/opt backup=yes' |
1 2 3 4 5 6 7 8 9 10 11 | [centos@linuxdady opt]$ ssh centos@172.17.0.2 Last login: Mon Dec 2 06:05:40 2019 from 172.17.0.1 [centos@d23524b07c9b ~]$ ls -ltrh /opt/ total 8.0K -rw-r--r-- 1 root root 21 Dec 2 05:29 test.sh.3075.2019-12-02@06:04:28~ -rw-r--r-- 1 root root 23 Dec 2 06:04 test.sh [centos@d23524b07c9b ~]$ cat /opt/test.sh echo > hello ansible 1 [centos@d23524b07c9b ~]$ cat /opt/test.sh.3075.2019-12-02\@06\:04\:28~ echo > hello ansible [centos@d23524b07c9b ~]$ |
Example 3
Suppose we want to write content in a file at all mange node at a time. Then use content option.
1 | ansible web -m copy -a 'content="hello ansible" dest=/opt/demo.txt' |
Similarly, we can change file permission, ownership and group ownership according to our requirement.
1 | ansible web -m copy -a 'src=test.sh dest=/mnt mode=0777 owner=centos group=centos' |
If you want to know more use ansible official docs. There will be detail knowledge with option and example. Use below command for copy module docs.
1 | ansible-doc copy |
Module 5: fetch module
Fetch module works like copy module but in reverse direction means copy module use to copy from local host to managed node. But fetch module copy file from manage node to local host. It will copy all file at a time from all manage node and it will manage their backup by their hostname. But mind it if file will already exit it will overwrite existing file.
1 | ansible web -m fetch -a 'src=/opt/test.sh dest=data' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | linuxdady.com | CHANGED => { "changed": true, "checksum": "7b320b1dc0c867516cf00728df488daa3532bc1f", "dest": "/home/centos/data/linuxdady.com/opt/test.sh", "md5sum": "37bc018071eae9a0e879c31b2f9aa554", "remote_checksum": "7b320b1dc0c867516cf00728df488daa3532bc1f", "remote_md5sum": null } 172.17.0.2 | CHANGED => { "changed": true, "checksum": "7b320b1dc0c867516cf00728df488daa3532bc1f", "dest": "/home/centos/data/172.17.0.2/opt/test.sh", "md5sum": "37bc018071eae9a0e879c31b2f9aa554", "remote_checksum": "7b320b1dc0c867516cf00728df488daa3532bc1f", "remote_md5sum": null } |
1 2 3 4 5 6 7 8 9 10 11 12 | [centos@linuxdady ~]$ ls data/ 172.17.0.2 linuxdady.com [centos@linuxdady ~]$ tree data data ├── 172.17.0.2 │ └── opt │ └── test.sh └── linuxdady.com └── opt └── test.sh 4 directories, 2 files |
Copy VS Fetch module
Module 6: File module
With the help of file module, we can perform task related to mkdir, touch, chown, chgrp, rm, soft link, hard link, Selinux policy etc. If we are well aware about file modules in ansible then there is no need to use above given commands. Syntax of file module.
1 | ansible web -m file -a 'path=/opt/demo state=directory mode=0775' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | linuxdady.com | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "gid": 0, "group": "root", "mode": "0775", "owner": "root", "path": "/opt/demo", "size": 6, "state": "directory", "uid": 0 } 172.17.0.2 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "gid": 0, "group": "root", "mode": "0775", "owner": "root", "path": "/opt/demo", "size": 6, "state": "directory", "uid": 0 } |
Let check demo directory has been created or not.
1 2 3 4 5 6 7 8 9 10 | [centos@linuxdady opt]$ ansible web -m command -a 'ls -ltrh /opt' linuxdady.com | CHANGED | rc=0 >> total 4.0K drwx--x--x 4 root root 26 Nov 22 20:28 containerd -rw-r--r-- 1 root root 3.8K Nov 22 23:30 Output.txt drwxrwxr-x 2 root root 6 Dec 2 03:05 demo 172.17.0.2 | CHANGED | rc=0 >> total 0 drwxrwxr-x 2 root root 6 Dec 2 01:40 demo |
Suppose we want to delete demo directory then use absent parameter.
1 | ansible web -m file -a 'path=/opt/demo state=absent' |
Let create a file with file module.
1 | ansible web -m file -a 'path=/opt/demofile state=touch mode=0755' |
Create a soft link with file module.
1 | ansible web -m file -a 'src=/etc/hosts dest=/opt/hosts state=link' |
Now check its working or not.
1 | ansible web -m command -a 'ls -ltrh /opt' |
Now let create hard link.
1 | ansible web -m file -a 'src=/etc/hosts state=hard dest=/media/hosts' |
Module 7: Package module
Package module is used to install, remove and to update package into Linux based OS like RedHat, Centos, Ubuntu, Debian etc. Syntax of package module.
1 2 3 4 | ansible web -m package -a 'name=ftp state=installed use=yum' ansible web -m package -a 'name=ftp state=installed use=apt' ansible web -m package -a 'name=ftp state=absent use=yum' ansible web -m package -a 'name=ftp state=latest use=yum' |
Module 8: Yum module
Yum module is identical to package module but little bit simple to use then package module. BY this module we can installs, upgrade, downgrades, removes, and lists packages and groups with the `yum’ package manager. Syntax of yum module.
1 2 3 4 | ansible web -m yum -a 'name=httpd state=installed' ansible web -m yum -a 'name=httpd state=removed' ansible web -m yum -a 'name=httpd state=latest' ansible web -m yum -a 'name=* state=latest exclude= kernel*' |
Module 9: Service module
Service module in ansible is used to manage the state of your service means you can start, stop, restart, reload, enable, disable your service according to your requirement.
1 2 | ansible web -m service -a 'name=postfix state=started enabled=true' ansible web -m service -a 'name=postfix state=reload enabled=true' |
For more visit ansible official docs.
1 | ansible-doc service |
Module 10: Lineinfile module
Lineinfile module is mainly used to edit the content of file means by this module we can comment and uncomment specific line, we can replace, delete any line based on regexp. We can add or delete line at our desire location into the file. For better understanding let’s have a look of syntax and its example.
1 | ansible web -m lineinfile -a 'line="linuxdady ALL=(ALL) NOPASSWD: ALL" dest=/etc/sudoers' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | linuxdady.com | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "backup": "", "changed": true, "msg": "line added" } 172.17.0.2 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "backup": "", "changed": true, "msg": "line added" } |
In above command we have checked this is added a user linuxdady with sudo permission into /etc/sudoers file. Suppose now we want to delete this user entry form /etc/sudoers file then.
1 | ansible web -m lineinfile -a 'line="linuxdady ALL=(ALL) NOPASSWD: ALL" dest=/etc/sudoers state=absent' |
Suppose we want to add content starting of the file then use below command.
1 | ansible web -m lineinfile -a 'line="linuxdady ALL=(ALL) NOPASSWD: ALL" dest=/etc/sudoers insertafter=BOF' |
Now suppose you want to delete line with the help of regular expiration. Then.
1 | ansible web -m lineinfile -a 'regexp=^linuxdady state=absent dest=/etc/sudoers' |
Module 11: Replace module
Replace modules in ansible is mainly used to change character or string into the file. Like suppose I have a file demo.sh. From this file I want to change character ‘ansible’ to ‘puppet’. Let’s do it.
1 | ansible web -m replace -a 'regexp=ansible replace=puppet dest=/opt/demo.txt' |
Module 12: URI module
If you want to understand URI modules in ansible then simple you can compare it with curl command. This can perform all task of curl command. For windows use win_uri module. Syntax and example of uri module.
1 | ansible web -m uri -a 'url=https://linuxdady.com' |
We can also pass username and password in this module if required. For more visit ansible official docs.
1 | ansible-doc uri |
Module 13: GET_URL module
You can compare this module with wget command in Linux means we can perform all operation of wget command with this module like downloading from the internet, passing credential etc. Let’s understand more with example suppose I want to download a package to all web group machine.
1 | ansible web -m get_url -a 'url=https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm dest=/tmp force=yes' |
The major disadvantage of get_url module is it will not download the file again if file already exist into directory even content differ. If we want to download, we have to use force=yes.
Module 14: Stat module
The state module is mainly used to find the details of file or directory like creation detail, modification detail, owner, permission, group, checksum, inode number etc. This module is an alternate of stat command in Linux. For windows we can use win_stat module.
1 | ansible web -m stat -a 'path=/tmp/test.sh' |
If your test.sh file will exist in /tmp folder then it will show the complete details of test.sh file otherwise will show the exist status = false. This module have lot of use case for more visit at its official docs.
1 | ansible-doc stat |
Module 15: Setup modules in ansible
Setup module is mainly used for fact gathering in ansible means we can get system information by this module hostname, IP address, filesystems, OS releases, Users, Network parameters, CPU, memory, disk space and many more. We can store fact value in a variable and we can call it into playbook if required
1 | ansible 172.17.0.2 -m setup |
This command will display the full details of 172.17.0.2 host. We can filter out on the behalf of facts.
1 | ansible web -m setup -a 'filter=ansible_distribution' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 172.17.0.2 | SUCCESS => { "ansible_facts": { "ansible_distribution": "CentOS", "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": false } linuxdady.com | SUCCESS => { "ansible_facts": { "ansible_distribution": "CentOS", "discovered_interpreter_python": "/usr/bin/python" }, "changed": false } |
Suppose we want to check IP address in web group then use below filter.
1 | ansible web -m setup -a 'filter=facter_ipaddress_eth0' |
1 2 3 4 5 6 7 8 9 10 11 12 13 | 172.17.0.2 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": false } linuxdady.com | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python", "facter_ipaddress_eth0": "172.31.86.202" }, "changed": false } |
Module 16: User module
User modules in ansible have very important role. Because with the help of this module we can create, delete, modify or we can add group, groups, home directory of user according to our requirement. Simple you can compare it with useradd command in Linux.
1 | ansible web -m user -a 'name=demo state=present group=root groups=wheel append=true' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | linuxdady.com | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "comment": "", "create_home": true, "group": 0, "groups": "wheel", "home": "/home/demo", "name": "demo", "shell": "/bin/bash", "state": "present", "system": false, "uid": 1001 } 172.17.0.2 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "comment": "", "create_home": true, "group": 0, "groups": "wheel", "home": "/home/demo", "name": "demo", "shell": "/bin/bash", "state": "present", "system": false, "uid": 1002 } |
Module 17: Group modules in ansible
Group module is used to manage the group in Linux based OS. For better understanding you can compare it with groupadd command in Linux mean we can add, delete, modify group according to our requirement.
1 | ansible web -m group -a 'name=linuxdady state=present gid=1010' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | linuxdady.com | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "gid": 1010, "name": "linuxdady", "state": "present", "system": false } 172.17.0.2 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": true, "gid": 1010, "name": "linuxdady", "state": "present", "system": false } |
Suppose we want to delete group from all web machine.
1 | ansible web -m group -a 'name=linuxdady state=absent gid=1010' |
Module 18: Archive
Archive modules in ansible use to compress our data in Linux based OS. For better understanding we can compare it with tar command. In below example we are going to archive /etc directory in bz2 comparison under temp directory.
1 | ansible web -m archive -a 'path=/etc dest=/tmp/etc.tar.bz2 format=bz2' |
Conclusion – Basic modules in ansible
In ansible there is tons of modules to read all module is not intelligence. Just be aware with basic modules of ansible. If we will become hands on over basic module then easily, we can use rest of module. So, In this tutorial I have tried to explain basic modules in ansible. If anyone have query write me in comment box. I will try my best to resolve.
Interview question related to modules in ansible
- How to copy test.sh file form manage node /opt directory to manage node /mnt directory?
1 | ansible web -m copy -a 'src=/opt/test.sh remote_src=yes dest=mnt' |
- Suppose I have a file of 5GB over the internet and I want to copy it on all manage node . Then what will be more preferable copy module or wget module and why?
Ans. Copy module because wget module will download package on all machine that will consume our bandwidth and download speed will be slow then copy which consume time.
- Which one module is to get fact in ansible?
Ans. Setup modules
4. Explain the difference between setup and stat module?
https://linuxdady.com/basic-modules-in-ansible/
https://linuxdady.com/ansible-playbook-example/
https://linuxdady.com/multitask-playbook-in-ansible/
https://linuxdady.com/ansible-ad-hoc-commands-with-example/
////////////////////////////////////////////////////////
Ansible ad hoc commands with example
In this tutorial we are going to learn ansible ad hoc commands and how to push configuration by ad hoc method. Ad hoc method will be helpful for you when you are not well aware about ansible modules. You can execute commands on all required managed host parallelly by this method.
Ansible ad hoc commands
To perform lab of ansible ad hoc commands we are using four managed node and we will create a static inventory file. On the behalf of this static inventory file we will perform our lab.
Control Node IP :– linuxdady.com (172.31.86.202)
Manage Node IP :– 172.17.0.2, 172.17.0.3, 172.17.0.4
Now we are going to create a simple inventory file to perform lab. Kindly have a look of below inventory file and change it accordingly.
1 2 3 4 5 6 7 8 9 10 11 | linuxdady.com [web] linuxdady.com 172.17.0.2 [dev] 172.17.0.2 172.17.0.3 172.17.0.4 [db:children] web dev |
[Click & Read:– How to install ansible step by step very easy]
[Click & Read:– Static and dynamic inventory file explanation for beginners]
In above static inventory file, we have created web and dev group as well a db group which is group over the group. Still our manage node are not password less. So, first we are going to create username and password for manage node. After doing practice with password then we will work with key based authentication. I have created user “centos” and set password “redhat”. You can change it accordingly. Now first have a look of ad hoc syntax.
1 | ansible -m <module> <argument> ‘key=value’ <options> |
Example 1 Check all hosts uptime in [web] group
1 | ansible -m command -a 'uptime' "web" -k |
-k :- Option is required to prompt password for manage node.
In above example we have checked uptime of manage node from centos user. Suppose you are login from centos, and you want to check uptime from another user at manage node. Mind it user should be exist of manage node. Then it will work otherwise it will show you the error. So, I am trying with root user. Use any command from below according to your comfort.
1 2 3 | ansible -m command -a 'uptime' "web" -k -u root ansible all -m command -a 'uptime' -u root -k ansible dev -m command -a 'uptime' -u root -k |
-u:- option will use to pass username.
-k:- Option will use to prompt password for root user.
How to disable host level verification from ansible level
In above example you will find every time while making connection with manage node asking for yes or no option. To avoid this, disable host level verification from ansible level. So, open you ansible.cfg file and uncomment the below entry. After that ansible will not prompt yes or no option while making connection with managed host.
1 | vim .ansible.cfg |
1 | # host_key_checking = False |
Example 2 Use sudo to perform any task
Suppose you are normal user and you want to perform any root level task. Then you need root level permission otherwise you will got permission error. So, use -b option.
1 | ansible web -m command -a 'mkdir /ansible' -k -b |
1 2 3 | SSH password: linuxdady.com | CHANGED | rc=0 >> 172.17.0.2 | CHANGED | rc=0 >> |
-b :– This option help to become sudo
Make managed node password less
To type password for every machine manually is not a best practice. Because for 2-3 machine this is ok but suppose you have hundred servers, or you want to automate any task then this become problematic task. So, best practice is we should make all manage node password less. For this purpose, we have to create a ssh key and then we have to copy it on all manage node.
1 | ssh-keygen |
Our key has been created by above command. Now copy public key to all managed node by using below command. Change IP address and user name accordingly.
1 2 3 | ssh-copy-id -i centos@172.17.0.3 ssh-copy-id -i centos@172.17.0.4 ssh-copy-id -i centos@172.17.0.2 |
Our key has been successfully added. Now check once it becomes password less or not from your end. Execute below command to check its working without password or not.
1 | ansible web -m command -a 'uptime' |
1 2 3 4 5 6 | [centos@linuxdady ~]$ ansible web -m command -a 'uptime' linuxdady.com | CHANGED | rc=0 >> 05:11:42 up 1:57, 6 users, load average: 0.40, 0.16, 0.09 172.17.0.2 | CHANGED | rc=0 >> 10:11:42 up 1:57, 1 user, load average: 0.40, 0.16, 0.09 [centos@linuxdady ~]$ |
We are properly able to check uptime from centos user. Let’s check user id of centos user once.
1 | ansible web -m command -a 'id' |
How to set -k and -u option as a default
Suppose you are not interest to type -k and -u option while making connection with manage node then we can also make all these option as a default. Open your ansible.cfg file and go to line 15 and make below entry.
1 2 3 | vim .ansible.cfg remote_user = centos |
1 2 3 4 5 6 7 8 | [defaults] # some basic default values... inventory = /home/centos/Prod-Inventory remote_user = centos #library = /usr/share/my_modules/ #module_utils = /usr/share/my_module_utils/ #remote_tmp = ~/.ansible/tmp #local_tmp = ~/.ansible/tmp |
Similarly, if you want to perform all action with sudo then again open you file and make below entry under line 340 and uncomment the below line.
1 2 3 4 5 6 7 8 | vim .ansible.cfg [privilege_escalation] become=True become_method=sudo become_user=root #become_ask_pass=False [paramiko_connection] |
Now check our changes are working or not. Note it down we are running command form centos user and we will see who is performing action on manage node. Let’s check the id.
1 | ansible web -m command -a 'id' |
As we have check it is showing id of root user or root user means our changing has been reflected and sudo parameter is working file.
Conclusion
In this tutorial we have taken basic overview of ansible ad hoc commands and how to perform action on group. Ad hoc method is very useful when you are lacking in modules and playbook part. You can directly push your changes with the help of ad hoc method. So, write me in comment box if anyone have query. I will try my best to resolve that query.
Interview on ansible ad hoc commands
- Suppose python is not installed on client machine which one module will you prefer in raw or command ?
Ans. raw module will be preferable because command module is written in core python. ( if I am wrong you can write me in comment box)
- Why ad hoc method?
- What is configuration file of ansible?
- What does -k option in ad hoc ?
- It is possible to make connection without key with manage host.
Ans. Yes, we can establish connection with the help of password. But to type password for every machine for every time become hectic.
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
Comments
Post a Comment