Eduardo Klosowski
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Introdução ao Ansible tags: Apresentação descricption: Apresentação inicial sobre o Ansible --- # Introdução ao Ansible ![Logo do Ansible](https://i.imgur.com/3vL5Zk9.png =200x) https://www.ansible.com/ ---- ## Eduardo Klosowski ![Imagem](https://avatars.githubusercontent.com/u/4060984?v=4 =200x) - 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)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully