Skip to content

Cheat Sheet Ansible

Ansible è uno strumento emergente per l’automazione delle operazioni IT sviluppato in Python. Combina i vantaggi di molti strumenti di gestione (puppet, cfengine, chef, func, fabric) e implementa funzioni come la configurazione di sistemi in batch, la distribuzione di programmi in batch e l’esecuzione di comandi in batch.

Iniziare

Host e Gruppi (Hosts and Groups)

$ sudo mkdir /etc/ansible
$ sudo vim /etc/ansible/hosts

[example]
192.0.2.101
192.0.2.102

Eseguire un Playbook

$ ansible-playbook playbook.yml

Task

- hosts: all
  user: root
  sudo: no
  vars:
    aaa: bbb
  tasks:
    - ...
  handlers:
    - ...

Inclusioni (Includes)

tasks:
  - include: db.yml
handlers:
  - include: db.yml user=timmy

Trigger

handlers:
  - name: start apache2
    action: service name=apache2 state=started

tasks:
  - name: install apache
    action: apt pkg=apache2 state=latest
    notify:
      - start apache2

Variabili

- host: lol
  vars_files:
    - vars.yml
  vars:
    project_root: /etc/xyz
  tasks:
    - name: Create the SSH directory.
      file: state=directory path=${project_root}/home/.ssh/
      only_if: "$vm == 0"

Role (Ruoli)

- host: xxx
  roles:
    - db
    - { role:ruby, sudo_user:$user }
    - web

# Utilizzi :
# roles/db/tasks/*.yml
# roles/db/handlers/*.yml

Gestione degli errori

- name: my task
  command: ...
  register: result
  failed_when: "'FAILED' in result.stderr"

  ignore_errors: yes

  changed_when: "result.rc != 2"

Variabili d’ambiente

vars:
  local_home: "{{ lookup('env','HOME') }}"