All exams← Red Hat Certified Engineer (RHCE) exam (EX294)
Test yourself →

Ansible Core Components

Ansible is an open-source automation engine that automates software provisioning, configuration management, and application deployment. It is agentless, meaning no special software needs to be installed on the managed nodes, relying primarily on SSH for communication and Python for module execution.

## Control Node & Managed Nodes

The Control Node is the machine where Ansible is installed and executed. It's where you run `ansible` commands or `ansible-playbook`. Managed Nodes (also called hosts) are the target servers or devices that Ansible manages. Communication between the control node and managed nodes typically occurs over SSH.

## Inventory

The Inventory is a file (or set of files) that defines the managed nodes Ansible will operate on. It lists hosts, groups them, and can assign variables specific to hosts or groups. Inventories can be static (INI or YAML files) or dynamic (generated by scripts).

  • INI format: `[webservers]` `host1.example.com`
  • YAML format: `all:` ` hosts:` ` host1.example.com:`

You can use the `ansible-inventory` command to view and manage your inventory.

## Modules & Tasks

Modules are the actual units of code Ansible executes on managed nodes. Each module is designed to perform a specific action, such as installing a package, managing a service, or copying a file. Modules are generally idempotent, meaning they can be run multiple times without causing unintended changes beyond the initial execution.

A Task is a call to an Ansible module with specific arguments. Tasks are defined within plays in a playbook.

  • Example Task: `- name: Ensure httpd is installed` ` ansible.builtin.yum: name=httpd state=present`

## Playbooks & Plays

Playbooks are YAML formatted files that are the core of Ansible's configuration, deployment, and orchestration language. They contain one or more Plays.

A Play is a block within a playbook that maps a set of tasks to a specific group of hosts defined in the inventory. Each play targets a specific set of hosts and runs tasks on them.

  • Playbook structure:

```yaml

---

  • name: Configure web servers

hosts: webservers

tasks:

  • name: Install Nginx

ansible.builtin.dnf:

name: nginx

state: present

```

## Variables & Facts

Variables are used to store values that can be reused throughout playbooks, making them more dynamic and flexible. They can be defined in inventory, playbooks, or separate variable files.

Facts are pieces of information about managed nodes (e.g., operating system, IP addresses, memory) that Ansible gathers automatically using the `setup` module. These facts can be accessed as variables within playbooks and are useful for conditional logic or dynamic configuration.

## Plugins

Plugins extend Ansible's core functionality. Examples include: Connection plugins (how Ansible connects), Lookup plugins (fetch external data), Filter plugins (manipulate data), and Callback plugins (add new behaviors).

  • Ansible is **agentless**, relying on SSH for communication with managed nodes.
  • The **Control Node** is where Ansible runs, targeting **Managed Nodes** (hosts).
  • The **Inventory** file defines hosts and groups, typically in INI or YAML format.
  • **Modules** are executable units of code that perform specific, often idempotent, actions on managed nodes.
  • A **Task** is a call to an Ansible module with specific arguments.
  • **Playbooks** are YAML files that orchestrate multiple tasks across managed nodes.
  • **Plays** within a playbook map a set of tasks to specific host groups.
  • **Facts** are system details automatically gathered by Ansible about managed nodes.
  • **Variables** provide dynamic configuration within playbooks, enhancing flexibility.
What is the primary connection method Ansible uses to communicate with managed nodes?
SSH
tap to reveal
What file defines the hosts and groups that Ansible manages?
Inventory (file)
tap to reveal
What are the executable units of code that Ansible runs on managed nodes?
Modules
tap to reveal
What is a YAML file that orchestrates a series of tasks and plays?
Playbook
tap to reveal
What information does Ansible automatically gather about managed nodes that can be used in playbooks?
Facts (gathered by the `setup` module)
tap to reveal
What command is used to run a single Ansible task on managed hosts without a playbook?
`ansible` (ad-hoc command)
tap to reveal
What property ensures that running a task multiple times yields the same result without unintended side effects?
Idempotence
tap to reveal
In a playbook, what block maps a set of tasks to a specific group of hosts?
A Play
tap to reveal

Ansible Installation and Configuration

## Ansible Installation and Configuration

Ansible is an agentless automation engine that uses SSH to communicate with managed nodes. Understanding its installation and configuration is fundamental for the RHCE exam, even if Ansible is pre-installed in the exam environment.

