---
title: Introdução ao Ansible
tags: Apresentação
descricption: Apresentação inicial sobre o Ansible
---
# Introdução ao Ansible

https://www.ansible.com/
----
## Eduardo Klosowski

- Twitter: [@eduklosowski](https://twitter.com/eduklosowski)
- GitHub: [eduardoklosowski](https://github.com/eduardoklosowski)
- DEV: [eduardoklosowski](https://dev.to/eduardoklosowski)
---
## Sobre o Ansible
----
### O que é o Ansible?
- Ferramenta de automatização para configurar sistemas, fazer deploy, orquestração, provisionamento...
- Projeto open-source escrito em Python
- Lançado em fevereiro de 2012
- Adquirido pela Red Hat em outubro de 2015
----
### Funcionamento
- Nó de controle
- Nós gerenciados (inventário)
- Scripts declarativos e idempotentes
- "Não pede para remover o arquivo, e sim que ele não exista"
- Módulos - Playbooks - Roles
----
### Diferencial
- Sem agente como o Puppet (apenas SSH e Python)
- Sem armazenar estado como o Terraform
----
### Exemplo de Playbook
```yaml
- name: Exemplo
hosts: all
tasks:
- name: Deixa uma marca
ansible.builtin.command: "touch /tmp/ansible_was_here"
- name: Configura serviço
ansible.builtin.template:
src: config.j2
dest: /etc/servico/config
- name: Instala bash-completion
ansible.builtin.apt: name=bash-completion
```
----
### Onde aplicar?
- Substituir shell script
- Ambiente onde ocorrem ações manuais
- Ações repetitivas
- Ambientes descartáveis
- Configurar vários dispositivos
- ...
#### Observação
- Necessário criar script para desfazer o que foi feito
---
## Instalação
----
### Requisitos
- **Nó de controle**
- Ambiente UNIX (GNU/Linux, MacOS...)
- Python 2.7 ou >= 3.5 (3.8)
- Outras dependências conforme os plugins
- **Nós gerenciados**
- Conectividade SSH e SFTP/SCP
- Python >= 2.6 ou >= 3.5
- Biblioteca SELinux para Python se estiver habilitado
----
### Ansible X ansible-core
- `ansible-core` (antes `ansible-base`) é o pacote mínimo
- Ansible é o pacote com coleções desenvolvidos pela comunidade
- playbooks, roles, módulos, plugins...
```shell
pip install ansible | ansible-core
apt install ansible
dnf install ansible
yum install ansible
...
```
---
## Hello World
----
### Arquivo de configuração (opcional)
- [Documentação](https://docs.ansible.com/ansible/2.10/reference_appendices/config.html)
- `ansible.cfg` global ou local
```ini
[defaults]
interpreter_python=/usr/bin/python3
```
----
### Inventário
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html)
- Arquivo estático, dinâmico ou por plugin
- `/etc/ansible/hosts`, `-i <path>` ou `-i <host1,host2,...>`
----
#### Inventário INI
```ini
mail.example.com
[webservers]
foo.example.com http_port=80
bar.example.com http_port=8080
[dbservers]
one.example.com
two.example.com
three.example.com
[dbserver:vars]
dbname=app
```
----
#### Inventario YAML
```yaml
all:
hosts:
mail.example.com:
children:
webservers:
hosts:
foo.example.com:
http_port: 80
bar.example.com:
http_port: 8080
dbservers:
hosts:
one.example.com:
two.example.com:
three.example.com:
vars:
dbname: app
```
----
### Comando Ad-hoc
```shell
ansible [pattern] -m [module] -a "[module options]"
```
#### Testando
```shell
ansible all -i localhost, -m ping
localhost | SUCCESS => {
"changed": false,
"ping": "pong"
}
```
```shell
ansible all -i localhost, -a "echo teste"
localhost | CHANGED | rc=0 >>
teste
```
----
### Playbook
```yaml
- name: Hello World
hosts: all
tasks:
- name: Ping
ansible.builtin.ping:
- name: Echo
ansible.builtin.command: "echo teste"
```
----
```
ansible-playbook -i localhost, playbook.yml
PLAY [Hello World] ***********************************************************************************************
TASK [Gathering Facts] *******************************************************************************************
ok: [localhost]
TASK [Ping] ******************************************************************************************************
ok: [localhost]
TASK [Echo] ******************************************************************************************************
changed: [localhost]
PLAY RECAP *******************************************************************************************************
localhost : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
---
## Módulos e plugins
https://docs.ansible.com/ansible/latest/collections/all_plugins.html
---
## Funcionalidades dos Playbooks
----
### Execução
```shell
ansible-playbook [argumentos] playbook [playbook...]
```
| Parâmetro | Descrição |
| --------- | --------- |
| `--syntax-check` | Valida sintaxe |
| `--list-hosts` | Lista hosts |
| `--step` | Confirma execução a cada task |
| `-C`, `--check` | Modo dry-run |
| `-D`, `--diff` | Mostra o que foi alterado |
----
| Parâmetro | Descrição |
| --------- | --------- |
| `-v`, `--verbose` | Modo verboso, pode ser utilizado mais vezes |
| `-u REMOTE_USER`, `--user REMOTE_USER` | Usuário do SSH |
| `-k`, `--ask-pass` | Solicita senha do usuário no terminal |
----
### Gathering Facts
- Coletar informações sobre os hosts que podem ser utilizadas nos playbooks
```shell
ansible all -i localhost, -m ansible.builtin.setup
```
```yaml
- name: Exibe nome do virtualizador
ansible.builtin.command: "echo {{ ansible_virtualization_type }}"
```
----
### Jinja2
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/playbooks_templating.html)
- Motor de template que pode ser utilizado para:
- [Filtros](https://jinja2docs.readthedocs.io/en/stable/templates.html#builtin-filters)
- [Arquivos de configuração](https://jinja2docs.readthedocs.io/en/stable/templates.html)
```yaml
- name: Filtro do Jinja2
ansible.builtin.command: "echo {{ variavel|default('Sem informação') }}"
vars:
variavel: 123
- name: Configura serviço
ansible.builtin.template:
src: config.j2
dest: /etc/servico/config
```
----
### Become
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/become.html)
- Utilizado para escalar privilégios
- `-b`, `--become`
- `-K`, `--ask-become-pass`
```ini
webserver.empresa.com ansible_become_method=sudo ansible_become_password=1234
database.empresa.com ansible_become_method=su ansible_become_password=4321
```
```yaml
- name: Instala servidor Web
ansible.builtin.apt:
name: apache2
become: true
```
----
### Loops
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html)
- Iterar sobre uma lista
```yaml
- name: Itera em uma lista
ansible.builtin.command: "echo {{ item }}"
loop:
- "apache2"
- "bind9"
- "php-cgi"
```
----
### Conditionals
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html)
- Determina se uma task deve ser executada ou não
```yaml
- name: Instala driver de vídeo para KVM
ansible.builtin.apt:
name: xserver-xorg-video-qxl
when: ansible_virtualization_type == "kvm" and ansible_virtualization_role == "guest"
```
----
### Block
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html)
- Junta várias tasks em um único bloco
```yaml
tasks:
- name: Configura apache
block:
- name: Instala apache
ansible.builtin.apt:
name: apache2
- ...
become: true
become_user: root
```
----
### Register
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#registering-variables)
- Guarda resposta da execução de um módulo
```yaml
- name: Verifica home do usuário
ansible.builtin.stat:
path: /home/{{ ansible_user }}
register: homedir
- name: Configura git para o usuário
ansible.builtin.copy:
src: gitconfig
dest: /home/{{ ansible_user }}/.gitconfig
when: homedir.stat.exists
```
----
### Handlers
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/playbooks_handlers.html)
- Dispara outras ações conforme o que ocorreu
```yaml
- name: Configura apache
ansible.builtin.template:
src: template.j2
dest: /etc/foo.conf
notify:
- Restart apache
- ...
handlers:
- name: Restart apache
ansible.builtin.service:
name: apache
state: restarted
```
----
### Roles
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html)
- Organização e reutilização de script
----
### Tags
- [Documentação](https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html)
- Selecionar que parte do script executar
```shell
ansible-playbook --tags "configuration,packages" ...
ansible-playbook --skip-tags "packages" ...
```
---
## Ansible Galaxy
https://galaxy.ansible.com/
[Documentação](https://docs.ansible.com/ansible/latest/galaxy/user_guide.html)
----
### Criando uma coleção
```shell
ansible-galaxy collection init eduardoklosowski.teste
eduardoklosowski/teste/
├── docs
├── galaxy.yml
├── plugins
│ └── README.md
├── README.md
└── roles
```
----
### Criando um role
```shell
cd eduardoklosowski/teste/roles
ansible-galaxy role init helloworld
helloworld/
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml
```
----
### Exemplo
https://galaxy.ansible.com/eduardoklosowski
---
## Outros
- [Ansible-Pull](https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#ansible-pull)
- [Ansible Vault](https://docs.ansible.com/ansible/latest/user_guide/vault.html)
---
## Materiais para estudo
- [Fundamentos do Ansible: simplicidade em automação técnica (visão geral)](https://www.redhat.com/pt-br/services/training/do007-ansible-essentials-simplicity-automation-technical-overview)
- [Katacoda RHEL](https://katacoda.com/rhel-labs)
- [Ansible Examples](https://github.com/ansible/ansible-examples)