Working with Tasks
1. Defining Task Structure
| Field | Description | Required | Examples |
|---|---|---|---|
| name | Human-readable description of the task | Yes | "Create directory /opt/myapp" |
| action | Module to execute (e.g., copy, file) |
Yes | copy, file |
| args | Arguments passed to the module | No | src: /local/file.txt |
| when | Conditional expression to control task execution | No | when: ansible_os_family == "RedHat" |
| loop | Iterate over a list or data structure | No | loop: [ "item1", "item2" ] |
| notify | Handler to run after task completion | No | notify: restart_service |
| register | Store output of the task in a variable | No | register: result |
Example: Task with Loop and Condition
- name: Copy files to hosts
copy:
src: "{{ item }}"
dest: "/tmp/{{ item }}"
loop:
- file1.txt
- file2.txt
when: ansible_os_family == "Debian"
2. Using Module Arguments
| Argument | Description | Required | Default |
|---|---|---|---|
| name | The name of the task or module | No | None |
| when | Condition to evaluate before running the task | No | None |
| delegate_to | Run the task on a different host than the one specified in the play | No | None |
| register | Store the result of a task in a variable for later use | No | None |
| loop | Repeat a task multiple times with different values | No | None |
| loop_control | Control how loops behave (e.g., batch size, pause between iterations) | No | None |
Example: Using when to conditionally run a task
- name: Check if a file exists
stat:
path: /etc/important_file
register: file_check
- name: Create backup only if file exists
copy:
src: /etc/important_file
dest: /backup/important_file
when: file_check.stat.exists
Example: Using loop to iterate over a list
- name: Create directories
file:
path: /home/user/{{ item }}
state: directory
loop:
- dir1
- dir2
- dir3
Example: Using delegate_to to run a task on a different host
- name: Gather facts from a specific host
setup:
delegate_to: webserver01
3. Setting Task State
| State | Description | Usage |
|---|---|---|
| present | Ensures the resource exists. Creates it if missing. | |
| absent | Ensures the resource is removed. Deletes it if exists. | |
| latest | Ensures the resource is at the latest version. Installs or upgrades if needed. | |
| present | Ensures the file or directory exists with specified content. | |
| absent | Ensures the file or directory is removed. | |
4. Registering Task Results
| Property | Description | Example |
|---|---|---|
| register | Stores the result of a task in a variable for later use | register: result |
Example: Registering a command result
- name: Get system information
command: uname -a
register: sys_info
- name: Display the result
debug:
msg: "System info: {{ sys_info.stdout }}"
Example: Registering a file lookup result
- name: Read a file content
command: cat /etc/os-release
register: os_release
- name: Show OS details
debug:
msg: "OS ID: {{ os_release.stdout_lines[0] }}"
Note: The registered variable can be used in subsequent tasks or in templates.
Warning: Be cautious with registering large outputs as variables, as they may impact performance.
5. Adding Task Conditions
| Condition | Description | Example |
|---|---|---|
| when | Executes the task only if the condition evaluates to true | |
| when (with variables) | Uses variable values to determine task execution | |
| when (with complex expressions) | Supports complex Jinja2 expressions for conditional logic | |
Example: Using when with multiple conditions
- name: Install packages only on CentOS 7 or Ubuntu 20.04
yum:
name:
- httpd
- mod_ssl
state: present
when:
- ansible_os_family == "RedHat"
- ansible_distribution_version == "7"
Note: The
when clause supports all Jinja2 expressions and can be used with variables, facts, and registered results.6. Controlling Task Execution
| Control Structure | Description | Usage |
|---|---|---|
| when | Conditionally execute a task based on a boolean expression | when: ansible_facts.os_family == "RedHat" |
| loop | Execute a task multiple times with different variables | loop: [ "item1", "item2", "item3" ] |
| loop_with | Loop over a list of items with additional variables | loop_with: "{{ item }}" |
| until | Repeat a task until a condition is met | until: "result.stdout == 'success'" |
| retries | Number of times to retry a task before failing | retries: 3 |
| delay | Seconds to wait between retries | delay: 5 |
Example: Using when to conditionally execute a task
- name: Install package on RedHat systems
yum:
name: httpd
state: present
when: ansible_facts.os_family == "RedHat"
Example: Using loop to iterate over a list
- name: Create directories
file:
path: "/tmp/{{ item }}"
state: directory
loop:
- "dir1"
- "dir2"
- "dir3"
Example: Using until to retry a task
- name: Wait for service to be up
uri:
url: "http://localhost:8080"
until: "result.status == 200"
retries: 5
delay: 10
7. Ignoring Errors
| Option | Values | Notes |
|---|---|---|
| ignore_errors | true / false |
When set to true, the task will continue executing even if a previous task fails. |
Example: Using ignore_errors
- name: Run a command that might fail
command: /bin/false
ignore_errors: true
- name: Continue with next task despite previous failure
debug:
msg: "This will run even if the previous command failed"
8. Delegating Tasks
| Property | Description | Default |
|---|---|---|
| delegate_to | Specifies the host to run the task on instead of the current host | None |
| delegate_facts_to | Specifies the host to store facts on when delegating tasks | None |
Example: Delegating a task to a different host
- name: "Run a command on the control node"
command: whoami
delegate_to: "localhost"
Example: Delegating task and storing facts
- name: "Gather facts on a different host"
setup:
delegate_to: "web01"
delegate_facts_to: "localhost"
Note: The
delegate_to directive allows tasks to be executed on a different host than the one specified in the hosts directive. This is useful for tasks that need to run on a specific host or when managing infrastructure from a central control node.
9. Running Tasks Once
| Option | Values | Notes |
|---|---|---|
| run_once | true |
Ensures task runs only on the first host in the inventory |
| delegate_to | host1 |
Runs task on a specific host instead of the current host |
Example: Using run_once
- name: Create directory once
file:
path: /shared/config
state: directory
run_once: true
Example: Using delegate_to
- name: Configure database on master node
command: /usr/bin/configure-db.sh
delegate_to: db-master-01
10. Setting Task Environment
| Property | Description | Values |
|---|---|---|
| environment | Sets environment variables for the task | dict |
| vars | Sets variables for the task | dict |
Example: Setting Environment Variables
- name: Run a command with custom environment
command: echo $MY_VAR
environment:
MY_VAR: "custom_value"
PATH: "/usr/local/bin:/usr/bin:/bin"
Example: Using vars to Set Variables
- name: Use vars to set task variables
debug:
msg: "{{ my_var }}"
vars:
my_var: "Hello World"
11. Adding Task Tags
| Tag | Description | Usage |
|---|---|---|
| tags | List of tags to apply to a task | tags: [web, production] |
Example: Applying Tags to a Task
---
- name: Configure web server
hosts: webservers
tasks:
- name: Install Apache
apt:
name: apache2
state: present
tags:
- web
- http
Note: Tags can be used to selectively run or skip tasks during playbook execution.
12. Using Task Timeout
| Parameter | Description | Default | Notes |
|---|---|---|---|
| timeout | Maximum time (in seconds) to wait for a task to complete | 0 (no timeout) | Set to 0 for no timeout. Values > 0 enable timeout behavior |
Example: Setting a Task Timeout
---
- name: Run a long-running command with timeout
command: sleep 30
args:
chdir: /tmp
timeout: 10
Note: If a task exceeds its timeout, Ansible will fail the task and continue with the playbook execution.