Ansible PlayBook - Task

1 - 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).

3 - Format

module: options
# or
action: module options

ie example

    src: templates/foo.j2
    dest: /etc/foo.conf
# or
action: template src=templates/foo.j2 dest=/etc/foo.conf

4 - Management

4.1 - Omit parameters

- name: touch files with an optional mode
  file: dest={{ item.path }} state=touch mode={{ item.mode | default(omit) }}
    - path: /tmp/foo
    - path: /tmp/bar
    - path: /tmp/baz
      mode: "0444"

4.2 - Status

4.3 - Import vs Include

Statement Show the child if skipped Apply the properties
import Yes directly
include No from the parent

4.3.1 - import_tasks

- name: Test TCP connectivity
  become: true
  become_user: foo
  import_tasks: 'tasks/tcp_connectivity_infa_sql_server.yml'

where the relative search path is

  • for a play, playdir/{files|vars|templates}/, playdir/.
  • for a role, rolename/{files|vars|templates}/, rolename/tasks/.

4.3.2 - Include_Tasks

An Include_Tasks should always be wrapped around a block because it inherits the sudo property of its parent

- name: Service Pack Installation
  become: yes
  become_user: '{{ bdm_install_user }}'
    - name: Install Service Pack 1022SP1
      include_tasks: user_install_1022sp1.yml

4.4 - Execution

- command: /opt/application/
  run_once: true


  • run-once - only run a task one time for a batch of hosts
  • delegate_to specify an individual host to execute on

5 - Example

- hosts: webservers 
  remote_user: root 
    - 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
        src: template.j2
        dest: /etc/httpd/conf.d/{{ myVar }}
        - restart memcached
        - restart apache


Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap