Configuration Management with Ansible
When you have more than one server, or rebuild one often, configuring by hand drifts: each machine ends up slightly different. Ansible describes the desired state in YAML and makes servers match it over plain SSH, with no agent to install.
Inventory
inventory.ini:
[web]
web1 ansible_host=203.0.113.10
web2 ansible_host=203.0.113.11
[db]
db1 ansible_host=10.0.0.5
[all:vars]
ansible_user=panda
ansible all -i inventory.ini -m ping
ansible web -i inventory.ini -a "uptime"
A playbook
site.yml:
- name: Base setup for web servers
hosts: web
become: true
tasks:
- name: Install packages
ansible.builtin.apt:
name: [nginx, ufw, fail2ban, unattended-upgrades]
state: present
update_cache: true
- name: Allow web traffic
community.general.ufw:
rule: allow
port: "{{ item }}"
proto: tcp
loop: ["22", "80", "443"]
- name: Deploy nginx site
ansible.builtin.template:
src: templates/site.conf.j2
dest: /etc/nginx/sites-available/pandadev
mode: "0644"
notify: Reload nginx
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
ansible-playbook -i inventory.ini site.yml --check --diff # dry run
ansible-playbook -i inventory.ini site.yml
Every module is idempotent: state: present installs only if missing. Run the playbook ten times and the result is the same. Handlers run only when a task actually changed something, so Nginx reloads only when its config changed.
Roles
As playbooks grow, split them into roles (roles/nginx, roles/postgres, roles/app) each with tasks/, templates/, handlers/ and defaults/. Reuse community roles from Ansible Galaxy after reading their code.
Secrets with Ansible Vault
ansible-vault create group_vars/all/vault.yml
ansible-playbook site.yml --ask-vault-pass
The file is encrypted at rest, so it can live in Git safely. Keep the vault password itself out of the repository.
Exercise
Write a playbook that turns a fresh Ubuntu server into the hardened state from the Linux System Administration track: admin user, SSH hardening, firewall, fail2ban and automatic updates. Run it with --check first.
Ihr Fortschritt wird nur in diesem Browser gespeichert.
Zur Prüfung einreichen (10 Punkte)