Ansible tasks form the basic building block of running Ansible commands. Ansible tasks are structured in the following format:
$ ansible <options> <inventory>
Ansible modules are reusable code for a particular function, such as running a shell command or creating and managing users. You can use Ansible modules with Ansible tasks to manage configuration within managed nodes. For example, the following command will run the uname command on each managed server:
$ ansible -m shell -a “uname” all
db | CHANGED | rc=0 >>
Linux
web | CHANGED | rc=0 >>
Linux
So, we get a reply from the db server and the web server, each providing a return code, 0, and an output, Linux. If you look at the command, you will see that we have provided the following flags:
- -m: The name of the module (shell module here)
- -a: The parameters to the module (uname in this case)
The command finally ends with where we want to run this task. Since we’ve specified all, it runs the task on all servers. We can run this on a single server, a set of servers, a role, or multiple roles, or use a wildcard to select the combination we want.
The tasks have three possible statuses—SUCCESS, CHANGED, and FAILURE. The SUCCESS status denotes that the task was successful, and Ansible took no action. The CHANGED status denotes that Ansible had to change the existing configuration to apply the expected configuration, and FAILURE denotes an error while executing the task.
Ansible modules are reusable scripts that we can use to define configuration within servers. Each module targets a particular aspect of CM. Modules are used in both Ansible tasks and playbooks. There are many modules available for consumption, and they are available at https://docs. ansible.com/ansible/latest/collections/index_module.html. You can pick and choose modules according to your requirements and use cases.
Tip
As Ansible is idempotent, always use modules specific to your task and avoid using command and shell modules. For example, use the apt module to install a package instead of the command module to run apt install <package> -y. If your playbook starts to look like code, then you’re doing something fundamentally wrong.
Tasks do not make sense when we have a series of steps to follow while setting up a server. Therefore, Ansible provides playbooks for this activity. Let’s have a look at this in the next section.
Leave a Reply