Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Cursus 4Naam in de cursus: Introduction to Ansible

Introduction to Ansible

Course 4 of 13 in the Alta3 Academy library. Alta3 Academy self-paced course.

Notitie

My result — Lessons read: all 36/36; Course progress: 100%.

  • 14 Lessen
  • 6 Commando's
  • 1 Labs

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

4.1

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-playbook command.
  • Variables, loops, conditions, tags, and handlers.
  • Files, templates, and Jinja2.
  • Error handling with block, rescue, and always.
  • Collections, roles, and Ansible Galaxy.
  • Ansible Vault for secrets, Molecule for role testing, and writing your own module in Python.

4.2

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.

4.3

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-B then % makes a side-by-side split, and Ctrl-B then " 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.

4.4

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 .gitignore file tells git what never to commit. For Ansible this includes vault password files and local secrets.

4.5

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.

4.6

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 of fry.
  • An INI inventory lists hosts under a group name, with ansible_host, ansible_user, and ansible_python_interpreter. A YAML inventory holds the same data with YAML syntax.

Plays and settings

  • A playbook has a name, hosts, gather_facts, connection, and tasks. Each task names a module, for example ansible.builtin.apt with name: figlet and state: present.
  • ansible-playbook runs a playbook. become: yes adds sudo for a task.
  • ansible.cfg holds defaults, so you type less. Ansible looks for it in ANSIBLE_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, and log_path. ansible-config dump shows 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_prompt asks the user for a value at run time. register saves a task result as a variable. set_fact creates a value during the run.

4.7

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.file creates files and directories, sets permissions, and removes paths. Set state: directory to 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_url downloads a file over HTTP. uri is 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 template module renders a .j2 file and copies the result to the host. The lab builds ship.cfg from ship.cfg.j2.
  • when runs a task only if a condition is true. You can test facts (ansible_facts['os_family'] == "Debian"), use and, or, not, in, is defined, and numeric comparisons.
  • Tags name parts of a playbook. --tags "configuration,packages" runs only those tasks, --skip-tags leaves them out, and --list-tasks shows the plan.

4.8

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, and always. block is what you try, rescue is the recovery, and always runs 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_json turns 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

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.

4.9

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 scenario adds a test scenario.

Scripts and custom modules

  • The script module 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, add library=~/mycode/library to ansible.cfg, and import AnsibleModule.
  • The module reads arguments, does the work, and prints one JSON result. The lab builds trivia_api.py against the Open Trivia Database.

4.10

Key commands and tools

4.11

Key terms

The words of this course in one table. Learn them before the quiz or exam.

TermMeaning
Ad-hoc commandOne module run from the shell with ansible. No playbook file is needed.
AnsibleA tool that automates Linux hosts over SSH. You write YAML, and Ansible makes the hosts match it.
ansible.cfgThe config file that sets defaults, such as the inventory path.
Ansible GalaxyThe public website and command for sharing roles and collections.
Ansible VaultThe tool that encrypts files and strings with a password. AES is the default cipher.
Callback pluginA plugin that changes how playbook output looks.
CollectionA 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.
FactInformation Ansible learns about a host, such as its OS family or IP address.
HandlerA task that runs only when notified, usually to restart a service. It runs once, at the end of the play.
IdempotentRunning it again gives the same end state. No change means "ok", not "changed".
InventoryThe list of hosts Ansible can reach, with their addresses and login details.
Jinja2The template language of Ansible. It uses {{ }} for values and {% %} for logic.
Lookup pluginA plugin that reads data from outside Ansible, such as a file or a URL.
LoopRepeats one task for each item in a list. The current item is {{ item }}.
ModuleA small program that does one job, for example install a package or copy a file.
MoleculeA tool that tests a role in a container: create, converge, verify, destroy.
PlaybookA YAML file with one or more plays. Each play has hosts and a list of tasks.
registerSaves the result of a task into a variable for later tasks.
RoleA reusable folder of tasks, handlers, defaults, vars, and templates.
set_factCreates or updates a variable while the playbook runs.
TagA label on tasks. --tags and --skip-tags choose which tasks run.
VariableA named value used in a playbook. It is read as {{ name }}.
vars_promptA playbook setting that asks the user for a value at run time.
whenA condition on a task. The task runs only if the condition is true.

4.12

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.

Oefenen

Alle commando's in dit hoofdstuk