About
A task is a call to an ansible module with arguments located in a play list. Variables can be used in arguments to modules.
Tasks are executed top to bottom one at a time, against
all machines
matched by the host pattern before moving on to the next task.
Task should be idempotent in order to be able to re-run the playbook safely. (ie check whether the desired final state has already been achieved, and if that's the case exit without performing any actions).
Format
module: options
# or
action: module options
ie example
template:
src: templates/foo.j2
dest: /etc/foo.conf
# or
action: template src=templates/foo.j2 dest=/etc/foo.conf
Management
Omit parameters
- name: touch files with an optional mode
file: dest={{ item.path }} state=touch mode={{ item.mode | default(omit) }}
loop:
- path: /tmp/foo
- path: /tmp/bar
- path: /tmp/baz
mode: "0444"
Status
Import vs Include
See What are the differences between Import vs Include in Ansible?
Execution
- command: /opt/application/upgrade_db.py
run_once: true
delegate_to: web01.example.org
where:
- run-once - only run a task one time for a batch of hosts
- delegate_to specify an individual host to execute on
Example
---
- hosts: webservers
remote_user: root
tasks:
- name: First task - A command execution
command: /sbin/setenforce 1
remote_user: yourname
become: yes
become_method: sudo # or su
ignore_errors: True # Ignore the exit code
vars: # To define system variables
ansible_become: yes
ansible_become_method: runas
ansible_become_user: DOMAIN\user
ansible_become_pass: Password01
ansible_become_flags: logon_type=new_credentials logon_flags=netcredentials_only
- name: template configuration file with var {{ myVar }} that restart services only if the file change
template:
src: template.j2
dest: /etc/httpd/conf.d/{{ myVar }}
notify:
- restart memcached
- restart apache
where:
- name is the task name (default to 'action')
- remote_user define the running user
- become defines privileges escalation (ie Security - (Proxy|N-tier|User Impersonation) authentication). Connection variables in inventory
- ansible_become
- ansible_become_method
- ansible_become_user
- ansible_become_pass
- notify call handlers.
- when conditional. See Ansible - When
- vars can set built in variable