## Installation

On Red Hat Enterprise Linux (RHEL) 8 or 9, Ansible is installed from the AppStream repository using `dnf`:

  • `sudo dnf install ansible`

Managed nodes (the systems Ansible manages) do not require Ansible to be installed. They only need Python (version 3.6 or later is recommended for RHEL 8/9) and its dependencies, which are typically present by default.

## Configuration Files

Ansible's behavior is controlled by configuration files, primarily `ansible.cfg`. Ansible resolves its configuration using a specific order of precedence:

1. The path specified by the ANSIBLE_CONFIG environment variable.

2. `ansible.cfg` in the current working directory.

3. `.ansible.cfg` in the user's home directory (`~/.ansible.cfg`).

4. The system-wide configuration file at `/etc/ansible/ansible.cfg`.

Key sections within `ansible.cfg` include:

  • `[defaults]`: Global settings like inventory path, remote_user, private_key_file, and host_key_checking.
  • `[privilege_escalation]`: Settings for `become` (sudo, su, etc.).
  • `[ssh_connection]`: SSH-specific parameters.

## Inventory

The inventory defines the managed hosts and groups that Ansible will operate on. By default, Ansible looks for `/etc/ansible/hosts`.

  • The inventory can be specified using the `-i` option with `ansible` or `ansible-playbook` commands, or by setting the `inventory` parameter in `ansible.cfg`.
  • Inventory files can be in INI or YAML format.
  • They support defining groups, host variables, and group variables.

## SSH Connection and Authentication

Ansible uses OpenSSH for communication. Key parameters for SSH configuration include:

  • `remote_user`: The user Ansible connects as on managed nodes.
  • `private_key_file`: Path to the SSH private key for authentication.
  • Host key checking: A critical security feature. `host_key_checking = True` (default) verifies the identity of the remote host. For lab environments, it's sometimes set to `False` (e.g., in `ansible.cfg`) but should be `True` in production.

## Privilege Escalation (become)

Ansible uses the `become` directive to escalate privileges on managed nodes, typically to `root`. This is equivalent to using `sudo` or `su`.

  • `become: yes` (or `become: true`) enables privilege escalation.
  • `become_method`: Specifies the method (default is `sudo`). Other options include `su`, `doas`, `pbrun`, `pfexec`.
  • `become_user`: Specifies the user to become (default is `root`).

These settings can be defined globally in `ansible.cfg`, in playbooks, or as host/group variables.

  • Ansible is agentless and uses SSH for communication with managed nodes.
  • Managed nodes only require Python installed, not Ansible itself.
  • The `ansible.cfg` file controls Ansible's global behavior and can be overridden by environment variables or local files.
  • The order of `ansible.cfg` precedence is: `ANSIBLE_CONFIG`, current directory, `~/.ansible.cfg`, `/etc/ansible/ansible.cfg`.
  • The inventory file (default `/etc/ansible/hosts`) defines managed hosts and their grouping.
  • `become: yes` enables privilege escalation (e.g., `sudo`) on managed nodes.
  • `host_key_checking` is a crucial security setting for verifying remote host identities.
  • Ansible is installed on RHEL using `sudo dnf install ansible`.
How do you install Ansible on RHEL 8 or 9?
`sudo dnf install ansible`
tap to reveal
Do managed nodes need Ansible installed?
No, only Python (and its dependencies) is required on managed nodes.
tap to reveal
What is the default system-wide Ansible configuration file?
`/etc/ansible/ansible.cfg`
tap to reveal
What is the order of precedence for Ansible configuration files?
ANSIBLE_CONFIG env var > current directory `ansible.cfg` > `~/.ansible.cfg` > `/etc/ansible/ansible.cfg`
tap to reveal
What does `become: yes` achieve in an Ansible playbook?
It enables privilege escalation (e.g., using `sudo`) on the managed node.
tap to reveal
What is the default location for Ansible's inventory file?
`/etc/ansible/hosts`
tap to reveal
Which `ansible.cfg` parameter controls the verification of remote SSH host keys?
`host_key_checking`
tap to reveal

Creating Plays and Playbooks

## Introduction to Ansible Playbooks

