├── .gitignore ├── README.md ├── Vagrantfile ├── ansible ├── ansible.cfg ├── balancer-v2.yml ├── balancer-v3.yml ├── balancer.yml ├── balancer │ ├── README.md │ ├── defaults │ │ └── main.yml │ ├── handlers │ │ └── main.yml │ ├── meta │ │ └── main.yml │ ├── tasks │ │ ├── debian.yml │ │ ├── main.yml │ │ └── redhat.yml │ ├── templates │ │ ├── haproxy.j2 │ │ └── keepalived.j2 │ ├── tests │ │ ├── inventory │ │ └── test.yml │ └── vars │ │ ├── debian.yml │ │ ├── main.yml │ │ └── redhat.yml ├── debian.yml ├── files │ ├── haproxy.cfg │ ├── haproxy.j2 │ ├── keepalived.conf │ └── keepalived.j2 ├── inventory.ini ├── playbook.yml ├── provision.yml ├── redhat.yml ├── site │ ├── css │ │ └── style.css │ ├── images │ │ ├── ansible.png │ │ └── favicon.png │ └── index.html ├── webserver-v2.yml └── webserver.yml ├── images ├── ansible.png ├── virtualbox-01.png ├── virtualbox-02.png ├── virtualbox-03.png ├── virtualbox-04.png ├── virtualbox-05.png ├── virtualbox-06.png ├── virtualbox-07.png ├── virtualbox-08.png ├── virtualbox-09.png ├── virtualbox-10.png ├── virtualbox-11.png ├── virtualbox-12.png ├── virtualbox-13.png ├── virtualbox-14.png └── youtube-video.png ├── provision ├── id_ed25519 └── id_ed25519.pub └── steps ├── ova.md └── vagrant.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | .vagrant 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NIC.br Ansible 2 | 3 | Este repositório guarda os arquivos para o laboratório de Ansible da palestra da NIC.br de 2022. 4 | 5 | Para fazer o laboratório é preciso possuir um software de virtualização, conhecido como hypervisor, como por exemplo o [VirtualBox](https://www.virtualbox.org/). Para atender ao maior número de pessoas possíveis, todas as ferramentas utilizadas e recomendadas neste laboratório são livres e de código aberto. 6 | 7 | Existem outros hypervisors como o [KVM](https://www.linux-kvm.org/page/Main_Page) para Linux ou outras soluções fechadas para Windows ou sistemas operacionais da Apple, porém o foco será sempre o VirtualBox. 8 | 9 | Para criar o laboratório é possível utilizar o `Vagrant` ou baixar o arquivo [ansible.ova](https://drive.google.com/file/d/1DfS5piCj1AX0k8O3Njoax5BNQ6dA2GX_/view?usp=sharing) e importá-lo no VirtualBox, a primeira forma é mais moderna e trás mais possibilidades de estudo para o usuário. 10 | 11 | Escolha uma das opções abaixo para obter melhores instruções sobre como preparar o ambiente: 12 | 13 | - [Vangrat](https://github.com/hector-vido/nicbr-ansible/tree/master/steps/vagrant.md) 14 | - [ansible.ova](https://github.com/hector-vido/nicbr-ansible/tree/master/steps/ova.md) 15 | 16 | **Atenção:** 17 | - Será preciso habilitar a capacidade de virtualização do seu processador na "BIOS" do seu computador. 18 | - O Vagrant tem maior compatibilidade com o `VirtualBox` e o `Libvirt`, nem todas as imagens estão disponíveis para todos os hypervisors. 19 | - O funcionamento do `HyperV` com o Vagrant é parcial, as máquinas não conseguem ser configuradas com endereço IP fixo. 20 | - O `HyperV` ou mesmo versões não originais do `VMWare Workstation` podem causar problemas nada óbvios no `VirtualBox`, não use software pirata, use Linux. 21 | - Algums versões do Windows possuem componentes do `HyperV` instalados que podem causar problemas no `VirtualBox`. 22 | - Até o momento não há hypervisors livres de arquitetura `amd64`(`x86_64`) para sistemas operacionais da Apple `arm64`, se possui uma máquina destas, venda, compre um computador de verdade e ajude alguém com o dinheiro que sobrar. 23 | - O Fedora 36 está com problemas para configurar endereço IP fixo. 24 | 25 | # Ansible 26 | 27 |  28 | 29 | De forma simplista, Ansible é uma ferramenta de automação, mas é importante entender de qual tipo automação estamos falando e que "Ansible" não é apenas uma única ferramenta. 30 | 31 | Ansible é um projeto livre e de código aberto voltado para o provisionamento, gerência de configuração e implantação de software que nos possibilita utilizar [Infraestrutura como Código](https://pt.wikipedia.org/wiki/Infraestrutura_como_C%C3%B3digo). Foi desenvolvido originalmente por Michael DeHaan e adquirido pela Red Hat em 2015. 32 | 33 | Na maioria das vezes as operações do Ansible acontecem através de uma máquina central, normalmente a mesma que está usando para ler este texto, se comunicando com outros dispositivos, APIs ou qualquer outro protocolo disponível. Essa máquina é conhecida como **control node**. 34 | 35 | Na grande maioria das vezes utilizamos o Ansible para configurar outras máquinas, os **managed nodes**, e fazemos isso através de [**módulos**](https://docs.ansible.com/ansible/2.9/modules/list_of_all_modules.html). Para cada tarefa que deseja fazer (instalar um pacote, criar um usuário, copiar um arquivo), haverá um módulo especifico. Durante a execução, o Ansible se conectará ao nó gerenciado, copiando o módulo (normalmente código python) e o executando. 36 | 37 | Para fazer a conexões em outras máquinas o Ansible utiliza o bom e velho [**SSH**](https://pt.wikipedia.org/wiki/Secure_Shell) em máquinas Linux ou o [**winrm**](https://en.wikipedia.org/wiki/Windows_Remote_Management) em máquinas Windows, formas de conexão já conhecidas pelos profissionais de cada um destes sistemas. 38 | 39 | Apesar de configurar máquinas ser a principal função do Ansible, esta não é a sua única capacidade. Podemos utilizar o Ansible para consumir APIs, configurar equipamentos de rede (switches, pontos de acesso, etc), fazer testes (verificar se uma porta está aberta, procurar uma palavra em um site) e praticamente tudo o que sua criatividade e persistência lhe permitir. 40 | 41 | Para **codificarmos nossa infraestrutura** em Ansible utilizamos um arquivo de texto bastante fácil de se ler e escrever chamado **playbook**. Uma playbook descreve as tarefas que queremos executar e são escritas no formato de serialização [YAML](https://pt.wikipedia.org/wiki/YAML). 42 | 43 | Para informar ao Ansible quais nós queremos gerenciar utilizamos um **inventário**. Basicamente um inventário é um arquivo de texto simples com informações pertinentes de cada nó. É muito comum utilizarmos o formato `.ini` já conhecido no Linux, mas podemos escrevê-los em outros formatos como `.json` ou `.yaml`. 44 | 45 | Existem duas características interessantes do Ansible, a sua forma declarativa e a sua idempotência. 46 | 47 | ## Forma Declarativa 48 | 49 | Uma das características do Ansible é trabalhar de forma declarativa, nós não especificamos como as coisas devem ser feitas e sim como as coisas devem ficar. 50 | 51 | Por exemplo, para instalar o `vim` nós não digitamos o comando de instalação de forma imperativa: 52 | 53 | ```bash 54 | dnf install -y vim 55 | ``` 56 | 57 | Muito pelo contrário, nós especificamos o pacote e seu estado e o Ansible ficará responsável por resolver: 58 | 59 | ```yml 60 | package: 61 | name: vim 62 | state: present 63 | ``` 64 | 65 | Dessa forma eu não preciso me preocupar tanto com parâmetros e características peculiares de uma determinada distribuição. Nem sempre é possível trabalhar assim, mas é interessante ter esse conceito em mente. 66 | 67 | ## Idempotência 68 | 69 | Idempotência, em ciência da computação, é a propriedade que algumas operações tem de poderem ser executadas diversas vezes sem que o resultado final se altere após a primeira execução. Neste nosso caso, significa que podemos executar um "código do Ansible" para, por exemplo, criar um usuário sem se preocupar se suas execuções subsequentes apresentarão problemas com o usuário agora existente. 70 | 71 | No Linux, se tentarmos cadastrar o mesmo usuário duas vezes, teremos um erro na segunda execução, pois o usuário já existe. 72 | 73 | # E o Ansible da Red Hat? 74 | 75 | O Ansible que a Red Hat fornece aos seus clientes é baseado na versão community do Ansible, é praticamente o mesmo, porém seus módulos e demais complementos que podemos adicionar passam por um teste ainda mais rigoroso e passam a ser suportados pela própria Red Hat. 76 | 77 | Se você quer conhecer as ferramentas da Red Hat, é um desenvolvedor, ou apenas um curioso, e não pretende necessariamente adquirir a subscrição é possível ingressar gratuitamente no [Red Hat Developer Program](https://developers.redhat.com/about) e ter acesso a todas essas ferramentas, inclusive para usar em produção. 78 | 79 | -------------------------------------------------------------------------------- /Vagrantfile: -------------------------------------------------------------------------------- 1 | # -*- mode: ruby -*- 2 | # vi: set ft=ruby : 3 | 4 | vms = { 5 | # 'ansible' => {'memory' => '1024', 'cpus' => 1, 'ip' => '10', 'box' => 'ubuntu/kinetic64'}, 6 | 'alma' => {'memory' => '1024', 'cpus' => 1, 'ip' => '101', 'box' => 'almalinux/9'}, 7 | 'debian' => {'memory' => '1024', 'cpus' => 1, 'ip' => '102', 'box' => 'debian/bullseye64'}, 8 | 'fedora' => {'memory' => '1024', 'cpus' => 1, 'ip' => '201', 'box' => 'fedora/35-cloud-base'}, 9 | 'opensuse' => {'memory' => '1024', 'cpus' => 1, 'ip' => '202', 'box' => 'opensuse/Leap-15.4.x86_64'} 10 | } 11 | 12 | Vagrant.configure('2') do |config| 13 | 14 | config.vm.box_check_update = false 15 | 16 | vms.each do |name, conf| 17 | 18 | config.vm.define "#{name}" do |k| 19 | k.vm.hostname = "#{name}.ansible.local" 20 | k.vm.network 'private_network', ip: "192.168.56.#{conf['ip']}" 21 | k.vm.box = conf['box'] 22 | 23 | k.vm.provider 'virtualbox' do |vb| 24 | vb.memory = conf['memory'] 25 | vb.cpus = conf['cpus'] 26 | end 27 | 28 | k.vm.provider 'libvirt' do |lv| 29 | lv.cpus = conf['cpus'] 30 | lv.memory = conf['memory'] 31 | lv.cputopology :sockets => 1, :cores => conf['cpus'], :threads => 1 32 | end 33 | 34 | k.vm.provision 'shell', inline: <<-SHELL 35 | mkdir -p /root/.ssh 36 | cp /vagrant/provision/id_ed25519 /root/.ssh 37 | chmod 400 /root/.ssh/id_ed25519* 38 | cp /vagrant/provision/id_ed25519.pub /root/.ssh/authorized_keys 39 | sed -Ei 's,#PermitRootLogin prohibit-password,PermitRootLogin yes,' /etc/ssh/sshd_config 40 | sed -Ei 's,#?PasswordAuthentication .*,PasswordAuthentication yes,' /etc/ssh/sshd_config 41 | systemctl restart sshd 42 | > /etc/udev/rules.d/70-persistent-net.rules 43 | SHELL 44 | 45 | end 46 | 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /ansible/ansible.cfg: -------------------------------------------------------------------------------- 1 | # https://github.com/ansible/ansible/blob/stable-2.9/examples/ansible.cfg 2 | 3 | [defaults] 4 | interpreter_python = /usr/bin/python3 5 | host_key_checking = False 6 | 7 | inventory = inventory.ini 8 | remote_user = root 9 | private_key_file = ../provision/id_ed25519 10 | -------------------------------------------------------------------------------- /ansible/balancer-v2.yml: -------------------------------------------------------------------------------- 1 | - hosts: balancers 2 | become: yes 3 | tasks: 4 | # ------------ Debian -------------- 5 | - name: Executa as ações em Debian 6 | include_tasks: debian.yml 7 | when: ansible_os_family == 'Debian' 8 | # ------------ Red Hat ------------- 9 | - name: Executa as ações em Red Hat 10 | include_tasks: redhat.yml 11 | when: ansible_os_family == 'RedHat' 12 | # ------------- Geral -------------- 13 | - name: Garante que o HAProxy esteja presente 14 | package: 15 | name: haproxy, keepalived 16 | state: present 17 | - name: Garante que o arquivo de configuração esteja presente 18 | copy: 19 | src: files/haproxy.cfg 20 | dest: /etc/haproxy/haproxy.cfg 21 | register: haproxy 22 | - name: Garante que o serviço do HAProxy esteja iniciado 23 | service: 24 | name: haproxy 25 | state: started 26 | enabled: yes 27 | - name: Garante que o serviço do HAProxy receba as modificações 28 | service: 29 | name: haproxy 30 | state: reloaded 31 | when: haproxy.changed == true 32 | - name: Garante que o arquivo do keepalived esteja presente 33 | template: 34 | src: files/keepalived.j2 35 | dest: /etc/keepalived/keepalived.conf 36 | register: keepalived 37 | - name: Garante que o serviço do keepalived esteja iniciado 38 | service: 39 | name: keepalived 40 | state: started 41 | enabled: yes 42 | - name: Garante que o serviço do keepalived receba as modificações 43 | service: 44 | name: keepalived 45 | state: reloaded 46 | when: keepalived.changed == true 47 | - name: Garante que o kernel esteja ajustado para o HAProxy 48 | lineinfile: 49 | path: /etc/sysctl.conf 50 | line: '{{ item }}' 51 | state: present 52 | loop: 53 | - 'net.ipv4.tcp_rmem = 4096 16060 262144' 54 | - 'net.ipv4.tcp_wmem = 4096 16384 262144' 55 | - 'net.ipv4.tcp_tw_reuse = 1' 56 | - 'net.ipv4.ip_local_port_range = 1024 65023' 57 | - 'net.ipv4.tcp_max_syn_backlog = 60000' 58 | - 'net.ipv4.tcp_fin_timeout = 30' 59 | - 'net.ipv4.tcp_synack_retries = 3' 60 | - 'net.ipv4.ip_nonlocal_bind = 1' 61 | - 'net.core.somaxconn = 60000' 62 | - name: Garante que o kernel receba as configurações 63 | service: 64 | name: systemd-sysctl 65 | state: restarted 66 | -------------------------------------------------------------------------------- /ansible/balancer-v3.yml: -------------------------------------------------------------------------------- 1 | - name: Provisionando os balancers 2 | hosts: balancers 3 | become: yes 4 | tasks: 5 | - name: Inclui o arquivo de tarefas especificas da distribuicao 6 | include_tasks: '{{ ansible_os_family|lower }}.yml' 7 | - name: Garantindo que os pacotes haproxy e keepalived estejam instalados 8 | package: 9 | name: haproxy, keepalived 10 | state: present 11 | - name: Garantindo o arquivo de configuração do HAProxy 12 | template: 13 | src: files/haproxy.cfg 14 | dest: /etc/haproxy/haproxy.cfg 15 | register: haproxy_config 16 | - name: Garantindo o arquivo de configuração do keepalived 17 | template: 18 | src: files/keepalived.conf 19 | dest: /etc/keepalived/keepalived.conf 20 | notify: Restart keepalived 21 | - name: Garantindo que o serviço do HAProxy esteja rodando 22 | service: 23 | name: haproxy 24 | state: started 25 | enabled: yes 26 | - name: Garantindo que o serviço do HAProxy receba as configurações 27 | service: 28 | name: haproxy 29 | state: reloaded 30 | when: haproxy_config.changed == true 31 | - name: Garantindo que o serviço do keepalived esteja rodando 32 | service: 33 | name: keepalived 34 | state: started 35 | enabled: yes 36 | - name: Garante que o kernel esteja ajustado para o HAProxy 37 | lineinfile: 38 | path: /etc/sysctl.conf 39 | line: '{{ item }}' 40 | state: present 41 | loop: 42 | - 'net.ipv4.tcp_rmem = 4096 16060 262144' 43 | - 'net.ipv4.tcp_wmem = 4096 16384 262144' 44 | - 'net.ipv4.tcp_tw_reuse = 1' 45 | - 'net.ipv4.ip_local_port_range = 1024 65023' 46 | - 'net.ipv4.tcp_max_syn_backlog = 60000' 47 | - 'net.ipv4.tcp_fin_timeout = 30' 48 | - 'net.ipv4.tcp_synack_retries = 3' 49 | - 'net.ipv4.ip_nonlocal_bind = 1' 50 | - 'net.core.somaxconn = 60000' 51 | - name: Garante que o kernel receba as configurações 52 | service: 53 | name: systemd-sysctl 54 | state: restarted 55 | 56 | handlers: 57 | - name: Restart keepalived 58 | service: 59 | name: keepalived 60 | state: reloaded 61 | -------------------------------------------------------------------------------- /ansible/balancer.yml: -------------------------------------------------------------------------------- 1 | - hosts: balancers 2 | become: yes 3 | tasks: 4 | - name: Atualiza os pacotes do Debian 5 | apt: 6 | update_cache: yes 7 | when: ansible_os_family == 'Debian' 8 | - name: Garante que o serviço firewalld esteja rodando 9 | service: 10 | name: firewalld 11 | state: started 12 | enabled: yes 13 | when: ansible_os_family == 'RedHat' 14 | - name: Permite o tráfego na porta 80 e 443 15 | ansible.posix.firewalld: 16 | service: '{{ item }}' 17 | permanent: yes 18 | state: enabled 19 | immediate: yes 20 | loop: 21 | - http 22 | - https 23 | when: ansible_os_family == 'RedHat' 24 | - ansible.posix.firewalld: 25 | rich_rule: rule protocol value="vrrp" accept 26 | permanent: yes 27 | state: enabled 28 | immediate: yes 29 | when: ansible_os_family == 'RedHat' 30 | - name: Garante que o HAProxy esteja presente 31 | package: 32 | name: haproxy, keepalived 33 | state: present 34 | - name: Garante que o módulo python3-libsemanage esteja instalado 35 | package: 36 | name: python3-libsemanage 37 | state: present 38 | when: ansible_os_family == 'RedHat' 39 | - name: Garante que o SELinux permita o HAProxy a usar as portas 40 | ansible.posix.seboolean: 41 | name: haproxy_connect_any 42 | state: yes 43 | persistent: yes 44 | when: ansible_os_family == 'RedHat' 45 | - name: Garante que o arquivo de configuração esteja presente 46 | copy: 47 | src: files/haproxy.cfg 48 | dest: /etc/haproxy/haproxy.cfg 49 | register: haproxy 50 | - name: Garante que o serviço do HAProxy esteja iniciado 51 | service: 52 | name: haproxy 53 | state: started 54 | enabled: yes 55 | - name: Garante que o serviço do HAProxy receba as modificações 56 | service: 57 | name: haproxy 58 | state: reloaded 59 | when: haproxy.changed == true 60 | - name: Garante que o arquivo do keepalived esteja presente 61 | template: 62 | src: files/keepalived.j2 63 | dest: /etc/keepalived/keepalived.conf 64 | register: keepalived 65 | - name: Garante que o serviço do keepalived esteja iniciado 66 | service: 67 | name: keepalived 68 | state: started 69 | enabled: yes 70 | - name: Garante que o serviço do keepalived receba as modificações 71 | service: 72 | name: keepalived 73 | state: reloaded 74 | when: keepalived.changed == true 75 | - name: Garante que o kernel esteja ajustado para o HAProxy 76 | lineinfile: 77 | path: /etc/sysctl.conf 78 | line: '{{ item }}' 79 | state: present 80 | loop: 81 | - 'net.ipv4.tcp_rmem = 4096 16060 262144' 82 | - 'net.ipv4.tcp_wmem = 4096 16384 262144' 83 | - 'net.ipv4.tcp_tw_reuse = 1' 84 | - 'net.ipv4.ip_local_port_range = 1024 65023' 85 | - 'net.ipv4.tcp_max_syn_backlog = 60000' 86 | - 'net.ipv4.tcp_fin_timeout = 30' 87 | - 'net.ipv4.tcp_synack_retries = 3' 88 | - 'net.ipv4.ip_nonlocal_bind = 1' 89 | - 'net.core.somaxconn = 60000' 90 | - name: Garante que o kernel receba as configurações 91 | service: 92 | name: systemd-sysctl 93 | state: restarted 94 | -------------------------------------------------------------------------------- /ansible/balancer/README.md: -------------------------------------------------------------------------------- 1 | Role Name 2 | ========= 3 | 4 | A brief description of the role goes here. 5 | 6 | Requirements 7 | ------------ 8 | 9 | Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required. 10 | 11 | Role Variables 12 | -------------- 13 | 14 | A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well. 15 | 16 | Dependencies 17 | ------------ 18 | 19 | A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles. 20 | 21 | Example Playbook 22 | ---------------- 23 | 24 | Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: 25 | 26 | - hosts: servers 27 | roles: 28 | - { role: username.rolename, x: 42 } 29 | 30 | License 31 | ------- 32 | 33 | BSD 34 | 35 | Author Information 36 | ------------------ 37 | 38 | An optional section for the role authors to include contact information, or a website (HTML is not allowed). 39 | -------------------------------------------------------------------------------- /ansible/balancer/defaults/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # defaults file for balancer 3 | keepalived_state: BACKUP 4 | keepalived_priority: 254 5 | -------------------------------------------------------------------------------- /ansible/balancer/handlers/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # handlers file for balancer 3 | - name: Reload HAProxy 4 | service: 5 | name: haproxy 6 | state: reloaded 7 | - name: Reload keepalived 8 | service: 9 | name: keepalived 10 | state: reloaded 11 | - name: Restart sysctl 12 | service: 13 | name: systemd-sysctl 14 | state: restarted 15 | -------------------------------------------------------------------------------- /ansible/balancer/meta/main.yml: -------------------------------------------------------------------------------- 1 | galaxy_info: 2 | author: your name 3 | description: your role description 4 | company: your company (optional) 5 | 6 | # If the issue tracker for your role is not on github, uncomment the 7 | # next line and provide a value 8 | # issue_tracker_url: http://example.com/issue/tracker 9 | 10 | # Choose a valid license ID from https://spdx.org - some suggested licenses: 11 | # - BSD-3-Clause (default) 12 | # - MIT 13 | # - GPL-2.0-or-later 14 | # - GPL-3.0-only 15 | # - Apache-2.0 16 | # - CC-BY-4.0 17 | license: license (GPL-2.0-or-later, MIT, etc) 18 | 19 | min_ansible_version: 2.1 20 | 21 | # If this a Container Enabled role, provide the minimum Ansible Container version. 22 | # min_ansible_container_version: 23 | 24 | # 25 | # Provide a list of supported platforms, and for each platform a list of versions. 26 | # If you don't wish to enumerate all versions for a particular platform, use 'all'. 27 | # To view available platforms and versions (or releases), visit: 28 | # https://galaxy.ansible.com/api/v1/platforms/ 29 | # 30 | # platforms: 31 | # - name: Fedora 32 | # versions: 33 | # - all 34 | # - 25 35 | # - name: SomePlatform 36 | # versions: 37 | # - all 38 | # - 1.0 39 | # - 7 40 | # - 99.99 41 | 42 | galaxy_tags: [] 43 | # List tags for your role here, one per line. A tag is a keyword that describes 44 | # and categorizes the role. Users find roles by searching for tags. Be sure to 45 | # remove the '[]' above, if you add tags to this list. 46 | # 47 | # NOTE: A tag is limited to a single word comprised of alphanumeric characters. 48 | # Maximum 20 tags per role. 49 | 50 | dependencies: [] 51 | # List your role dependencies here, one per line. Be sure to remove the '[]' above, 52 | # if you add dependencies to this list. 53 | -------------------------------------------------------------------------------- /ansible/balancer/tasks/debian.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # debian tasks file for balancer 3 | - name: Atualiza os pacotes do Debian 4 | apt: 5 | update_cache: yes 6 | when: ansible_os_family == 'Debian' 7 | -------------------------------------------------------------------------------- /ansible/balancer/tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # tasks file for balancer 3 | - name: Inclui variáveis específicas da distro 4 | include_vars: '{{ ansible_os_family|lower }}.yml' 5 | - name: Executa as ações específicas da distro 6 | include_tasks: '{{ ansible_os_family|lower }}.yml' 7 | - name: Garante que o HAProxy esteja presente 8 | package: 9 | name: haproxy, keepalived 10 | state: present 11 | - name: Garante que o arquivo de configuração do HAProxy esteja presente 12 | template: 13 | src: haproxy.j2 14 | dest: /etc/haproxy/haproxy.cfg 15 | notify: Reload HAProxy 16 | - name: Garante que o serviço do HAProxy esteja iniciado 17 | service: 18 | name: haproxy 19 | state: started 20 | enabled: yes 21 | - name: Garante que o arquivo do keepalived esteja presente 22 | template: 23 | src: keepalived.j2 24 | dest: /etc/keepalived/keepalived.conf 25 | notify: Reload keepalived 26 | - name: Garante que o serviço do keepalived esteja iniciado 27 | service: 28 | name: keepalived 29 | state: started 30 | enabled: yes 31 | - name: Garante que o kernel esteja ajustado para o HAProxy 32 | lineinfile: 33 | path: /etc/sysctl.conf 34 | line: '{{ item }}' 35 | state: present 36 | loop: 37 | - 'net.ipv4.tcp_rmem = 4096 16060 262144' 38 | - 'net.ipv4.tcp_wmem = 4096 16384 262144' 39 | - 'net.ipv4.tcp_tw_reuse = 1' 40 | - 'net.ipv4.ip_local_port_range = 1024 65023' 41 | - 'net.ipv4.tcp_max_syn_backlog = 60000' 42 | - 'net.ipv4.tcp_fin_timeout = 30' 43 | - 'net.ipv4.tcp_synack_retries = 3' 44 | - 'net.ipv4.ip_nonlocal_bind = 1' 45 | - 'net.core.somaxconn = 60000' 46 | notify: Restart sysctl 47 | -------------------------------------------------------------------------------- /ansible/balancer/tasks/redhat.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # redhat tasks file for balancer 3 | - name: Garante que o serviço firewalld esteja rodando 4 | service: 5 | name: firewalld 6 | state: started 7 | enabled: yes 8 | - name: Permite o tráfego na porta 80 e 443 9 | ansible.posix.firewalld: 10 | service: '{{ item }}' 11 | permanent: yes 12 | state: enabled 13 | immediate: yes 14 | loop: 15 | - http 16 | - https 17 | - name: Garante que o protocolo VRRP esteja liberado no firewalld 18 | ansible.posix.firewalld: 19 | rich_rule: rule protocol value="vrrp" accept 20 | permanent: yes 21 | state: enabled 22 | immediate: yes 23 | - name: Garante que o módulo libsemange esteja presente 24 | package: 25 | name: python3-libsemanage 26 | state: present 27 | - name: Garante que o SELinux permita o HAProxy a usar as portas 28 | ansible.posix.seboolean: 29 | name: haproxy_connect_any 30 | state: yes 31 | persistent: yes 32 | -------------------------------------------------------------------------------- /ansible/balancer/templates/haproxy.j2: -------------------------------------------------------------------------------- 1 | # /etc/haproxy/haproxy.cfg 2 | 3 | defaults 4 | timeout http-request 10s 5 | timeout queue 1m 6 | timeout connect 10s 7 | timeout client 1m 8 | timeout server 1m 9 | timeout http-keep-alive 10s 10 | timeout check 1s 11 | 12 | frontend stats 13 | bind *:1936 14 | mode http 15 | maxconn 10 16 | stats enable 17 | stats hide-version 18 | stats refresh 1s 19 | stats show-node 20 | stats show-desc Stats for webservers 21 | stats auth admin:admin 22 | stats uri /stats 23 | 24 | # http 80 25 | listen webservers-http 26 | bind *:80 27 | mode tcp # http 28 | balance roundrobin # leastconn, source 29 | {% for host in groups['webservers'] %} 30 | server webserver{{ loop.index }} {{ hostvars[host].inventory_hostname }}:80 check inter 1s 31 | {% endfor %} 32 | 33 | # https 443 34 | listen webservers-https 35 | bind *:443 36 | mode tcp 37 | balance roundrobin # leastconn, sourc 38 | {% for host in groups['webservers'] %} 39 | server webserver{{ loop.index }} {{ hostvars[host].inventory_hostname }}:443 check inter 1s 40 | {% endfor %} 41 | -------------------------------------------------------------------------------- /ansible/balancer/templates/keepalived.j2: -------------------------------------------------------------------------------- 1 | vrrp_instance ansible { 2 | state {{ keepalived_state }} 3 | interface {{ keepalived_interface }} 4 | virtual_router_id 51 5 | priority {{ keepalived_priority }} 6 | advert_int 1 7 | authentication { 8 | auth_type PASS 9 | auth_pass ansible 10 | } 11 | virtual_ipaddress { 12 | 192.168.56.100/24 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ansible/balancer/tests/inventory: -------------------------------------------------------------------------------- 1 | localhost 2 | 3 | -------------------------------------------------------------------------------- /ansible/balancer/tests/test.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: localhost 3 | remote_user: root 4 | roles: 5 | - balancer 6 | -------------------------------------------------------------------------------- /ansible/balancer/vars/debian.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # debian vars file for balancer 3 | keepalived_interface: eth1 4 | -------------------------------------------------------------------------------- /ansible/balancer/vars/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # vars file for balancer 3 | -------------------------------------------------------------------------------- /ansible/balancer/vars/redhat.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # redhat vars file for balancer 3 | keepalived_interface: enp0s8 4 | -------------------------------------------------------------------------------- /ansible/debian.yml: -------------------------------------------------------------------------------- 1 | - name: Garantindo que a lista de pacotes esteja atualizada 2 | apt: 3 | update_cache: yes 4 | -------------------------------------------------------------------------------- /ansible/files/haproxy.cfg: -------------------------------------------------------------------------------- 1 | # /etc/haproxy/haproxy.cfg 2 | 3 | defaults 4 | timeout http-request 10s 5 | timeout queue 1m 6 | timeout connect 10s 7 | timeout client 1m 8 | timeout server 1m 9 | timeout http-keep-alive 10s 10 | timeout check 1s 11 | 12 | frontend stats 13 | bind *:1936 14 | mode http 15 | maxconn 10 16 | stats enable 17 | stats hide-version 18 | stats refresh 1s 19 | stats show-node 20 | stats show-desc Stats for webservers 21 | stats auth admin:admin 22 | stats uri /stats 23 | 24 | # http 80 25 | listen webservers-http 26 | bind *:80 27 | mode tcp # http 28 | balance roundrobin # leastconn, source 29 | server webserver1 192.168.56.201:80 check inter 1s 30 | server webserver2 192.168.56.202:80 check inter 1s 31 | 32 | # https 443 33 | listen webservers-https 34 | bind *:443 35 | mode tcp 36 | balance roundrobin # leastconn, sourc 37 | server webserver1 192.168.56.201:443 check inter 1s 38 | server webserver2 192.168.56.202:443 check inter 1s 39 | -------------------------------------------------------------------------------- /ansible/files/haproxy.j2: -------------------------------------------------------------------------------- 1 | # /etc/haproxy/haproxy.cfg 2 | 3 | defaults 4 | timeout http-request 10s 5 | timeout queue 1m 6 | timeout connect 10s 7 | timeout client 1m 8 | timeout server 1m 9 | timeout http-keep-alive 10s 10 | timeout check 1s 11 | 12 | frontend stats 13 | bind *:1936 14 | mode http 15 | maxconn 10 16 | stats enable 17 | stats hide-version 18 | stats refresh 1s 19 | stats show-node 20 | stats show-desc Stats for webservers 21 | stats auth admin:admin 22 | stats uri /stats 23 | 24 | # http 80 25 | listen webservers-http 26 | bind *:80 27 | mode tcp # http 28 | balance roundrobin # leastconn, source 29 | {% for host in groups.webservers %} 30 | server webserver{{ loop.index }} {{ host }}:80 check inter 1s 31 | {% endfor %} 32 | 33 | # https 443 34 | listen webservers-https 35 | bind *:443 36 | mode tcp 37 | balance roundrobin # leastconn, sourc 38 | {% for host in groups.webservers %} 39 | server webserver{{ loop.index }} {{ host }}:443 check inter 1s 40 | {% endfor %} 41 | -------------------------------------------------------------------------------- /ansible/files/keepalived.conf: -------------------------------------------------------------------------------- 1 | vrrp_instance ansible { 2 | state MASTER 3 | interface enp0s8 4 | virtual_router_id 51 5 | priority 255 6 | advert_int 1 7 | authentication { 8 | auth_type PASS 9 | auth_pass ansible 10 | } 11 | virtual_ipaddress { 12 | 192.168.56.100/24 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ansible/files/keepalived.j2: -------------------------------------------------------------------------------- 1 | vrrp_instance ansible { 2 | state {{ keepalived_state }} 3 | interface {{ keepalived_interface }} 4 | virtual_router_id 51 5 | priority {{ keepalived_priority }} 6 | advert_int 1 7 | authentication { 8 | auth_type PASS 9 | auth_pass ansible 10 | } 11 | virtual_ipaddress { 12 | 192.168.56.100/24 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ansible/inventory.ini: -------------------------------------------------------------------------------- 1 | [balancers] 2 | 192.168.56.101 keepalived_state=MASTER keepalived_interface=enp0s8 keepalived_priority=255 3 | 192.168.56.102 keepalived_state=BACKUP keepalived_interface=eth1 keepalived_priority=254 4 | 5 | [webservers] 6 | 192.168.56.201 7 | 192.168.56.202 8 | 9 | [balancers_limpo] 10 | 192.168.56.101 keepalived_state=MASTER keepalived_priority=255 11 | 192.168.56.102 12 | -------------------------------------------------------------------------------- /ansible/playbook.yml: -------------------------------------------------------------------------------- 1 | - hosts: balancers_limpo 2 | become: yes 3 | roles: 4 | - balancer 5 | -------------------------------------------------------------------------------- /ansible/provision.yml: -------------------------------------------------------------------------------- 1 | - name: Importa a playbook de webservers 2 | import_playbook: webserver-v2.yml 3 | - name: Importa a playbook de balancers 4 | import_playbook: balancer-v2.yml 5 | -------------------------------------------------------------------------------- /ansible/redhat.yml: -------------------------------------------------------------------------------- 1 | - name: Garantindo que o firewall esteja inicializado 2 | service: 3 | name: firewalld 4 | state: started 5 | enabled: yes 6 | - name: Garantindo que as portas 80 e 443 estejam abertas 7 | ansible.posix.firewalld: 8 | service: '{{ item }}' 9 | state: enabled 10 | immediate: yes 11 | permanent: yes 12 | loop: 13 | - http 14 | - https 15 | - name: Garantindo que o protocolo VRRP esteja liberado 16 | ansible.posix.firewalld: 17 | rich_rule: rule protocol value="vrrp" accept 18 | state: enabled 19 | immediate: yes 20 | permanent: yes 21 | - name: Garantindo que python3-libsemanage esteja instalado 22 | yum: 23 | name: python3-libsemanage 24 | state: present 25 | - name: Garantindo regra selinux para HAProxy 26 | ansible.posix.seboolean: 27 | name: haproxy_connect_any 28 | state: yes 29 | persistent: yes 30 | -------------------------------------------------------------------------------- /ansible/site/css/style.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | margin:0; 3 | padding:0; 4 | width:100%; 5 | height:100%; 6 | } 7 | body { 8 | font-family: Arial, sans-serif; 9 | background-color: #aee7d9; 10 | -webkit-animation: slide 4s linear infinite; 11 | -moz-animation: slide 4s linear; 12 | animation: slide 4s linear infinite; 13 | } 14 | 15 | #color-version { 16 | color: #aee7d9; 17 | -webkit-animation: text 4s linear infinite; 18 | -moz-animation: text 4s linear; 19 | animation: text 4s linear infinite; 20 | } 21 | 22 | @-webkit-keyframes slide 23 | { 24 | 0% {background-color: #aee7d9;} 25 | 40% {background-color: #b0e8f6;} 26 | 60% {background-color: #c7d3ff;} 27 | 90% {background-color: #b0e8f6;} 28 | 100% {background-color: #aee7d9;} 29 | } 30 | 31 | @-moz-keyframes slide 32 | { 33 | 0% {background-color: #aee7d9;} 34 | 40% {background-color: #b0e8f6;} 35 | 60% {background-color: #c7d3ff;} 36 | 90% {background-color: #b0e8f6;} 37 | 100% {background-color: #aee7d9;} 38 | } 39 | 40 | @keyframes slide 41 | { 42 | 0% {background-color: #aee7d9;} 43 | 40% {background-color: #b0e8f6;} 44 | 60% {background-color: #c7d3ff;} 45 | 90% {background-color: #b0e8f6;} 46 | 100% {background-color: #aee7d9;} 47 | } 48 | 49 | @-webkit-keyframes text 50 | { 51 | 0% {color: #5dc6ac;} 52 | 40% {color: #25b1d4;} 53 | 60% {color: #8b9fe8;} 54 | 90% {color: #25b1d4;} 55 | 100% {color: #5dc6ac;} 56 | } 57 | 58 | @-moz-keyframes text 59 | { 60 | 0% {color: #5dc6ac;} 61 | 40% {color: #25b1d4;} 62 | 60% {color: #8b9fe8;} 63 | 90% {color: #25b1d4;} 64 | 100% {color: #5dc6ac;} 65 | } 66 | 67 | @keyframes text 68 | { 69 | 0% {color: #5dc6ac;} 70 | 40% {color: #25b1d4;} 71 | 60% {color: #8b9fe8;} 72 | 90% {color: #25b1d4;} 73 | 100% {color: #5dc6ac;} 74 | } 75 | -------------------------------------------------------------------------------- /ansible/site/images/ansible.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hector-vido/nicbr-ansible/9d48575723aa4b615eb4ca6dd5eb1096b1d3aaec/ansible/site/images/ansible.png -------------------------------------------------------------------------------- /ansible/site/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hector-vido/nicbr-ansible/9d48575723aa4b615eb4ca6dd5eb1096b1d3aaec/ansible/site/images/favicon.png -------------------------------------------------------------------------------- /ansible/site/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |