Assignments
25 graded exercises: 10 ๐ข Beginner, 10 ๐ก Intermediate, 5 ๐ด Advanced. Each has an objective, tasks, acceptance criteria, collapsible hints and a bonus.
How to use these
You need ansible-core 2.18+ and two or three target machines. Cheap options: local VMs, Multipass or Vagrant boxes, Docker containers with SSH, or t3.micro EC2 instances. Keep every assignment in its own Git folder and commit when the acceptance criteria pass. Always use fully qualified module names (ansible.builtin.copy, not copy).
๐ข Beginner
Assignment 1. Install Ansible and reach a host ๐ข
Objective: Get a working control node and prove connectivity.
Tasks
- Create a Python virtualenv and install
ansible-core. - Prepare one Linux target with SSH key login.
- Create an inventory file
hosts.iniwith that target. - Run
ansible all -m ansible.builtin.ping. - Run
ansible all -m ansible.builtin.setup -a 'filter=ansible_distribution*'.
Expected outcome / acceptance criteria
pingreturnspongandchanged: false.- You can name the distribution and version from the facts output.
ansible --versionshows a config file path orNone, and you can explain why.
Hints
Set remote_user and private_key_file in ansible.cfg or in the inventory (ansible_user, ansible_ssh_private_key_file). ansible all -m ping -vvv shows the exact SSH command. If you get Permission denied (publickey), test with plain ssh -i key user@host first.
Bonus: Make ping work through a bastion with ansible_ssh_common_args='-o ProxyJump=bastion'.
Assignment 2. Build an inventory with groups ๐ข
Objective: Understand groups, children groups and inventory inspection.
Tasks
- Create an INI inventory with groups
web,dband a parent groupprod:childrencontaining both. - Add a host alias with
ansible_host=pointing to a real IP. - Convert the same inventory to YAML format.
- Run
ansible-inventory --graphandansible-inventory --liston both versions. - Target groups with
ansible web -m pingandansible 'prod:!db' -m ping.
Expected outcome / acceptance criteria
- The INI and YAML inventories produce identical
--listJSON (compare withdiff). - Patterns
web,prod,prod:!dbandweb:&prodeach select the hosts you predicted.
Hints
In INI, [prod:children] lists group names. In YAML, use children: under the group. The pattern operators are : (union), :! (exclude) and :& (intersection). --list output is easier to diff after piping through jq -S ..
Bonus: Add a numeric range host pattern such as web[01:03].example.com and verify it expands.
Assignment 3. Ad-hoc commands for daily tasks ๐ข
Objective: Use modules from the command line instead of SSH-ing in.
Tasks
- Check uptime on all hosts with
ansible.builtin.command. - Install
htopwithansible.builtin.apt(use--become). - Copy a local file to
/tmp/hello.txtwithansible.builtin.copy. - Restart
cronusingansible.builtin.service. - Run the same install command twice and compare output.
Expected outcome / acceptance criteria
- First install shows
CHANGED, the second showsSUCCESSwithchanged: false. - You can explain why
-m command -a 'apt install htop'is a worse choice than-m apt.
Hints
ansible web -b -m ansible.builtin.apt -a "name=htop state=present update_cache=yes". The -b flag enables privilege escalation. Add -o for one-line output.
Bonus: Use -m ansible.builtin.fetch to pull /etc/os-release from every host into per-host folders.
Assignment 4. Your first playbook ๐ข
Objective: Describe a desired state in YAML.
Tasks
- Write
web.ymltargeting groupwebwithbecome: true. - Install
nginx, ensure it is started and enabled. - Deploy a custom
index.htmlwithansible.builtin.copyand itscontent:parameter. - Run with
--syntax-check, then run it for real. - Fetch the page with
curlfrom your workstation.
Expected outcome / acceptance criteria
- The page shows your custom text.
PLAY RECAPshowsfailed=0.- On a second run
changed=0.
Hints
Playbooks are a list of plays, each with name, hosts, tasks. Use ansible.builtin.service with state: started and enabled: true. If curl cannot connect, check the cloud security group or ufw status on the host.
Bonus: Add a ansible.builtin.uri task that asserts the page returns 200 and contains your text.
Assignment 5. Idempotency, check mode and diff ๐ข
Objective: Learn to see changes before making them.
Tasks
- Take your playbook from assignment 4.
- Run with
--check --diffafter editing the HTML content. - Add a task using
ansible.builtin.shell: echo hi >> /tmp/log.txtand observe that it reportschangedon every run. - Fix it with
creates:, or rewrite it withansible.builtin.lineinfile. - Add a
commandtask that only reads data and mark itchanged_when: false.
Expected outcome / acceptance criteria
--check --diffshows a unified diff and changes nothing on the host.- Two consecutive real runs end with
changed=0. - You can state why
shellandcommandare not idempotent by default.
Hints
--diff works with copy, template, lineinfile, blockinfile. command and shell are skipped in check mode unless you set check_mode: false on the task, which is what you want for read-only commands.
Bonus: Explain the output of a task marked check_mode: false when the whole play runs with --check.
Assignment 6. Variables and precedence ๐ข
Objective: Predict which variable value wins.
Tasks
- Define
http_port: 80in role-less playvars:. - Override it in
group_vars/web.ymlas8080and inhost_vars/<host>.ymlas9090. - Print the value on each host with
ansible.builtin.debug. - Run again with
-e http_port=7000. - Move the play-level definition to
vars_files:and observe the new winner.
Expected outcome / acceptance criteria
- You can write the order you observed, from weakest to strongest, and it matches the docs.
- A one-paragraph note exists explaining why you should avoid defining the same variable in many places.
Hints
ansible-inventory --host <name> --vars shows inventory-sourced values only. Play vars beat inventory vars, and -e beats all. Role defaults/ are the weakest, which is why they are the right place for overridable settings.
Bonus: Use ansible.builtin.set_fact and show that it outranks play vars, then explain the risk.
Assignment 7. Loops and conditionals ๐ข
Objective: Avoid copy-pasted tasks.
Tasks
- Create three users from a list of dicts (
name,shell,groups) with one task andloop. - Install a package list in a single
apttask by passing a list toname. - Install
httpdon RedHat family andapache2on Debian family usingwhen: ansible_facts['os_family'] == .... - Print each user's name with
loop_control: label: "{{ item.name }}".
Expected outcome / acceptance criteria
- Output shows labels instead of full dictionaries.
- On a Debian host the RedHat task shows
skipping. - Re-running produces no changes.
Hints
Facts are available as ansible_facts['os_family'] (and the legacy ansible_os_family). Use ansible.builtin.user with groups: and append: true so you do not strip existing groups. Passing a list to name: is much faster than looping the package module.
Bonus: Use with_items-free syntax only, and loop: "{{ users | selectattr('enabled') | list }}" to filter the list.
Assignment 8. Handlers ๐ข
Objective: Restart services only when configuration changes.
Tasks
- Template or copy an nginx config file and
notify: Reload nginx. - Define the handler with
ansible.builtin.service: state=reloaded. - Run twice and confirm the handler fires only the first time.
- Make two tasks notify the same handler and confirm it runs once.
- Add
ansible.builtin.meta: flush_handlersbefore a health check.
Expected outcome / acceptance criteria
- Handler output appears only after a real change.
- Break a later task on purpose and observe that the pending handler does not run.
- Fix it with
force_handlers: trueon the play and show the difference.
Hints
Handlers run at the end of each play (or on flush_handlers) and de-duplicate by name. Names are matched exactly; notifying a handler that does not exist fails the play with an error, so read it carefully. Use listen: to group multiple handlers under one topic.
Bonus: Replace the notify chain with listen: "restart web stack" so two handlers run together.
Assignment 9. First Jinja2 template ๐ข
Objective: Generate files from variables and facts.
Tasks
- Write
motd.j2that prints hostname, OS, IP address, memory in MB and the Ansible-managed warning. - Deploy to
/etc/motdwithansible.builtin.template, mode0644. - Add a
{% for %}loop over a list of admin contacts. - Use
default()for an optional variable. - Log into the host and read the result.
Expected outcome / acceptance criteria
- Output contains real fact values, not Jinja syntax.
- Missing optional variable falls back to the default without error.
- A second run reports
ok.
Hints
Facts: ansible_facts['hostname'], ansible_facts['distribution'], ansible_facts['default_ipv4']['address'], ansible_facts['memtotal_mb']. Do not put timestamps in templates, or every run becomes changed. Use {{ ansible_managed }} only if you set it deliberately; otherwise write your own header comment.
Bonus: Add trim_blocks-friendly loops so the rendered output has no blank-line gaps.
Assignment 10. Facts, register, tags and limits ๐ข
Objective: Control what runs and use task results.
Tasks
- Run a command with
register: resultand printresult.stdout_lines. - Tag tasks with
packages,configandservice. - Run only
--tags config, then--skip-tags service. - Use
--limitto run on one host, and--list-tasksand--list-hoststo preview. - Set
gather_facts: falseon a play that does not need facts and compare run time.
Expected outcome / acceptance criteria
- Tag selection runs the expected subset (
--list-tasks --tags configproves it). - Timing of the no-facts play is measurably shorter (use
time).
Hints
register captures rc, stdout, stderr, changed, failed. Tags can be applied at task, block, role or play level. Tag always runs unless explicitly skipped, and never runs only when requested.
Bonus: Enable the profile_tasks callback (ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks) to see task timings.
๐ก Intermediate
Assignment 11. Refactor a playbook into a role ๐ก
Objective: Make automation reusable.
Tasks
- Scaffold a role with
ansible-galaxy role init nginx. - Move tasks, handlers, templates and variables into the proper directories.
- Put tunables in
defaults/main.yml, constants invars/main.yml. - Add
meta/main.ymlwith supported platforms and a dependency on acommonrole. - Call the role from a short
site.yml.
Expected outcome / acceptance criteria
site.ymlhas fewer than 15 lines.- Overriding a default from
group_varsworks with no role edits. ansible-lintpasses with no errors.
Hints
Role variables in vars/ have high precedence and are hard to override; use defaults/ for anything a user might change. Prefix every role variable with the role name (nginx_port) to avoid collisions. Dependencies in meta run before the role.
Bonus: Add an argument_specs.yml under meta/ so wrong variable types fail fast with a clear message.
Assignment 12. Secrets with Ansible Vault ๐ก
Objective: Keep secrets encrypted in Git.
Tasks
- Create
group_vars/prod/vault.ymlwithansible-vault create, holdingvault_db_password. - Reference it from
group_vars/prod/vars.ymlasdb_password. - Encrypt a single value with
ansible-vault encrypt_string --name api_token. - Use
--vault-id dev@promptand--vault-id [email protected]_prodwith separate passwords. - Template a config that uses the secret with
no_log: true. - Rotate the password with
ansible-vault rekey.
Expected outcome / acceptance criteria
git grepfinds no plaintext secret anywhere, and.vault_pass*is in.gitignore.- The playbook runs unattended using the password file.
- Output never prints the secret, even with
-v.
Hints
With no_log: true on a task, nothing is printed even on failure, which hurts debugging; enable it only on tasks that handle secrets. ansible-vault view and edit avoid leaving plaintext on disk. Rekey needs the old password; every file encrypted with it must be rekeyed.
Bonus: Write a pre-commit hook that blocks commits where a file named vault.yml lacks the $ANSIBLE_VAULT header.
Assignment 13. Error handling: block, rescue, always ๐ก
Objective: Make failures predictable.
Tasks
- Write a block that deploys a config, validates it, and in
rescuerestores the backup. - Add an
alwayssection that records the result in/var/log/deploy.log. - Use
failed_whento treat a specific command output as failure even whenrc == 0. - Use
ignore_errorsonce and replace it withfailed_whenorrescue. - Use
any_errors_fatal: trueon a play and show its effect across hosts.
Expected outcome / acceptance criteria
- A deliberately broken config leads to rollback, and the play recap shows
rescued=1. - The
alwaystask runs on both success and failure. - You can explain why
ignore_errorshides real problems.
Hints
Within rescue, the variables ansible_failed_task and ansible_failed_result describe the failure. A play with rescued tasks still ends failed=0. block can carry become, when, tags to avoid repetition.
Bonus: Add retries, delay and until to a flaky uri task and show the retry output.
Assignment 14. Collections, requirements and ansible.cfg ๐ก
Objective: Make a project reproducible.
Tasks
- Create
requirements.ymlpinningcommunity.general,ansible.posixandamazon.awsversions. - Install them into
./collectionsusingansible-galaxy collection install -r requirements.yml -p collections. - Set
collections_pathinansible.cfg. - Use a module from each collection (
community.general.ufw,ansible.posix.sysctl). - Run
ansible-config dump --only-changed.
Expected outcome / acceptance criteria
- A fresh clone plus one install command is enough to run the playbooks.
ansible-galaxy collection listshows exact versions matching the pins.
Hints
Use version: "==x.y.z" for strict pins or ">=x,<y" for ranges. Commit requirements.yml, not the downloaded collections/ folder. ansible-doc community.general.ufw shows module docs offline.
Bonus: Add a role requirement from Galaxy using the roles: key in the same file.
Assignment 15. Dynamic inventory on AWS ๐ก
Objective: Stop maintaining host lists by hand.
Tasks
- Launch three EC2 instances tagged
EnvandRole. - Write
aws_ec2.ymlforamazon.aws.aws_ec2withregions,filters,keyed_groups,hostnames,compose. - Run
ansible-inventory -i aws_ec2.yml --graph. - Create a group via
groups:with a Jinja condition (for example instances of typet3.micro). - Enable inventory caching with
cache: trueandcache_plugin: jsonfile.
Expected outcome / acceptance criteria
- Groups such as
role_webandenv_prodappear from tags alone. - Terminating one instance and re-running removes it with no file edits.
- Cache hits are visible in timing and in the cache directory.
Hints
The file name must end with aws_ec2.yml. Install boto3 and botocore. Credentials come from the standard AWS chain (env vars, profile, instance role). Use compose: ansible_host: public_ip_address for public access or private_ip_address from inside the VPC. Use ansible-inventory --host <name> to list available hostvars such as tags, instance_type.
Bonus: Use SSM Session Manager as the connection (ansible_connection: community.aws.aws_ssm) so no inbound port 22 is needed.
Assignment 16. Config files from inventory data with Jinja2 ๐ก
Objective: Generate a load balancer config from the live host list.
Tasks
- Write
haproxy.cfg.j2that loops overgroups['web']to createserverlines. - Use
hostvars[host]['ansible_host']for addresses and weights from a host variable with a default. - Add a conditional section only when
haproxy_enable_statsis true. - Validate with
validate: haproxy -c -f %s. - Add and remove a web host and confirm the template output changes.
Expected outcome / acceptance criteria
- The rendered file lists exactly the hosts in the group, ordered.
- Invalid config is never installed.
- A
diffrun shows only the added or removed server line.
Hints
{% for h in groups['web'] | sort %}. If the target group hosts were not contacted in this play, their facts are missing; use inventory variables or run a prior play with gather_facts. Use {{- -}} or trim_blocks for whitespace control.
Bonus: Write the template so it can also render an nginx upstream block using the same data via a variable switch.
Assignment 17. Safe file edits: lineinfile, blockinfile, replace ๐ก
Objective: Edit files you do not own, without breaking them.
Tasks
- Harden
/etc/ssh/sshd_configwithlineinfileandvalidate: sshd -t -f %s. - Add a managed block to
/etc/hostswithblockinfileand a custom marker. - Use
replaceto change a value across a file with a regex andbefore:/after:. - Use
backup: trueand find the backup file. - Prove each task is idempotent.
Expected outcome / acceptance criteria
- Runs 2 and 3 show
changed=0. - An invalid sshd value is rejected and the live file is untouched.
- You can justify when a
templateis the better tool.
Hints
lineinfile needs a regexp that matches both the commented and the active form ('^#?\s*PermitRootLogin'), otherwise it appends a new line on every run because the pattern never matches the existing one. In blockinfile, the marker must be unique per block, so use {mark} placeholders with distinct text. Keep a second SSH session open when changing sshd.
Bonus: Convert the sshd changes into a full template with a validated drop-in under /etc/ssh/sshd_config.d/.
Assignment 18. Users, groups and SSH keys at scale ๐ก
Objective: Manage access as data.
Tasks
- Define a
team_userslist ingroup_varswith name, groups, state and public keys. - Create users with
ansible.builtin.userand install keys withansible.posix.authorized_keyandexclusive: true. - Add a sudoers drop-in with
ansible.builtin.copyandvalidate: visudo -cf %s. - Remove a user by setting
state: absentandremove: true. - Lock the password for all service accounts.
Expected outcome / acceptance criteria
- Adding a key to the YAML list gives access on the next run; removing it revokes access.
- A malformed sudoers file never lands in
/etc/sudoers.d.
Hints
exclusive: true removes keys not listed, so be careful not to remove your own automation key. Sudoers drop-ins must be mode 0440. File names in /etc/sudoers.d must not contain dots or end with ~.
Bonus: Use a with_fileglob or lookup('file', ...) to load keys from a keys/ folder in the repo.
Assignment 19. Containers with Ansible ๐ก
Objective: Use Ansible to bootstrap Docker and run a workload.
Tasks
- Install the Docker apt repository and
docker-cepackages using modern keyring handling (ansible.builtin.get_urlfor the key into/etc/apt/keyrings, plusansible.builtin.apt_repositorywith asigned-byoption). - Add your user to the
dockergroup. - Pull and run
nginxusingcommunity.docker.docker_container. - Publish port 8080 and mount a templated config volume.
- Update the config and recreate the container only when it changes.
Expected outcome / acceptance criteria
docker psshows the container with the expected port mapping.- Second run:
changed=0. - Changing the template triggers one restart through a handler.
Hints
Install the Python docker library on the target (or use ansible_python_interpreter that has it). community.docker.docker_container is idempotent on image and parameters; restart: true or a handler forces a restart. Group membership takes effect only on a new login session.
Bonus: Replace the container with a community.docker.docker_compose_v2 project.
Assignment 20. Write a custom filter plugin and use lookups ๐ก
Objective: Extend Jinja2 and reach outside the inventory.
Tasks
- Create
filter_plugins/netutils.pywith a filterto_cidr_hoststhat returns the host count for a prefix. - Use it inside a template and a debug task.
- Use
lookup('env', 'HOME'),lookup('file', ...)andlookup('ansible.builtin.password', '/tmp/pw length=20'). - Show that lookups run on the controller, not on the managed host.
Expected outcome / acceptance criteria
{{ 24 | to_cidr_hosts }}renders 254.- The password lookup returns the same value on the second run (it caches in the file).
Hints
A filter plugin is a class FilterModule with a filters() method returning a dict of name to callable. Put the file next to the playbook in filter_plugins/, or in a role. Lookups always execute on the control node; use slurp or fetch to read remote files.
Bonus: Add a unit test with pytest for the filter.
๐ด Advanced
Assignment 21. Zero-downtime rolling deploy with rollback ๐ด
Objective: Release safely across a fleet.
Tasks
- Use three web servers behind a load balancer (nginx or an ALB).
- Write a play with
serial: 1(then[1, "30%", "100%"]) andmax_fail_percentage: 0. - Drain the host (flag file, LB API via
delegate_to, or target group deregistration), deploy a new version from Git, restart the service. - Gate on an
ansible.builtin.urihealth check withretriesanduntil. - Add
block/rescuethat rolls back to the previous commit on failure and then fails the play. - Deploy a deliberately broken release and show that two hosts stay on the old version.
Expected outcome / acceptance criteria
- A continuous
curlloop against the LB never gets a 5xx during a good release. - The bad release stops after the first batch and the failed host is rolled back and re-added.
- The recap shows
rescued=1on one host and nothing for the others.
Hints
serial accepts an integer, a percentage or a list for canary-then-ramp. max_fail_percentage: 0 aborts as soon as any host in a batch fails. For an ALB, use delegate_to: localhost with amazon.aws or community.aws target group modules and wait for draining to finish. Save the previous commit before changing anything, or you have nothing to roll back to.
Bonus: Add run_once: true smoke tests after the last batch and a throttle: 1 database migration step.
Assignment 22. Test a role with Molecule ๐ด
Objective: Prove a role is correct, idempotent and portable.
Tasks
- Initialise a Molecule scenario with the Docker driver in your nginx role.
- Test on two platforms (Ubuntu 24.04 and Rocky 9 or Debian 12).
- Write
verify.ymlassertions: package present, service running, config content, HTTP 200, port listening. - Make the idempotence step fail on purpose with a bad
commandtask, then fix it. - Add a second scenario that tests non-default variables.
- Run in CI on pull requests.
Expected outcome / acceptance criteria
molecule testpasses on both platforms, and the logs show anidempotencestep with zero changes.- The failing task from step 4 breaks CI with a clear message.
- A matrix job runs both scenarios.
Hints
Use images built for systemd-in-Docker (for example the geerlingguy/docker-*-ansible family) with privileged: true, cgroupns_mode: host, and the cgroup volume mounted. Use molecule converge and molecule login while iterating, since a full test run recreates the container. The default verifier is Ansible itself; testinfra is an alternative with pytest.
Bonus: Add ansible-lint and yamllint as a pre-step and make the lint failure block the job.
Assignment 23. Make a slow playbook fast ๐ด
Objective: Measure first, then tune.
Tasks
- Run a playbook on 20+ hosts (or 20 containers) and capture a baseline with
profile_tasksandtime. - Enable SSH pipelining and
ControlPersistand re-measure. - Raise
forks, setgather_facts: falseorgather_subset: [min], and enable fact caching withjsonfileor Redis. - Replace per-item package loops with list arguments.
- Compare
strategy: linearvsstrategy: freeand explain a case wherefreeis unsafe. - Write a table of each change and its measured gain.
Expected outcome / acceptance criteria
- At least a 2x improvement on the same workload, backed by timing data.
- A clear note on the trade-off of each change (for example pipelining versus
requiretty).
Hints
ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks,ansible.posix.timer. Pipelining lives under [ssh_connection] pipelining = True. A very high forks value can overload the controller or the SSH bastion. Look at ANSIBLE_KEEP_REMOTE_FILES=1 when debugging, never in normal runs.
Bonus: Try async plus poll: 0 and async_status for parallel long-running tasks on a single host.
Assignment 24. Write a custom module with check mode ๐ด
Objective: Understand what a module really is.
Tasks
- Write
library/app_flag.pythat creates or removes a flag file and returnschangedaccurately. - Use
AnsibleModulewithargument_spec,supports_check_mode=Trueandrequired_if. - Return structured results (
path,state,previous). - Add
DOCUMENTATION,EXAMPLES,RETURNblocks soansible-doc app_flagworks. - Test with
ansible localhost -m app_flagand in a playbook with--check --diff. - Write a pytest unit test using
AnsibleModulepatching, or a Molecule verify.
Expected outcome / acceptance criteria
- Running twice shows
changedonce, thenok. - In check mode the file is not touched, but
changedcorrectly predicts the result. ansible-docrenders your docs.
Hints
Use module.exit_json(changed=..., **result) and module.fail_json(msg=...). In check mode, compute the change but return before performing it. Keep modules idempotent by comparing current and desired state before acting. Place the file in library/ next to the playbook or in a collection's plugins/modules/.
Bonus: Package it in a collection with galaxy.yml and build it with ansible-galaxy collection build.
Assignment 25. Full delivery pipeline for configuration code ๐ด
Objective: Treat Ansible like software.
Tasks
- Create a pipeline (GitHub Actions or GitLab CI) with stages: lint (
ansible-lint --profile production,yamllint), Molecule test matrix,--syntax-check, and a--check --diffrun against staging. - Store the vault password and SSH key in the CI secret store; load the key through an SSH agent step and delete the vault file after use.
- Apply to staging automatically on merge, and to production only after a manual approval with
serialrolling. - Add a nightly scheduled job that runs production with
--check --diffand fails whenchanged > 0(drift report). - Build an execution environment image with
ansible-buildercontaining pinned collections and Python deps, and run the playbook in it usingansible-navigatoror in the CI container.
Expected outcome / acceptance criteria
- A pull request with a lint error or failing Molecule test cannot merge.
- Manual SSH edits on a staging host are reported by the nightly drift job.
- No secret appears in job logs (
no_logand masked variables), and the pipeline file contains no credentials.
Hints
Parse the recap in the drift job (grep -E 'changed=[1-9]'), or use the JSON callback with ANSIBLE_STDOUT_CALLBACK=json and jq. Use environment-protected secrets for production only. Pin the EE base image and the collections to avoid surprise breakage. Prefer short-lived cloud credentials via OIDC rather than static keys.
Bonus: Add ansible-pull on one host as a comparison, and write down when pull beats push (large fleets, firewalled nodes, autoscaling at boot).