Ansible Tasks: Complete Guide
Tasks are the building blocks of Ansible automation. They define specific actions that Ansible should perform on managed nodes, such as installing software, modifying files, or starting services. Tasks are organized into playbooks or roles, enabling automation of complex workflows.
This guide explores Ansible tasks in detail, from the basics to advanced features, providing everything you need to master them.
1. What Are Tasks in Ansible?
Ansible tasks are individual units of work that execute a specific action using an Ansible module. Tasks are defined in YAML syntax within playbooks, roles, or include files.
Key Features of Tasks
- Declarative: Tasks describe the desired state rather than how to achieve it.
- Idempotent: Tasks ensure that the desired state is maintained without making unnecessary changes.
- Flexible: Tasks can use variables, conditions, loops, and more for dynamic behavior.
2. Anatomy of a Task
A typical task has the following structure:
- name: <Description of the task>
module_name:
option1: value1
option2: value2
Components
-
name
(Optional): A human-readable description of the task. -
module_name
: The Ansible module to execute. - Module Options: Parameters passed to the module.
Example:
- name: Install Nginx
apt:
name: nginx
state: present
3. Common Options in Tasks
3.1 name
The name
field provides a description of the task for better readability in playbook execution output.
Example:
- name: Ensure Nginx is installed
apt:
name: nginx
state: present
3.2 register
The register
keyword stores the output of a task in a variable for later use.
Example:
- name: Check Nginx status
command: systemctl status nginx
register: nginx_status
3.3 when
The when
keyword allows conditional execution of tasks based on variables or facts.
Example:
- name: Install Apache on Debian systems
apt:
name: apache2
state: present
when: ansible_os_family == "Debian"
3.4 become
The become
keyword allows privilege escalation for tasks that require root or higher permissions.
Example:
- name: Update system packages
apt:
upgrade: dist
become: yes
3.5 with_items
Loops are executed using with_items
or newer loop
syntax.
Example:
- name: Install multiple packages
apt:
name: "{{ item }}"
state: present
with_items:
- nginx
- curl
- git
4. Running Tasks in Playbooks
Tasks are defined under the tasks
section in a playbook.
Example Playbook:
---
- name: Configure webserver
hosts: webservers
become: yes
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Ensure Nginx is started
service:
name: nginx
state: started
Run the playbook:
ansible-playbook webserver.yml
5. Advanced Task Features
5.1 Tags
Tags allow selective execution of tasks. Tasks are marked with tags and executed using the --tags
option.
Example:
- name: Install Nginx
apt:
name: nginx
state: present
tags:
- install
- name: Start Nginx
service:
name: nginx
state: started
tags:
- configure
Run specific tags:
ansible-playbook playbook.yml --tags install
5.2 Handlers
Handlers are special tasks triggered by notifications when other tasks make changes.
Example:
- name: Copy Nginx config
copy:
src: nginx.conf
dest: /etc/nginx/nginx.conf
notify:
- Restart Nginx
handlers:
- name: Restart Nginx
service:
name: nginx
state: restarted
5.3 Loops
Loops repeat tasks over a list of items.
Using with_items
:
- name: Create multiple users
user:
name: "{{ item }}"
state: present
with_items:
- user1
- user2
- user3
Using loop
:
- name: Install packages
apt:
name: "{{ item }}"
state: present
loop:
- nginx
- git
- curl
5.4 Conditional Tasks
The when
keyword allows tasks to run only if a condition is true.
Example:
- name: Install Apache on Debian
apt:
name: apache2
state: present
when: ansible_os_family == "Debian"
5.5 Delegation
Tasks can be delegated to a different host using delegate_to
.
Example:
- name: Run a command on a specific host
command: uptime
delegate_to: management-server
5.6 Blocks
Blocks group tasks together for common error handling or conditional execution.
Example:
- block:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Configure Nginx
copy:
src: nginx.conf
dest: /etc/nginx/nginx.conf
rescue:
- name: Rollback
command: rm -rf /etc/nginx
6. Using Variables in Tasks
Tasks can use variables defined in the inventory, playbook, or external files.
Example:
- name: Install a package
apt:
name: "{{ package_name }}"
state: present
In the inventory:
[webservers]
host1 ansible_host=192.168.1.10 package_name=nginx
7. Debugging and Testing Tasks
7.1 Debug Module
The debug
module prints variables or messages for debugging.
Example:
- name: Print variable value
debug:
var: ansible_os_family
7.2 Dry Run
Use --check
to perform a dry run of the playbook.
Example:
ansible-playbook playbook.yml --check
8. Best Practices for Tasks
-
Use
name
for Clarity: Always include aname
for tasks to describe their purpose. - Leverage Modules: Use Ansible modules instead of raw commands for better idempotency.
- Avoid Hardcoding: Use variables and templates to make tasks dynamic.
- Use Handlers: Trigger handlers for service restarts or similar actions.
- Test Incrementally: Test individual tasks using tags or by limiting target hosts.
-
Use Conditionals Sparingly: Avoid excessive use of
when
to keep tasks simple and readable.
9. Example: Complete Playbook with Tasks
---
- name: Set up a web server
hosts: webservers
become: yes
vars:
nginx_port: 80
nginx_user: www-data
tasks:
- name: Update package cache
apt:
update_cache: yes
- name: Install Nginx
apt:
name: nginx
state: present
- name: Copy Nginx config
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify:
- Restart Nginx
- name: Open firewall port
ufw:
rule: allow
port: "{{ nginx_port }}"
proto: tcp
handlers:
- name: Restart Nginx
service:
name: nginx
state: restarted
10. Conclusion
Ansible tasks are at the core of automating system configurations. By mastering tasks, you can effectively:
- Perform specific actions on managed nodes.
- Use variables, loops, and conditions for dynamic behavior.
- Organize tasks efficiently in playbooks and roles.
Key Takeaways
- Tasks are idempotent and declarative.
- Use modules for robust automation.
- Leverage features like loops, handlers, and conditionals to enhance functionality.
Understanding tasks is essential to becoming proficient in Ansible, as they form the foundation of all automation workflows.
Top comments (0)