Ansible Playbooks are the core of Ansible's automation capabilities, allowing you to define, orchestrate, and execute complex IT workflows. They are written in YAML (YAML Ain't Markup Language) and provide a human-readable way to describe a desired state for your managed nodes. Playbooks are idempotent, meaning they can be run multiple times without causing unintended side effects, only making changes when necessary.

## Playbook Structure

A playbook is an ordered list of plays. Each play defines a set of tasks to be executed on a specific group of hosts from your inventory. The basic structure includes:

  • `hosts:`: Specifies the target hosts or host groups from your inventory where the play's tasks will run (e.g., `webservers`, `all`, `localhost`).
  • `become:`: A boolean (`yes`/`no`) or a dictionary to control privilege escalation (e.g., `sudo`, `su`). Often used with `become_user:` to specify which user to become (e.g., `root`).
  • `vars:`: Defines variables specific to the play, which can then be used in tasks within that play.
  • `tasks:`: An ordered list of actions to be performed on the target hosts. Each task calls an Ansible module.

## Tasks and Modules

Each task in a play executes a specific Ansible module with a set of arguments. Modules are reusable units of code that perform specific functions, such as installing packages, managing services, copying files, or executing commands. Common modules include:

  • `ansible.builtin.yum` (or `dnf`): Manages packages on RHEL-based systems.
  • `ansible.builtin.service`: Manages system services (start, stop, restart, enable).
  • `ansible.builtin.copy`: Copies files from the control node to managed nodes.
  • `ansible.builtin.file`: Manages files and directories (create, delete, change permissions).
  • `ansible.builtin.command` / `ansible.builtin.shell`: Executes arbitrary commands.

## Handlers and Tags

  • Handlers: Special tasks that are only triggered when explicitly `notify:`-ed by another task and when that task reports a change. They are typically used for actions like restarting services after a configuration file has changed. Handlers are defined in a `handlers:` section at the play level.
  • Tags: Allow you to logically group tasks or plays. You can then selectively run only specific parts of a playbook using the `--tags` or `--skip-tags` options with `ansible-playbook`.

## Running Playbooks

To execute a playbook, use the `ansible-playbook` command:

`ansible-playbook [options] <playbook.yml>`

Key options include:

  • `--check`: Perform a "dry run" to show what changes would be made without actually making them.
  • `--syntax-check`: Verify the playbook's YAML syntax.
  • `-i <inventory>`: Specify an inventory file.
  • `-l <limit>`: Limit execution to a subset of hosts.
  • `-v`, `-vv`, `-vvv`: Increase verbosity for more detailed output.
  • `--extra-vars "key=value"`: Pass additional variables at runtime.

Understanding these components is crucial for automating system administration tasks effectively with Ansible.

  • Ansible Playbooks are written in YAML and define automation workflows.
  • A playbook consists of one or more plays, each targeting specific hosts.
  • Tasks within a play call Ansible modules to perform actions on managed nodes.
  • The `hosts:` directive specifies the target inventory groups or hosts for a play.
  • `become: yes` is used for privilege escalation, often with `become_user: root`.
  • Handlers are special tasks triggered by `notify:` and run only if a change occurs.
  • The `ansible-playbook` command is used to execute playbooks.
  • `--check` performs a dry run, showing changes without applying them.
  • Tags allow selective execution of tasks or plays using `--tags`.
