--- title: Ansible 101 description: A small overview and best practice guide for ansible author: Ricardo Band keywords: automation,basics --- # Ansible 101 ## A small overview and best practice guide for ansible --- # Python - 🐍 use python 3.6+ - newer = better ✨ - Dedicated virtualenv - 📦 container ```dockerfile FROM python:3-slim ADD . RUN pip install -r requirements.txt ENTRYPOINT ["ansible-playbook"] CMD ["--help"] ``` - `podman run -it --rm ansible my-playbook.yml` --- # Ansible - `ansible` package is only the CLI - `ansible-core` is the actual library - only versions 2.19 and later are semantic - CLI versions increase quite fast currently at version 6 - Red Hat Ansible Automation Platform 2.2 (tm) --- # ansible.cfg - Define inventory path - Could be sourced by a plugin from a DCIM - Define roles path - Can be ommitted if all roles are externally sourced - Switch output plugin `stdout_callback = yaml` - Always use root - Easier then writing `become: yes` everywhere - 90% of tasks require root anyway - SSH options - Faster ssh by reusing connections ```ini [ssh_connection] pipelining = True ssh_args = -o ControlMaster=auto -o ControlPersist=600 ``` --- # requirements.txt _Python dependencies_ - Ansible dependencies - `ansible~=6.0` - Libraries needed by ansible modules or plugins - Role dependencies - Libraries needed by roles - Collection dependencies - Libraries needed by collections --- # requirements.yml _Ansible dependencies_ - Roles - Collections - Get dependencies from Ansible docs, example: [podman](https://docs.ansible.com/ansible/latest/collections/containers/podman/podman_container_module.html) --- # Variables - `group_vars` - `host_vars` - "Task vars" - Role vars - Role defaults --- # Playbooks - Simple playbook - Playbook with roles --- # Roles ``` roles/./ ├── defaults │ └── main.yml ├── files │ └── etc │ └── foo │ └── config.ini ├── meta │ ├── argument_specs.yml │ └── main.yml ├── tasks │ └── main.yml ├── templates │ └── etc │ └── foo │ └── conf.d │ └── special.ini.j2 └── vars └── main.yml ``` --- # Roles - `meta` - `defaults` vs `vars` - `files` vs `templates` - Advanced tasks --- # Advances topics - 🔐 Secrets - Create your own roles - Create your own collections - If you need your own plugins or modules --- # Secrets `$ ansible-galaxy collection install community.general` ```yaml password: "{{ lookup('community.general.passwordstore', 'accounts/foobar.com') }}" aws_secret_key: "{{ lookup('community.general.passwordstore', 'accounts/aws subkey=secret_key') }}" aws_access_key: "{{ lookup('community.general.passwordstore', 'accounts/aws subkey=access_key') }}" ``` See: https://docs.ansible.com/ansible/latest/collections/community/general/passwordstore_lookup.html --- # ❓ questions ❓