ansible-doc é um comando que exibe uma documentação sobre componentes do Ansible.
$ sudo ansible-doc -l
A flag -l lista todos os módulos que podemos utilizar no Ansible.
Para mostrar somente a descrição do módulo user, use o seguinte comando:
$ sudo ansible-doc user | grep EXAMPLES -A 15 EXAMPLES: - name: Add the user 'johnd' with a specific uid and a primary group of 'admin' ansible.builtin.user: name: johnd comment: John Doe uid: 1040 group: admin - name: Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups ansible.builtin.user: name: james shell: /bin/bash groups: admins,developers append: yes
hosts: Define em qual máquina o Playbook será aplicado, a partir do inventário.
Task: Uma Task no Ansible é uma coleção de comandos que serão executados em uma ou mais máquinas. A palavra task vem do inglês “tarefa”. Cada Task do Ansible consiste em uma sequência de comandos que serão executados em uma máquina.
Handlers: Um Handler tem a mesma função de uma Task (tarefa) dentro de um PlayBook. Um Handle será executado quando chamado por outra tarefa. Você pode pensar nisso como parte de um sistema de eventos, o Handler vai tomar uma ação quando chamado por um evento que escuta.
Isso é útil para as ações “secundárias” que possam ser necessárias depois de executar uma tarefa, como iniciar um novo serviço após a instalação ou recarregar um serviço depois de uma alteração de configuração.
Fatos: O Ansible pode utilizar informações do sistema chamada de fatos em seus PlayBooks. Exemplos:
Módulos: O Ansible usa módulos para realizar a maioria de suas tarefas. Os módulos podem instalar um software, copiar arquivos, adicionar usuários, entre outros. Através de módulos, o Ansible usa fatos do sistema para determinar quais ações devem ser feitas para realizar uma tarefa. Exemplos:
Variáveis: O Ansible usa variáveis para permitir mais flexibilidade na PlayBooks e Roles. Elas podem ser usadas para fazer um loop através de um conjunto de valores fornecidos, acessar várias informações como o nome do host de um sistema e substituir certas palavras em templates por valores específicos do sistema
< /dev/urandom tr -dc '!@#%*?'_A-Z-a-z-0-9 | head -c12;echo b_sTssWh60NC
$ echo 'b_sTssWh60NC' | openssl passwd -1 -stdin $1$cYdCAK1T$i4IEPWKr2VfsV84mhSKh50
--- - hosts: local tasks: - name: Create user user: name: helpdesk shell: /bin/bash password: $1$cYdCAK1T$i4IEPWKr2VfsV84mhSKh50
Checando a sintax
$ sudo ansible-playbook --syntax-check user-add.yaml playbook: user-add.yaml
Aplicando a playbook
$ sudo ansible-playbook user-add.yaml PLAY [local] **************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ****************************************************************************************************************************************************************************************** ok: [ansible-server] TASK [Create user] ********************************************************************************************************************************************************************************************** ok: [ansible-server] PLAY RECAP ****************************************************************************************************************************************************************************************************** ansible-server : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Multiplos usuários
--- - name: Create new users hosts: local tasks: - name: Create users user: name: "{{ item }}" password: $1$cYdCAK1T$i4IEPWKr2VfsV84mhSKh50 shell: /bin/bash loop: - alice - bob
$ sudo ansible-playbook --syntax-check multi-user-add.yaml playbook: multi-user-add.yaml
$ sudo ansible-playbook multi-user-add.yaml PLAY [Create new users] ***************************************************************************************************************************************************************************************** TASK [Gathering Facts] ****************************************************************************************************************************************************************************************** ok: [ansible-server] TASK [Create users] ********************************************************************************************************************************************************************************************* ok: [ansible-server] => (item=alice) ok: [ansible-server] => (item=bob) PLAY RECAP ****************************************************************************************************************************************************************************************************** ansible-server : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
$ sudo ansible local -m shell -a "getent passwd | tail -n3" ansible-server | CHANGED | rc=0 >> helpdesk:x:1002:1002::/home/helpdesk:/bin/bash alice:x:1003:1003::/home/alice:/bin/bash bob:x:1004:1004::/home/bob:/bin/bash
--- - name: Remove the users hosts: local tasks: - name: Remove users ansible.builtin.user: name: "{{ item }}" state: absent remove: yes loop: - alice - bob
$ sudo ansible-playbook --syntax-check user-del.yaml playbook: user-del.yaml
$ sudo ansible-playbook user-del.yaml PLAY [Remove the users] ***************************************************************************************************************************************************************************************** TASK [Gathering Facts] ****************************************************************************************************************************************************************************************** ok: [ansible-server] TASK [Remove users] ********************************************************************************************************************************************************************************************* changed: [ansible-server] => (item=alice) changed: [ansible-server] => (item=bob) PLAY RECAP ****************************************************************************************************************************************************************************************************** ansible-server : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
--- - hosts: local tasks: - name: Garantir permissão de superusuário para o usuário helpdesk lineinfile: path: /etc/sudoers state: present insertafter: "root ALL=(ALL:ALL) ALL" line: "helpdesk ALL=(ALL) NOPASSWD: ALL"
Ou:
--- - hosts: local tasks: - name: Add user to sudo ansible.builtin.lineinfile: path: /etc/sudoers.d/helpdesk line: 'helpdesk ALL=(ALL) NOPASSWD: ALL' mode: 0440 create: yes validate: /usr/sbin/visudo -cf %s
$ sudo ansible-playbook --syntax-check lineinfile.yml playbook: lineinfile.yml
$ sudo ansible-playbook lineinfile.yml PLAY [local] *********************************************************************************************************************************************************************************************** TASK [Gathering Facts] ************************************************************************************************************************************************************************************* ok: [ansible-server] TASK [Garantir permissão de superusuário para o usuário helpdesk] ****************************************************************************************************************************************** changed: [ansible-server] PLAY RECAP ************************************************************************************************************************************************************************************************* ansible-server : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
$ sudo -i -u helpdesk sudo tail -n1 /etc/sudoers helpdesk ALL=(ALL) NOPASSWD: ALL
--- - hosts: local vars: varsUsers: - alice - bob varsGroups: linuxadm tasks: - name: Add goup to Linux ansible.builtin.group: name: "{{ varsGroups }}" state: present - name: Add group sudo ansible.builtin.lineinfile: path: /etc/sudoers insertafter: "root ALL=(ALL:ALL) ALL" line: "%linuxadm ALL=(ALL) NOPASSWD: ALL" validate: /usr/sbin/visudo -cf %s - name: Add users to linuxadm group ansible.builtin.user: name: "{{ item }}" groups: linuxadm append: yes with_items: "{{ varsUsers }}"
$ sudo ansible-playbook --syntax-check group-add-sudo.yaml playbook: group-add-sudo.yaml
$ sudo ansible-playbook group-add-sudo.yaml PLAY [local] **************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ****************************************************************************************************************************************************************************************** ok: [ansible-server] TASK [Add goup to Linux] **************************************************************************************************************************************************************************************** changed: [ansible-server] TASK [Add group sudo] ******************************************************************************************************************************************************************************************* changed: [ansible-server] TASK [Add users to linuxadm group] ****************************************************************************************************************************************************************************** changed: [ansible-server] => (item=alice) changed: [ansible-server] => (item=bob) PLAY RECAP ****************************************************************************************************************************************************************************************************** ansible-server : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
--- - hosts: local tasks: - name: Instala pacote ntpdate apt: name=ntpdate state=present update_cache=true
$ sudo ansible-playbook --syntax-check install-ntpdate.yml playbook: install-ntpdate.yml
$ sudo ansible-playbook install-ntpdate.yml PLAY [local] *********************************************************************************************************************************************************************************************** TASK [Gathering Facts] ************************************************************************************************************************************************************************************* ok: [ansible-server] TASK [Instala pacote ntpdate] ****************************************************************************************************************************************************************************** changed: [ansible-server] PLAY RECAP ************************************************************************************************************************************************************************************************* ansible-server : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0