# Ansible

### Instalação (Linux)

**Debian/Ubuntu:**
```bash
sudo apt update
sudo apt install ansible -y
```

**Verificar:**
```bash
ansible --version
```

### Conceitos Básicos

**Inventário**: Lista de hosts
**Playbook**: Arquivo YAML com tarefas
**Tasks**: Ações a executar
**Modules**: Comandos pré-prontos (apt, copy, shell)
**Handlers**: Tarefas executadas sob demanda

**Arquitetura**: Agentless (usa SSH, sem agente nos hosts)

### Inventário

Arquivo `hosts`:

```ini
[rancher-cluster]
rancher-node1
rancher-node2
rancher-node3

[prod-cluster]
prod-node1
prod-node2
prod-node3
prod-node4
prod-node5
prod-node6
```

**Referência**: `/hosts`

### Playbook Básico

```yaml
- name: Configurar servidor
  hosts: rancher-cluster
  become: yes  # Executar como root

  tasks:
    - name: Instalar pacote
      apt:
        name: nginx
        state: present
```

**Estrutura:**
- `name`: Descrição
- `hosts`: Grupo do inventário
- `become`: Usar sudo
- `tasks`: Lista de tarefas

### Modules Principais

**apt**: Instalar pacotes (Debian/Ubuntu)
```yaml
- name: Instalar Docker
  apt:
    name: docker-ce
    state: present
```

**copy**: Copiar arquivos
```yaml
- name: Copiar configuração
  copy:
    src: nginx.conf
    dest: /etc/nginx/nginx.conf
```

**shell**: Executar comandos
```yaml
- name: Executar script
  shell: /opt/meu-script.sh
```

**sysctl**: Configurar kernel
```yaml
- name: Habilitar IP forwarding
  sysctl:
    name: net.ipv4.ip_forward
    value: '1'
    state: present
```

### Variables

**Via linha de comando:**
```bash
ansible-playbook --extra-vars 'ansible_user=estevao' playbook.yml
```

**No playbook:**
```yaml
- name: Mostrar usuário
  debug:
    msg: "Usuário SSH: {{ ansible_user }}"
```

### Privilege Escalation (Become)

```yaml
- name: Tarefa que requer root
  hosts: all
  become: yes  # sudo

  tasks:
    - name: Instalar pacote (requer root)
      apt:
        name: docker-ce
```

**Executar:**
```bash
ansible-playbook --ask-become-pass playbook.yml
# Solicita senha do sudo
```

### Handlers

Executados apenas se uma task mudar algo:

```yaml
tasks:
  - name: Copiar regras iptables
    copy:
      src: rules.v4
      dest: /etc/iptables/rules.v4
    notify: Reload iptables  # Chama handler

handlers:
  - name: Reload iptables
    shell: iptables-restore < /etc/iptables/rules.v4
```

**Referência**: `fw-dicom/fw-dicom.yml`

### Conditional Execution

```yaml
tasks:
  - name: Formatar disco (apenas workers)
    filesystem:
      fstype: ext4
      dev: /dev/sdb
    when: inventory_hostname in groups['workers']
```

**Referência**: `prod-cluster/prod-cluster.yml`

### Exemplo Completo

Arquivo `playbook.yml`:

```yaml
- name: Instalar Docker
  hosts: rancher-cluster
  become: yes

  tasks:
    - name: Adicionar chave GPG do Docker
      apt_key:
        url: https://download.docker.com/linux/debian/gpg
        state: present

    - name: Adicionar repositório Docker
      apt_repository:
        repo: deb https://download.docker.com/linux/debian bookworm stable
        state: present

    - name: Instalar Docker
      apt:
        name: docker-ce
        state: present
        update_cache: yes

    - name: Adicionar usuário ao grupo docker
      user:
        name: "{{ ansible_user }}"
        groups: docker
        append: yes
```

**Executar:**
```bash
ansible-playbook --ask-become-pass --extra-vars 'ansible_user=estevao' -i hosts playbook.yml
```

**Referência**: `rancher-cluster/rancher-cluster.yml`

---