Ansible Modules

  • Share this blog:

Ansible uses "modules" to accomplish most of its Tasks. Modules can do things like install software, copy files, use templates, and much more.

Modules are the way to use Ansible, as they can use available context ("Facts") in order to determine what actions, if any need to be done to accomplish a task.

If we didn't have modules, we'd be left running arbitrary shell commands like this:

ansible all -s -m shell -a 'apt-get install nginx'

Here, the sudo apt-get install nginx the command will be run using the "shell" module. The -a flag is used to pass any arguments to the module. I use -s to run this command using sudo.

However, this isn't particularly powerful. While it's handy to be able to run these commands on all of our servers at once, we still only accomplish what any bash script might do.

If we used a more appropriate module instead, we can run commands with an assurance of the result. Ansible modules ensure indempotence - we can run the same Tasks over and over without affecting the final result.

For installing software on Debian/Ubuntu servers, the "apt" module will run the same command but ensure idempotence.

ansible all -s -m apt -a 'pkg=nginx state=installed update_cache=true' | success >> { 
"changed": false 

This will use the apt module to update the repository cache and install Nginx (if not installed).

Interested in mastering Ansible Training?
Check out this blog post to learn more Ansible Tutorials.

The result of running the Task was "changed": false. This shows that there were no changes; I had already installed Nginx. I can run this command over and over without worrying about it affecting the desired result.

Going over the command:

all - Run on all defined hosts from the inventory file

-s - Run using sudo

-m apt - Use the apt module

-a 'pkg=nginx state=installed update_cache=true'

Provide the arguments for the apt module, including the package name, our desired end state and whether to update the package repository cache or not

We can run all of our needed Tasks (via modules) in this ad-hoc way, but let's make this more managable. We'll move this Task into a Playbook, which can run and coordinate multiple Tasks.

About Author
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated

Get stories of change makers and innovators from the startup ecosystem in your inbox