Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
What the course covers
What Ansible is, and why teams use it for automation.
- Inventories: the list of hosts Ansible can reach.
- YAML, and the playbook structure: plays, tasks, modules, and the
ansible-playbookcommand. - Variables, loops, conditions, tags, and handlers.
- Files, templates, and Jinja2.
- Error handling with
block,rescue, andalways. - Collections, roles, and Ansible Galaxy.
- Ansible Vault for secrets, Molecule for role testing, and writing your own module in Python.
Welcome to Alta3 Research Labs!
The labs run in a Linux desktop. You work in a terminal as the student user.
- VIRGIL is the lab coach. It knows which lab you are on, and it can explain code and errors.
- The lessons show copy and paste, the command prompt, and the basic Linux commands you need.
Required Tools
Vim is the editor used in the labs. i starts insert mode, Esc stops it, :wq saves and quits.
- Tmux is a terminal multiplexer.
Ctrl-Bthen%makes a side-by-side split, andCtrl-Bthen"makes a top-and-bottom split. - You can keep a playbook in one pane and run it in the other, so you do not lose your place.
Source Code Management
The course uses GitHub or GitLab to store your work. You create a public repository named mycode.
- Git runs on your machine. GitHub and GitLab keep the copy online and show the history.
- A
.gitignorefile tells git what never to commit. For Ansible this includes vault password files and local secrets.
Ansible Overview
Ansible is an automation tool. You describe the desired state, and Ansible changes the hosts to match it.
- It connects to Linux hosts over SSH. The lab hosts are Docker containers (bender, fry, zoidberg, farnsworth) with SSH.
- The main ideas are inventory, module, task, play, and playbook. A module does one job, a task calls one module, and a playbook is a list of plays.
Ansible Basics
YAML uses indentation, - for list items, and key: value for pairs. A playbook starts with ---.
- An ad-hoc command runs one module:
ansible fry -m ping. This fails until an inventory exists, because Ansible does not know the address offry. - An INI inventory lists hosts under a group name, with
ansible_host,ansible_user, andansible_python_interpreter. A YAML inventory holds the same data with YAML syntax.
Plays and settings
- A playbook has a
name,hosts,gather_facts,connection, andtasks. Each task names a module, for exampleansible.builtin.aptwithname: figletandstate: present. ansible-playbookruns a playbook.become: yesadds sudo for a task.ansible.cfgholds defaults, so you type less. Ansible looks for it inANSIBLE_CONFIG, then the current directory, then~/.ansible.cfg, then/etc/ansible/ansible.cfg. The first file found wins.- The common settings are
inventory,host_key_checking = False, andlog_path.ansible-config dumpshows the live settings.
Loops and variables
- A loop repeats one task:
loop:takes a list, and{{ item }}is the current value. This replaces many copied tasks. - Variables can come from the play (
vars), a file (vars_files), the inventory (host vars), or the command line (-e). Extra vars win over all of them. vars_promptasks the user for a value at run time.registersaves a task result as a variable.set_factcreates a value during the run.
Critical Modules and Keywords
ansible.builtin.copy copies a file from the controller to the host. It can set owner, group, and mode. Use fetch for the other direction.
ansible.builtin.filecreates files and directories, sets permissions, and removes paths. Setstate: directoryto make a folder.- A common mistake: a module will not create a missing parent directory for you. Make the directory first, or the task fails.
get_urldownloads a file over HTTP.uriis the flexible one: it can send any HTTP method and read the response.
Templates, conditions, and tags
- Jinja2 adds logic to templates with
{{ variable }},{% if %}, and{% for %}. - The
templatemodule renders a.j2file and copies the result to the host. The lab buildsship.cfgfromship.cfg.j2. whenruns a task only if a condition is true. You can test facts (ansible_facts['os_family'] == "Debian"), useand,or,not,in,is defined, and numeric comparisons.- Tags name parts of a playbook.
--tags "configuration,packages"runs only those tasks,--skip-tagsleaves them out, and--list-tasksshows the plan.
Advanced Ansible
Handlers are tasks that run only when a change notifies them. They run once, at the end of the play, even if several tasks notify them. The usual case is "restart Apache after the config changes".
- Error handling uses
block,rescue, andalways.blockis what you try,rescueis the recovery, andalwaysruns no matter what. - Lookup plugins bring data in from outside: a file, a URL, a database.
lookup('url', 'http://api.open-notify.org/astros.json') | from_jsonturns a JSON API into variables. - Callback plugins change the output of a playbook. They are switched on in
ansible.cfg, one at a time.
Collections and roles
- A collection is a package of modules, roles, and plugins. Install it from Galaxy or straight from git:
ansible-galaxy collection install git+https://github.com/csfeeser/nasa_images.git. - A role is a folder with a fixed layout:
tasks,handlers,defaults,vars,meta, andtemplates. A play uses it withroles: - role: name. - You can build a role and a collection yourself.
ansible-galaxy collection initmakes the skeleton,ansible-galaxy collection buildmakes a.tar.gz, andansible-galaxy collection installadds it.
Vault
- Ansible Vault encrypts files with AES. It can encrypt a variable file, a whole playbook, or one string, and decrypt only for a run.
- Vault commands take the password from a prompt,
--vault-password-file, or--vault-id @prompt. A playbook can load an encrypted vars file with-e @file. - The lab also shows
ansible-vault encrypt_string "value" --name "key"for one secret value.
Additional Ansible Tools
Molecule tests a role. It creates a container, runs the role (converge), checks the result (verify), and removes the container (destroy). molecule test runs the whole cycle.
- Molecule expects the role to sit under
collections/ansible_collections.molecule init scenarioadds a test scenario.
Scripts and custom modules
- The
scriptmodule copies a script to the host and runs it. The lab runs a small Python script that calls the ISS API. - The course says a script is a quick fix. A real module is better: reviewed, stable, and idempotent.
- You can write a module in Python. Put it in
~/mycode/library, addlibrary=~/mycode/librarytoansible.cfg, and importAnsibleModule. - The module reads arguments, does the work, and prints one JSON result. The lab builds
trivia_api.pyagainst the Open Trivia Database.
Key commands and tools
python3 -m pip install ansible— install Ansible.ansible --version— show the version and the config file in use.ansible fry -m ping— one ad-hoc task on one host.ansible-playbook playbook.yml— run a playbook.ansible-playbook playbook.yml -i inventory— pick the inventory.ansible-playbook playbook.yml --limit 'all:!farnsworth'— skip one host.ansible-playbook playbook.yml --tags "configuration,packages"/--skip-tags "packages"/--list-tasksansible-playbook playbook.yml -e "key=value"— extra vars, highest precedence.ansible-playbook playbook.yml --vault-password-file=~/.vaultpw/--vault-id @promptansible-doc apt/ansible-doc ansible.builtin.copy— read module docs.ansible-doc -t lookup -l— list lookup plugins.ansible-doc -t role alta3.nasa_images.image_downloader— read role docs.ansible-config dump/ansible-config init --disabled -t all > ansible-example.cfgansible-galaxy collection install,list,init,buildansible-galaxy role init create_firewall_rulesansible-vault encrypt,edit,decrypt,encrypt_stringmolecule init scenario,molecule create,converge,verify,destroy,testbash ~/px/scripts/full-setup.sh— reset the lab hosts before a lab.docker ps,ssh bender,curl http://10.10.2.3— check the lab hosts and the web server.
Key terms
The words of this course in one table. Learn them before the quiz or exam.
| Term | Meaning |
|---|---|
| Ad-hoc command | One module run from the shell with ansible. No playbook file is needed. |
| Ansible | A tool that automates Linux hosts over SSH. You write YAML, and Ansible makes the hosts match it. |
ansible.cfg | The config file that sets defaults, such as the inventory path. |
| Ansible Galaxy | The public website and command for sharing roles and collections. |
| Ansible Vault | The tool that encrypts files and strings with a password. AES is the default cipher. |
| Callback plugin | A plugin that changes how playbook output looks. |
| Collection | A package of modules, roles, and plugins, installed from Galaxy or git. |
Extra vars (-e) | Values passed on the command line. They have the highest precedence. |
| Fact | Information Ansible learns about a host, such as its OS family or IP address. |
| Handler | A task that runs only when notified, usually to restart a service. It runs once, at the end of the play. |
| Idempotent | Running it again gives the same end state. No change means "ok", not "changed". |
| Inventory | The list of hosts Ansible can reach, with their addresses and login details. |
| Jinja2 | The template language of Ansible. It uses {{ }} for values and {% %} for logic. |
| Lookup plugin | A plugin that reads data from outside Ansible, such as a file or a URL. |
| Loop | Repeats one task for each item in a list. The current item is {{ item }}. |
| Module | A small program that does one job, for example install a package or copy a file. |
| Molecule | A tool that tests a role in a container: create, converge, verify, destroy. |
| Playbook | A YAML file with one or more plays. Each play has hosts and a list of tasks. |
register | Saves the result of a task into a variable for later tasks. |
| Role | A reusable folder of tasks, handlers, defaults, vars, and templates. |
set_fact | Creates or updates a variable while the playbook runs. |
| Tag | A label on tasks. --tags and --skip-tags choose which tasks run. |
| Variable | A named value used in a playbook. It is read as {{ name }}. |
vars_prompt | A playbook setting that asks the user for a value at run time. |
when | A condition on a task. The task runs only if the condition is true. |
Check yourself
Answer each question first, then open it to check the answer.
1What is an inventory, and why does an ad-hoc command fail without one?
An inventory is the list of hosts, with their addresses and login details. Without it, Ansible has no address book, so ansible fry -m ping cannot find the host.
2What is the difference between the ansible and ansible-playbook commands?
ansible runs one ad-hoc module on hosts. ansible-playbook runs a YAML file with one or more plays and many tasks.
3What does idempotent mean for a module?
Idempotent means running it again gives the same end state. If nothing needs to change, the task reports "ok" and does nothing.
4Where does Ansible look for ansible.cfg, and which file wins?
It checks ANSIBLE_CONFIG, then ./ansible.cfg, then ~/.ansible.cfg, then /etc/ansible/ansible.cfg. The first file it finds is used, and the rest are ignored.
5What is a handler, and when does it run?
A handler is a special task, usually a service restart. It runs only when another task notifies it, and only once, at the end of the play.
Useful links
Official documentation and pages for this course.
- Alta3 Research — training, planning, and consulting.
- Alta3 Research on YouTube — free videos.
- Alta3 Research on GitHub — lab code and examples.
- Ansible documentation
- Ansible Galaxy
- Molecule documentation
- YAML specification