What language are Ansible Playbooks written in?
YAML (YAML Ain't Markup Language)
tap to reveal
What is the primary purpose of the `hosts:` directive in a play?
To specify which hosts or host groups from the inventory the play's tasks will target.
tap to reveal
How do you enable privilege escalation (e.g., sudo) within an Ansible play?
By using `become: yes` (and optionally `become_user:` to specify the target user).
tap to reveal
What is an Ansible 'handler' and when is it executed?
A handler is a special task that is only executed when explicitly notified by another task, and only if the notifying task reports a change.
tap to reveal
Which `ansible-playbook` option allows you to test a playbook without making any actual changes?
`--check` (or `-C`)
tap to reveal
How can you run only a specific subset of tasks within a playbook?
By assigning `tags:` to tasks and then using the `--tags` option with `ansible-playbook`.
tap to reveal
Name two common Ansible modules used for managing packages and services on RHEL systems.
`ansible.builtin.yum` (or `dnf`) for packages and `ansible.builtin.service` for services.
tap to reveal

System Administration with Ansible Modules

## System Administration with Ansible Modules

The Red Hat Certified Engineer (RHCE) exam (EX294) heavily emphasizes using Ansible modules to automate common system administration tasks. Ansible is an agentless automation engine, meaning it doesn't require special software on managed nodes, relying on SSH for communication. Playbooks, written in YAML, define the desired state of your systems.

## Key Ansible Concepts

  • Playbooks: YAML files containing one or more plays. Each play targets a group of hosts from the inventory and defines a series of tasks.
  • Tasks: Calls to specific Ansible modules. Each task performs a single operation, e.g., installing a package or creating a user.
  • Modules: The core units of work in Ansible. They are idempotent, meaning running them multiple times with the same parameters will achieve the same result without unnecessary changes.
  • Inventory: A list of managed hosts, typically defined in an INI or YAML file. Hosts can be grouped for easier management.
  • Handlers: Special tasks that are only triggered when explicitly notified by another task, typically after a change occurs (e.g., restarting a service after a configuration file update).

## Essential Modules for RHCE

You'll need proficiency with various modules to manage RHEL systems:

  • Package Management: The `dnf` module (or `yum` for older RHEL) is crucial for installing, updating, and removing packages and managing repositories.

```yaml

  • name: Ensure httpd is installed

dnf:

name: httpd

state: present

```

  • Service Management: The `systemd` module manages services. Use `state: started/stopped`, `enabled: yes/no` to control their runtime and boot behavior.

```yaml

  • name: Start and enable httpd service

systemd:

name: httpd

state: started

enabled: yes

```

  • User and Group Management: The `user` and `group` modules create, modify, or delete system users and groups, managing properties like UID, GID, and shell.
  • File Management:
  • `file`: Manages files, directories, and symlinks (permissions, ownership, state).
  • `copy`: Copies files from the control node to managed hosts.
  • `template`: Renders Jinja2 templates on the control node and deploys them to managed hosts, allowing for dynamic configuration.
  • `lineinfile`/`blockinfile`: Modify specific lines or blocks within text files.
  • Storage Management: Modules like `lvg`, `lvol`, `filesystem`, and `mount` are used to create and manage Logical Volumes, filesystems, and mount points.
  • Firewall Management: The `firewalld` module configures firewall rules, zones, and services.
  • SELinux Management: The `selinux` module sets SELinux booleans or file contexts.
  • Cron Jobs: The `cron` module manages scheduled tasks.

Mastering these modules and understanding playbook structure is key to passing the RHCE exam.

  • Ansible is agentless, communicating with managed nodes via SSH.
  • Playbooks are written in YAML and define desired system states.
  • Ansible modules are idempotent, ensuring consistent results without unnecessary changes.
  • The `dnf` module manages packages and repositories on RHEL 8/9.
  • The `systemd` module controls services, including their state and enabled status.
  • The `template` module uses Jinja2 for dynamic configuration file deployment.
  • `firewalld` and `selinux` modules are critical for security configuration.
  • Handlers are triggered by `notify` only when a task reports a change.
  • The `file` module manages file permissions, ownership, and types (file, directory, link).
What is the primary communication method Ansible uses with managed nodes?
SSH (it is agentless).
tap to reveal
What file format are Ansible playbooks written in?
YAML (YAML Ain't Markup Language).
tap to reveal
Which Ansible module is used to install, update, or remove packages on RHEL 8/9?
The `dnf` module (or `yum` for older RHEL).
tap to reveal
How do you ensure a service like `httpd` is started and enabled at boot using Ansible?
Use the `systemd` module with `state: started` and `enabled: yes`.
tap to reveal
Which Ansible module allows you to deploy configuration files that include dynamic variables?
The `template` module, which uses Jinja2 templating.
tap to reveal
What is the purpose of an Ansible handler?
Handlers are tasks that are only run when explicitly `notify`-ed by another task, typically after a change.
tap to reveal
Which module would you use to create a directory, set its permissions, and ownership?
The `file` module.
tap to reveal
What does "idempotence" mean in the context of Ansible modules?
Running a module multiple times with the same parameters will achieve the same desired state without making unnecessary changes after the first successful run.
tap to reveal

Managing Ansible Roles

## Managing Ansible Roles

Ansible roles are a fundamental concept for organizing and reusing Ansible content. They provide a standardized directory structure that groups related tasks, handlers, variables, templates, files, and metadata into a cohesive unit. This modular approach significantly improves the manageability and scalability of complex automation projects.

## Why Use Roles?

  • Modularity and Reusability: Roles allow you to encapsulate specific functionalities (e.g., "install web server," "configure database") that can be easily reused across multiple playbooks and projects.
  • Readability and Maintainability: By separating different components into their designated directories, roles make playbooks easier to read, understand, and maintain.
  • Sharing: Roles are the standard way to share Ansible content, often via Ansible Galaxy.
  • Organization: They enforce a consistent structure for your automation code, making collaboration simpler.

## Standard Role Directory Structure

A typical role directory structure looks like this:

  • `roles/my_role/`
  • `tasks/main.yml`: Contains the main list of tasks for the role.
  • `handlers/main.yml`: Contains handlers that can be notified by tasks.
  • `vars/main.yml`: Defines variables specific to this role, with higher precedence than `defaults`.
  • `defaults/main.yml`: Defines default variables for the role, with the lowest precedence. These are easily overridden.
  • `files/`: Stores static files that the role might deploy (e.g., configuration files).
  • `templates/`: Stores Jinja2 templates that the role renders and deploys.
  • `meta/main.yml`: Contains metadata about the role, including author information, license, and role dependencies.
  • `library/`: For custom modules.

## Applying Roles in Playbooks

Roles are applied within a playbook using the `roles:` keyword.

```yaml

  • name: Apply web server role

hosts: webservers

roles:

  • web_server_role

```

For more dynamic or conditional role application, `include_role` (dynamic) and `import_role` (static) modules can be used. `import_role` processes the role at playbook parsing time, while `include_role` processes it at runtime, allowing for loops and conditionals.

## Role Variable Precedence

Understanding variable precedence is crucial:

1. `defaults/main.yml`: Lowest precedence. Easily overridden.

2. `vars/main.yml`: Higher precedence than `defaults`.

3. Playbook variables: Variables defined directly in the playbook.

4. `extra_vars`: Variables passed via `ansible-playbook -e "key=value"`, highest precedence.

## Ansible Galaxy

Ansible Galaxy is a public repository for sharing and finding roles. You can initialize a new role structure with `ansible-galaxy init my_new_role` and install roles from Galaxy using `ansible-galaxy install username.role_name`.

  • Ansible roles organize tasks, handlers, variables, templates, and files into a reusable, standardized structure.
  • The `defaults/main.yml` file defines variables with the lowest precedence within a role.
  • `vars/main.yml` defines role-specific variables with higher precedence than `defaults`.
  • `tasks/main.yml` is the primary entry point for a role's execution.
  • Role dependencies are declared in the `meta/main.yml` file.
  • `ansible-galaxy init` creates the standard directory structure for a new role.
  • `import_role` is static (processed at parse time), while `include_role` is dynamic (processed at runtime).
  • Roles significantly enhance modularity, reusability, and maintainability of Ansible automation.
What is the primary purpose of an Ansible role?
To organize and reuse Ansible content (tasks, handlers, variables, templates, files) into a standardized, modular structure.
tap to reveal
Which file in a role defines variables with the lowest precedence?
`defaults/main.yml`
tap to reveal
Where would you define role-specific variables that should override `defaults` but be overridden by playbook variables?
`vars/main.yml`
tap to reveal
How do you apply a role named `web_server` in an Ansible playbook?
Using the `roles:` keyword: ```yaml - hosts: webservers roles: - web_server ```
tap to reveal
What is the difference between `import_role` and `include_role`?
`import_role` is static (processed at playbook parsing time), while `include_role` is dynamic (processed at runtime, allowing for loops and conditionals).
tap to reveal
Where are role dependencies declared?
In the `meta/main.yml` file within the role's directory.
tap to reveal
Which command is used to create a new role's directory structure?
`ansible-galaxy init <role_name>`
tap to reveal
What is the main entry point for tasks within an Ansible role?
`tasks/main.yml`
tap to reveal

Using Advanced Ansible Features

## Using Advanced Ansible Features

The Red Hat Certified Engineer (RHCE) exam (EX294) requires proficiency in advanced Ansible features to manage complex environments efficiently and securely. These features promote reusability, security, and robust automation, moving beyond basic task execution to enterprise-grade configuration management.

## Ansible Roles

Ansible Roles are the standard way to organize Ansible content (tasks, handlers, variables, templates, files, and metadata) into reusable, self-contained units. They enforce a specific, well-defined directory structure, making playbooks more modular, readable, and shareable across projects and teams. You can initialize a role structure using `ansible-galaxy init <role_name>`. Roles are activated in playbooks using the `roles:` directive, simplifying complex playbook logic.

## Ansible Vault

Ansible Vault is crucial for securing sensitive data like passwords, API keys, or SSL certificates within your Ansible projects. It encrypts files, variables, or entire directories using strong AES256 encryption. Key commands include `ansible-vault create`, `ansible-vault edit`, `ansible-vault view`, `ansible-vault encrypt`, and `ansible-vault decrypt`. To use vault-encrypted files or variables in a playbook, you must provide the vault password, typically via the `--ask-vault-pass` command-line option or by specifying a vault password file with `--vault-password-file <path>`.

## Advanced Playbook Control

  • Error Handling: For robust automation, Ansible offers several error handling mechanisms. The `block`, `rescue`, and `always` keywords allow you to define a set of tasks (`block`) to run, tasks to execute if an error occurs within the block (`rescue`), and tasks that always run regardless of success or failure (`always`). You can also use `ignore_errors: true` to skip failures for specific tasks or `failed_when` to define custom failure conditions based on task output or registered variables.
  • Delegation: The `delegate_to` keyword allows a task to be executed on a different host than the one it's currently iterating over. For example, a task might run on the Ansible control node or a specific management host instead of the target inventory host. `run_once: true` ensures a task executes only once, typically on the first host in the current batch, even if multiple hosts are targeted. This is useful for tasks that should only happen a single time, like creating a database or updating a load balancer.
  • Conditionals and Loops: Advanced usage includes complex `when` conditions with `and`/`or` operators and nested loops using `loop_control` for specific iteration behaviors, such as `label` or `pause`.

## Dynamic Inventories

Dynamic Inventories allow Ansible to retrieve inventory information from external sources (e.g., cloud providers like AWS, Azure, VMware, or CMDBs) at runtime, rather than relying on static `ini` or `YAML` files. This is achieved using inventory plugins. You specify the plugin configuration in a YAML file or use a script that outputs JSON, allowing your inventory to be automatically updated as your infrastructure changes, providing flexibility and scalability.

  • Ansible Roles provide a standardized directory structure for organizing and reusing Ansible content.
  • Ansible Vault encrypts sensitive data (like passwords or keys) using AES256 to secure projects.
  • Use `ansible-vault --ask-vault-pass` or `--vault-password-file` to provide the vault password during execution.
  • The `block`, `rescue`, and `always` keywords enable structured error handling within playbooks.
  • `delegate_to` executes a task on a host different from the current target inventory host.
  • `run_once: true` ensures a task runs only once, typically on the first host in the current batch.
  • Dynamic inventories use plugins or scripts to fetch host information from external sources at runtime.
  • `ansible-galaxy init <role_name>` creates the standard directory structure for a new Ansible role.
What are Ansible Roles primarily used for?
To organize Ansible content (tasks, handlers, variables, etc.) into reusable, self-contained, and structured units.
tap to reveal
How do you encrypt sensitive data like passwords in Ansible?
Using Ansible Vault with commands like `ansible-vault encrypt <file>` or `ansible-vault create <file>`.
tap to reveal
What is the purpose of the `delegate_to` keyword in an Ansible task?
To execute the task on a different host (e.g., the control node or another management host) than the current target host from the inventory.
tap to reveal
Explain the `block`, `rescue`, and `always` keywords in Ansible.
`block` defines a set of tasks to run; `rescue` tasks run if any task in the block fails; `always` tasks run regardless of success or failure of the block.
tap to reveal
How do dynamic inventories work in Ansible?
They use inventory plugins or scripts to retrieve host information from external sources (like cloud providers or CMDBs) at runtime, keeping inventory up-to-date.
tap to reveal
What Ansible command is used to initialize the standard directory structure for a new role?
`ansible-galaxy init <role_name>`
tap to reveal
How do you provide the vault password when running an Ansible playbook that uses encrypted files?
By using the `--ask-vault-pass` option or by specifying a vault password file with `--vault-password-file <path>`.
tap to reveal
What does `run_once: true` achieve in an Ansible task?
It ensures the task is executed only once, typically on the first host in the current batch, even if multiple hosts are targeted by the playbook.
tap to reveal

Managing Secrets with Ansible Vault

## Managing Secrets with Ansible Vault

Ansible Vault is a feature that allows you to encrypt sensitive data such as passwords, API keys, and other confidential information within your Ansible projects. This ensures that sensitive data is not stored in plain text, making your automation more secure, especially when storing playbooks in version control systems.

Core Vault Commands

  • `ansible-vault create <filename>`: Use this command to create a new, empty file that will be immediately encrypted. You'll be prompted to set a new vault password. The file will open in your default editor for content entry.
  • `ansible-vault edit <filename>`: This command decrypts an existing vault-encrypted file, opens it in your editor, and re-encrypts it upon saving and exiting. This is the primary way to modify encrypted data.
  • `ansible-vault view <filename>`: To inspect the contents of an encrypted file without editing it, use `view`. It decrypts the file and displays its content to standard output, then exits without saving.
  • `ansible-vault encrypt <filename>`: Encrypts an *existing* unencrypted file in place. The original file is replaced by its encrypted version.
  • `ansible-vault decrypt <filename>`: Decrypts an *existing* encrypted file in place, reverting it to plain text. Use with caution.
  • `ansible-vault rekey <filename>`: This command allows you to change the password of an already encrypted vault file. You'll be prompted for the old password and then the new one.
  • `ansible-vault encrypt_string`: This is useful for encrypting individual strings directly from the command line, which can then be pasted into `vars` files. For example: `ansible-vault encrypt_string --name 'db_password' 'mysecretpassword'`

Managing Vault Passwords

To interact with encrypted files, Ansible needs the vault password. You can provide it in several ways:

  • `--ask-vault-pass`: Prompts you for the password interactively during execution.
  • `--vault-password-file /path/to/vault_pass.txt`: Specifies a file containing the vault password. The file should contain only the password and have strict permissions (e.g., `chmod 0600`).
  • `ansible.cfg`: You can configure `vault_password_file = /path/to/vault_pass.txt` in your `ansible.cfg` to automatically use a password file.

Using Vault in Playbooks

Encrypted files can be included in playbooks just like regular variable files. For example, if you have `group_vars/all/secrets.yml` encrypted with vault, Ansible will automatically prompt for the password (or use a configured password file) when it needs to access variables from that file. Variables defined within these encrypted files can then be used in your playbooks and templates.

Best Practices

  • Never commit vault password files to version control systems (like Git). Use `.gitignore` to exclude them.
  • Ensure vault password files have strict file permissions (e.g., `0600`) to prevent unauthorized access.
  • Use different vault passwords for different environments (e.g., dev, staging, production) or sensitive projects if feasible.
  • Ansible Vault encrypts sensitive data using AES256 to protect it from unauthorized access.
  • `ansible-vault create` generates a new encrypted file, while `ansible-vault edit` modifies an existing one.
  • The `--vault-password-file` option allows Ansible to read the vault password from a specified file.
  • Vault password files should have strict permissions (e.g., `0600`) and never be committed to version control.
  • `ansible-vault encrypt` encrypts an existing unencrypted file in place, replacing its content.
  • `ansible-vault encrypt_string` is used to encrypt individual variable strings for direct use in playbooks.
  • `ansible-vault rekey` changes the password of an already encrypted vault file.
  • Ansible automatically decrypts vault files when processing playbooks, provided the correct password is supplied.
What is the primary purpose of Ansible Vault?
To encrypt sensitive data (passwords, API keys, etc.) within Ansible projects to prevent plain-text storage.
tap to reveal
Which command creates a *new* encrypted file?
`ansible-vault create <filename>`
tap to reveal
How do you modify an *existing* encrypted file?
`ansible-vault edit <filename>`
tap to reveal
What command allows you to encrypt an *already existing* unencrypted file?
`ansible-vault encrypt <filename>`
tap to reveal
How can you provide the vault password to Ansible without typing it every time?
Using `--vault-password-file /path/to/vault_pass.txt` or configuring `vault_password_file` in `ansible.cfg`.
tap to reveal
What command is used to encrypt a single string for use as a variable in a playbook?
`ansible-vault encrypt_string --name 'my_var_name' 'my_secret_value'`
tap to reveal
What security best practice should be followed for vault password files?
They should have strict file permissions (e.g., `0600`) and never be committed to version control systems.
tap to reveal
What is the purpose of `ansible-vault rekey`?
To change the password of an existing encrypted vault file.
tap to reveal

Creating and Using Templates

## Creating and Using Templates in Ansible

Ansible templates are a powerful feature for creating customized configuration files dynamically on managed hosts. They allow you to embed variables and control structures directly into static file content, which is then rendered on the target system. Ansible uses the Jinja2 templating language for this purpose.

Why Use Templates?

Templates are essential for:

  • Dynamic Configuration: Generating configuration files (e.g., Apache virtual hosts, Nginx server blocks, user profiles) that vary based on host-specific data, group variables, or facts.
  • Reduced Duplication: Maintaining a single template file and populating it with different data, rather than having multiple slightly different static configuration files.
  • Idempotency: The `template` module, like other Ansible modules, ensures that the target file is only updated if its content changes, maintaining idempotency.

The `template` Module

The core of using templates in Ansible is the `template` module.

It takes a source template file (on the control node) and renders it on the managed node, substituting Jinja2 expressions with actual values.

Key parameters for the `template` module:

  • `- src`: Specifies the path to the template file on the Ansible control node. This path is typically relative to the playbook or defined in `ansible.cfg`. A common convention is to place templates in a `templates/` subdirectory relative to the playbook.
  • `- dest`: Specifies the absolute path where the rendered file will be created or updated on the managed node.
  • `- owner`, `- group`, `- mode`: Optional parameters to set the ownership, group, and file permissions of the destination file on the managed node, similar to the `copy` module.

Jinja2 Syntax Basics

Understanding basic Jinja2 syntax is crucial for writing effective templates:

  • Expressions and Variables: Use `{{ variable_name }}` to insert the value of an Ansible variable. For example, `ServerName {{ ansible_hostname }}`.
  • Statements and Control Structures: Use `{% statement %}` for logic like loops (`for`) and conditionals (`if/else`).
  • Example `for` loop:

```jinja2

{% for user in users %}

User {{ user.name }} with UID {{ user.uid }}

{% endfor %}

```

  • Example `if` statement:

```jinja2

{% if enable_feature %}

Feature is enabled.

{% else %}

Feature is disabled.

{% endif %}

```

  • Comments: Use `{# comment #}` for comments within the template that will not appear in the rendered output.

Variables used within templates can originate from various Ansible sources, including inventory variables, `group_vars`, `host_vars`, `vars` sections in playbooks, `set_fact` tasks, and Ansible facts.

  • Ansible templates utilize the Jinja2 templating language for dynamic content generation.
  • The `template` module is the primary tool for rendering and deploying templates to managed nodes.
  • The `src` parameter in the `template` module specifies the template file's path on the Ansible control node.
  • The `dest` parameter in the `template` module defines the target file's absolute path on the managed node.
  • Variables are embedded within Jinja2 templates using the `{{ variable_name }}` syntax.
  • Control structures (e.g., loops, conditionals) in Jinja2 templates are enclosed in `{% statement %}`.
  • Template files are conventionally organized in a `templates/` subdirectory relative to the Ansible playbook.
  • The `template` module is idempotent, only making changes on the managed node if the rendered file's content differs.
What templating language does Ansible use for its templates?
Jinja2
tap to reveal
Which Ansible module is used to deploy a template file to a managed node?
`template` module
tap to reveal
In the `template` module, what does the `src` parameter specify?
The path to the template file on the Ansible control node.
tap to reveal
In the `template` module, what does the `dest` parameter specify?
The absolute path where the rendered file will be created on the managed node.
tap to reveal
What is the Jinja2 syntax for embedding an Ansible variable within a template?
`{{ variable_name }}`
tap to reveal
What is the Jinja2 syntax for control structures like loops or conditionals within a template?
`{% statement %}`
tap to reveal
Where are template files typically stored relative to an Ansible playbook?
In a `templates/` subdirectory.
tap to reveal
Name two optional parameters for the `template` module to manage the destination file's permissions.
`owner`, `group`, `mode` (any two)
tap to reveal