Ansible Task Snippets

Package Management

- name: update apt cache
  apt: update_cache_yes cache_valid_time=3600
- name: install common tools
  package:
    pkg:
      - git
      - htop

File Management

Copy a file with given owner and permissions

- name: copy site config
  copy:
    src: authorized_keys
    dest: /root/.ssh/authorized_keys
    owner: root
    mode: 0600

Copy a host-specific file if it exists, the default otherwise

- name: copy proper config
  copy: src={{ item }} dest=/etc/foo.conf
  with_first_found:
    - "foo.conf_{{ inventory_hostname}}"
    - foo.conf_default

Copy and unpack a compressed file to a given directory

- name: copy and extract archive
  unarchive: src=archive.tar.gz dest=/tmp

Create a directory

- name: create ~root/.ssh directory
  file: path=/root/.ssh state=directory

Create a symlink

- name: enable apache site
  file:
    src: /etc/apache2/sites-available/site.conf
    dest: /etc/apache2/sites-enabled/site.conf
    state: link

Delete a file

- name: disable apache2 default config
  file: path=/etc/apache2/sites-enabled/default state=absent

Use stat for instance to check the existence of a file

- name: check if somefile exists
  stat: path=/path/to/somefile
  register: somefile
- name: run boostrap script (only if somefile does not exist)
  script: bootstrap.sh
  when: somefile.stat.exists == false

Handlers

Handlers can be notified to restart services or trigger other actions.

Example handlers/services.yml to restart ssh service:

- name: restart ssh
  service: name=ssh state=restarted

Include handler in site.yml:

- hosts: all
  roles:
    - role: remote-login
  handlers:
    - include: handlers/services.yml
      static: yes

Use notify to trigger a service restart in a playbook:

- name: sshd_config file
  copy: src=sshd_config dest=/etc/ssh/sshd_config
  notify: restart ssh

You may want to set handler_includes_static = yes in ansible.cfg to automatically include all handlers as static.

A meta module can be used to trigger the processing of all handlers at a specific moment:

- name: trigger all pending handler actions
  meta: flush_handlers

Tags

You may add tags to selected items or roles

roles:
  - { role: webserver, tags: 'webserver' }
  - { role: mysqlserver, tags: [ 'dbserver', 'slowtask' ] }

and then only run tasks with a given tag.

ansible-playbook site.yml --tags "webserver,dbserver"
ansible-playbook site.yml --skip-tags "slowtask"

Prompt for variable values to be entered

vars_prompt:
  - name: user_password
    prompt: Please enter the your password
    private: yes                              # don't show what is being typed

Wait for a condition to be met

Use wait_for to not continue until a port accepts a connection

- name: wait for webserver to start
  wait_for:
    port: 80
    state: started

or use until loops

- name: wait for web app
  shell: curl --head --silent http://localhost:80
  register: result
  until: result.stdout.find('200 OK') != -1
  retries: 10
  delay: 3

Register

Use register to store output and debug to print it

- name: capture output of whoami
  command: whoami
  register: whoami_cmd
- debug:
    msg: "Logged in as user {{ whoami_cmd.stdout }}"
    verbosity: 2  # only show when run with -vv

Use when for conditionals

- shell: cat /etc/motd
  register: motd_contents
- shell: echo "motd contains the word hi"
  when: motd_contents.stdout.find('hi') != -1

When conditionals

when: "not 'production' in group_names"

when: inventory_hostname == 'host1'

when: inventory_hostname in ['host1', 'host2']

when: ansible_distribution_release == 'stretch'

Block

block:
  - name: failing task
    command: /bin/false
  - name: never executed because the of the previous error
    debug: msg="never"
rescue:
  - name: catch task to run if there was an error
    debug: msg="catch task"
  - name: info about the failed task
    debug: var=ansible_failed_task
  - name: info about failed result via automatic register
    debug: var=ansible_failed_result
always:
  - name: task that is always run, independently of any errors
    debug: msg="always"

Become to run shell command with sudo

- name: run shell command as johndoe
  shell: /some/command
  become: true
  become_user: johndoe
  args:
    creates: /some/generated/file

Check mode behavior

Do not run a given task in check mode:

when: not ansible_check_mode

Force a task to always run in normal mode (even in check mode):

check_mode: no

Force a task to always run in check mode (even in normal mode):

check_mode: yes

Ignore errors

- name: ignore failing task
  command: bin/false
  ignore_errors: True

This can also be set for a whole playbook to continue executing tasks after the first failure:

- hosts: example.com
  ignore_errors: True
  roles:
    - some_role

Run apt command only when online

- name: test internet connectivity
  shell: ping -q -c 1 -W 1 example.com > /dev/null 2>&1
  register: ping_cmd
  # Mark the task as changed instead of failed
  changed_when: ping_cmd.rc != 0
  failed_when: False

- name: update apt cache
  package: update_cache=yes cache_valid_time=3600
  when: ping_cmd.rc == 0

Yaml multiline values

Use | to preserve newlines:

some_key: |
  Line1
  Line2

Use > to generate a single line with all newlines stripped

some_key: >
  Word1
  Word2