Ansible — Basics
Ansible — Basics
Section titled “Ansible — Basics”What it is
Section titled “What it is”Agentless config management + provisioning over SSH (or WinRM). YAML “playbooks” describe desired state. Idempotent modules.
Strengths: no agent, simple YAML, large module ecosystem. Weakness: scale to thousands of hosts is slow vs pull-based agents.
Use cases:
- Server config (packages, files, users, services).
- App deploys (especially pre-K8s).
- One-off ops (rolling restart, upgrades).
- Network device automation.
Concepts
Section titled “Concepts”- Inventory — list of hosts, grouped. Static (
hosts.ini) or dynamic. - Module — discrete idempotent action (
apt,copy,service,template). - Task — invocation of a module.
- Play — set of tasks against a host group.
- Playbook — YAML file with one or more plays.
- Role — reusable bundle.
- Handler — task triggered by
notify, runs once at end. - Vault — encrypted secrets file.
Inventory
Section titled “Inventory”[web]web1.example.comweb2.example.com
[db]db1.example.com ansible_user=ubuntu
[prod:children]webdbPlaybook
Section titled “Playbook”- name: configure web servers hosts: web become: true vars: { nginx_version: 1.24.0 } tasks: - name: install nginx apt: { name: "nginx={{ nginx_version }}*", state: present, update_cache: true } - name: deploy site config template: { src: site.conf.j2, dest: /etc/nginx/sites-available/default } notify: reload nginx - name: ensure nginx running service: { name: nginx, state: started, enabled: true } handlers: - name: reload nginx service: { name: nginx, state: reloaded }Common modules
Section titled “Common modules”apt/yum/package, copy, template, file, lineinfile, service/systemd, user/group, git, command/shell (last resort), cron, firewalld/ufw, docker_container, k8s, aws_*/gcp_*.
Variables — precedence (last wins)
Section titled “Variables — precedence (last wins)”role defaults → inventory vars → group vars → host vars → play vars → task vars → --extra-vars.
ansible-vault create secrets.ymlansible-vault encrypt_string 'mypass' --name db_passwordansible-playbook play.yml --ask-vault-passCommon patterns
Section titled “Common patterns”--check --diff— dry run.tags— subset.serial: 5— rolling updates.delegate_to— run on different host.run_once— only first host.block/rescue/always— try/except.
When NOT to use
Section titled “When NOT to use”- Containerized workloads → K8s + GitOps.
- Frequent app deploys → CI/CD + orchestrator.
- Stateless cattle infra → cloud-init / immutable images.
- Configurable secrets at scale → use Vault/SecretsManager + agent.
Ansible shines for “make N existing servers look like this”.