Ansible

From Leo's Notes
Revision as of 03:45, 5 September 2020 by Leo (talk | contribs) (→Playbooks)
This page was last edited on 5 September 2020, at 03:45.

Inventory

Either static (.ini or .yaml) or dynamic. Located at /etc/ansible/hosts and each host may define specific parameters.

[webservers]
web1.example.com ansible_user=bob
web2.example.com  ansible_host=192.168.81.142 ansible_port=3333

[apservers]
ap1.example.com
ap2.example.com

[dbservers]
db[01:10].example.com

Can be grouped (webserers, apservers), or left ungrouped at the very top (for .ini files only). The 'all' group captures everything too. Groups can be nested. Use the ':' in group names for .ini files to represent hierarchy. Ranges can also be specified with brackets.

ansible -i /path/to/inventory all -m shell -a 'echo hello world' -f 5

Additional variables can be set as well. Variables can either be set to each host, or to a group. Since groups can be nested, the most immediate group variable takes presidence.

Playbooks

A series of tasks to configure something can be bundled into a playbook. Playbooks can be applied with the ansible-playbook command.

When applying a playbook, the recap will output the following:

  • ok - task ran successfully with no changes being made
  • changed - task ran successfully with changes being made
  • failed - task failed to run
  • unreachable - host was unreachable
  • skipped - task was skipped
  • ignored - task was ignored
  • rescued - ?

playbooks look like this:

---
- name: Handler demo 1
  hosts: frt01.example.com
  gather_facts: no
  become: yes

  tasks:
    - name: Update Apache configuration
      template:
        src: template.j2
        dest: /etc/httpd/httpd.conf
      notify: Restart Apache

    - name: restart all services
      command: echo "this task will restart all services"
      notify: "restart all services"

  handlers:
    - name: Restart Apache
      service:
        name: httpd
        state: restarted
      listen: "restart all services"

Handlers can be called with notify. Handlers can also listen for a specific event with the listen directive.

Loops can be done by specifying a list of items:

---
- name: Install Apache
  hosts: frt01.example.com
  gather_facts: no
  become: yes

  tasks:
    - name: Install Apache package
      yum:
        name: httpd
        state: latest
    - name: Open firewall for Apache
      firewalld:
        service: "[[:Template:Item]]"
        permanent: yes
        state: enabled
        immediate: yes
      loop:
        - "http"
        - "https"
    - name: Restart and enable the service
      service:
        name: httpd
        state: restarted
        enabled: yes