Skip to content

Exemplos de Playbooks

Aqui estão alguns exemplos de playbooks Ansible para ajudar no dia a dia.

Linux

Exibe o uptime do sistema

---
- name: Show Uptime
  hosts: all
  gather_facts: true
  tasks:
    - name: Run uptime command
      command: uptime
      register: uptime_output

    - name: Display uptime
      debug:
        var: uptime_output.stdout

Instalação de pacote Debian

- hosts: all
  tasks:
    - name: Instalar pacote
      apt:
        name: nginx
        state: present

Instalação de updates de segurança RHEL

---
- name: Verificar servidores e necessidade de reinicialização
  hosts: all
  gather_facts: no
  tasks:
    - name: Atualizar pacotes de segurança com dnf
      dnf:
        name: "*"
        security: yes
        state: latest
      register: security_update_result
      ignore_errors: no

    - name: Verificar se há pacotes que precisam reiniciar
      command: yum needs-restarting -r
      register: needs_restarting
      ignore_errors: yes

    - name: Definir necessidade de reinicialização
      set_fact:
        restart_needed: "{{ 'sim' if ('Reinicialização é necessária' in needs_restarting.stdout or 'Reboot is required' in needs_restarting.stdout) else 'não' }}"

    - name: Reiniciar o servidor se necessário
      when: restart_needed == 'sim'
      reboot:
        reboot_timeout: 300
      ignore_errors: no

    - name: Verificar se o servidor voltou após reinício
      wait_for_connection:
        timeout: 300
      when: restart_needed == 'sim'

Swappiness define quando o SO irá começar a usar swap, no exemplo é usado 10, ou seja, o SO irá utilizar swap somente com 90% de uso, obs.: Ajuste de acordo com o servidor

---
- name: Modify swappiness
  hosts: all
  become: yes
  tasks:
    - name: Garantir que vm.swappiness=10 está no arquivo sysctl.conf
      ansible.builtin.lineinfile:
        path: /etc/sysctl.conf
        regexp: '^vm.swappiness='
        line: 'vm.swappiness=10'

    - name: Aplicar as configurações de sysctl
      ansible.builtin.command: sysctl -p
      register: sysctl_apply

Melhoria do tempo de inicialização

---
- name: Set GRUB timeout
  hosts: all
  become: yes
  become_user: root
  tasks:
    - name: Set GRUB timeout to 1 second
      lineinfile:
        path: /etc/default/grub
        regexp: '^GRUB_TIMEOUT=5'
        line: 'GRUB_TIMEOUT=1'
      register: grub_changed_result

    - name: Update GRUB configuration
      command: grub2-mkconfig -o /boot/grub2/grub.cfg
      when: grub_changed_result.changed
      notify: Reboot

  handlers:
    - name: Reboot
      ansible.builtin.reboot: