Goals
- To have a Knowledge of Ansible
- To Understand the purpose of Ansible Modules
- To Differentiate between Shell and Command Modules
Introduction
Ansible is a software configuration and automation tool. It is an open-source IT configuration and automation tool developed by RedHat it is free to use. There is a paid version, called Ansible Tower, which is used when dealing with a large number of servers.
Alternatives to Ansible include Rudder, Puppet, SaltStack, Chef, and GitLab CI.
An Ansible playbook is what ansible uses to carry out its function. An Ansible playbook contains the tasks
ansible will run. Each task is called a play and a playbook contains two or more plays.
Ansible playbooks are written in YAML
format.
Image 1.1 Example of an Ansible Playbook
Ansible Modules
Ansible Modules are individual units of code that can run on their own. They represent a single command. Ansible has many modules, there is an ansible module for almost every task that needs to be run.
Alternatively, Ansible modules can be created as Ansible is an open-source project and actively accepts contributions.
Examples of ansible modules include: apt
, yum
, file
, git
, service
, copy
, and command
. More information can be found about frequently used ansible modules here.
These modules, are what is placed before running a command on the command line, or a condition that needs to be achieved before a command is run. Example:
- name: Create ChRIS directory
file:
path: /home/mfon/chris
state: directory
- This block of code is named
Create ChRIS directory
- It uses the module called
file
- The path the file is being created at, is
/home/mfon/chris
- The type of file being created,
state
, is adirectory
The command above tells Ansible, to create a directory in the path home/mfon/chris
.
Shell and Command Module
It is easy to use the shell
module in place of the command
module although they seem similar, they are fundamentally different. They carry out the same function of running a command in an ansible playbook however, the context in which they are being run leads to their difference.
The command
module executes commands like it would in the command line.
An example of this is:
- name: Move composer
command: mv composer.phar /usr/local/bin/composer
This block of code moves composer.phar
to the path /usr/local/bin/composer
The shell
module executes commands however in the context of Unix based OS like bash
, zsh
sh
. Using the shell
module we can run commands with more complexities like &&
, |
, >>
.
An example of this is:
- name: Hello World
shell: echo "Hello World!" > hello.txt
This block of code adds the line echo “Hello World!”
to the hello.txt
file.
Hence running a command as a shell
module is compared to running it as a script, bash script, or shell script.
Conclusion
As a general rule, it is advised not to use the command
or shell
module except it is the only alternative.
More specific modules should be used in your ansible playbooks to execute tasks.