Marcos Max

Wiki Max - TI

View on GitHub

Ansible — Automação de Configuração

Ferramenta de automação sem agente (agentless): conecta via SSH e aplica o estado desejado nos servidores. Idempotente — rodar várias vezes gera o mesmo resultado.

Instalação

sudo apt install -y ansible          # Debian/Ubuntu
ansible --version

Inventário

# inventory.ini
[web]
web01 ansible_host=192.168.1.10
web02 ansible_host=192.168.1.11

[db]
db01 ansible_host=192.168.1.20

[all:vars]
ansible_user=deploy
ansible_ssh_private_key_file=~/.ssh/id_rsa

Comandos ad-hoc

ansible all -i inventory.ini -m ping
ansible web -i inventory.ini -m apt -a "name=nginx state=present" --become
ansible all -i inventory.ini -a "uptime"

Playbook

# site.yml
- name: Configurar servidores web
  hosts: web
  become: true
  tasks:
    - name: Instalar Nginx
      apt:
        name: nginx
        state: present
        update_cache: true

    - name: Copiar configuração
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/sites-available/app
      notify: Reiniciar Nginx

    - name: Garantir serviço ativo
      service:
        name: nginx
        state: started
        enabled: true

  handlers:
    - name: Reiniciar Nginx
      service:
        name: nginx
        state: restarted

Rodar:

ansible-playbook -i inventory.ini site.yml
ansible-playbook -i inventory.ini site.yml --check     # dry-run
ansible-playbook -i inventory.ini site.yml --limit web01

Variáveis e cofre (secrets)

# Criptografar um arquivo de senhas
ansible-vault create group_vars/all/vault.yml
ansible-vault edit group_vars/all/vault.yml
ansible-playbook site.yml --ask-vault-pass

Estrutura recomendada (roles)

projeto/
├── inventory.ini
├── site.yml
├── group_vars/
└── roles/
    └── nginx/
        ├── tasks/main.yml
        ├── handlers/main.yml
        ├── templates/
        └── defaults/main.yml

Boas práticas

Veja também: Linux · Terraform