Ansible: Understanding Conditions, Roles, and Vault
Tags: devops, ansible, beginners, tutorial
Published: 2023-11-11 08:08:43


## Condition
In [Ansible](https://dev.to/imsushant12/unleash-the-power-of-automation-with-ansible-337g), conditions, specified using the `when` statement, allow us to define specific tasks based on certain conditions. For instance, let's consider a scenario where we need to install Apache Server on managed nodes depending on the type of Linux distribution. Here's how you can structure your YAML script:

```yaml
--- # Conditional Playbook
- hosts: <group-name>
  remote_user: <user-name>
  become: yes
  connection: ssh
  tasks:
    - name: install apache on Debian
      command: apt-get -y install apache2
      when: ansible_os_family == "Debian"
    - name: install apache for RedHat
      command: yum -y install httpd
      when: ansible_os_family == "RedHat"
```
In this example, the command module is utilized to execute Linux commands based on the type of Linux distribution detected using ``ansible_os_family``.

## Vault
Ansible provides a robust solution for encrypting playbooks using the concept of vaults. This helps secure sensitive information in playbooks, preventing unauthorized access and modifications. Ansible uses the **AES256** encryption technique to encrypt the files.

### Commands:
#### Encrypt an Existing Playbook:

```bash
ansible-vault encrypt <playbook-name.yml>
```

#### Decrypt an Encrypted Playbook:
```bash
ansible-vault decrypt <playbook-name.yml>
```

#### Create a New Encrypted Playbook:
```bash
ansible-vault create <playbook-name.yml>
```

#### Edit an Encrypted Playbook:
```bash
ansible-vault edit <playbook-name.yml>
```

#### Change the Password of an Encrypted Playbook:
```bash
ansible-vault rekey <playbook-name.yml>
```

> **Note**: During encryption, you will be prompted to provide a password. For decryption, the same password is required; otherwise, the file will be displayed with random data.

## Roles
Roles in Ansible serve as a powerful mechanism for organizing and structuring automation content. They allow the grouping of related tasks, handlers, variables, and files in a reusable and modular manner. This abstraction enhances the maintainability and scalability of playbooks.

#### Roles Directory Structure:
```
+-- roles/
    +-- WebServer/
        +-- tasks/
        |   +-- main.yml
        +-- handlers/
        |   +-- main.yml
        +-- files/
        +-- templates/
        +-- vars/
        |   +-- main.yml
        +-- defaults/
        |   +-- main.yml
        +-- meta/
        |   +-- main.yml
```

### Why Use Roles?
- **Modularity**: Break down automation into smaller, reusable components.
- **Reusability**: Easily reuse roles across different playbooks and projects.
- **Organization**: Provide a clear and organized structure for automation code.
- **Abstraction**: Abstract away the complexity of individual tasks, focusing on high-level organization.

### Creating a Role
#### 1. Create Directory:
```bash
mkdir -p playbook/roles/WebServer/tasks
```
#### 2. Create ``main.yml`` File:
```bash
touch playbook/roles/WebServer/tasks/main.yml
```
#### 3. Create ``master.yml`` File:
```bash
touch master.yml
```
#### 4. Write Script in ``main.yml``:
```bash
vi playbook/roles/WebServer/tasks/main.yml
```

```yml
- name: install apache
  yum: pkg=httpd state=latest
```
#### 5. Specify Tasks in ``master.yml``:
```bash
vi master.yml
```

```yml
- hosts: <group-name>
  remote_user: <user-name>
  become: yes
  connection: ssh
  roles:
    - WebServer
```
#### 6. Run the Playbook:
```bash
ansible-playbook master.yml
```


The overall structure can be simplified as:
```
+----------------------------------------+
|    master.yml          Roles           |
|  +--------------+   +---------------+  |
|  | Targets      |   |   WebServer   |  |
|  | Roles        |   | +----------+  |  |
|  |  - WebServer |   | |   task   |  |  |
|  |              |   | +----------+  |  |
|  +--------------+   |               |  |
|                     | +----------+  |  |
|                     | | handlers |  |  |
|                     | +----------+  |  |
|                     |               |  |
|                     | +----------+  |  |
|                     | |   vars   |  |  |
|                     | +----------+  |  |
|                     |               |  |
|                     +---------------+  |
+----------------------------------------+
```

This structured approach to Ansible scripting not only enhances the clarity of your code but also facilitates the scalability and maintainability of your automation projects.

## Conclusion
Ansible conditions allow for the selective execution of tasks based on specific conditions. This enables automation practitioners to tailor their playbooks to specific environments or configurations. The ``when`` clause is the primary mechanism for defining conditions in Ansible. It takes a boolean expression as its argument, and the corresponding task is executed only if the expression evaluates to true.

Now, let's talk about roles – they're like toolkits that keep everything organized. Imagine you have a bunch of tasks, files, and settings for, say, setting up a web server. Roles group all of that neatly together, making it easier to reuse and understand. So, Ansible roles play a pivotal role in structuring and organizing complex automation tasks. They encapsulate related configuration files, variables, and templates, allowing for modularity and reusability across different playbooks. By utilizing roles, automation practitioners can effectively manage and maintain large-scale automation projects.


Ansible vaults provide a secure mechanism for encrypting sensitive data, such as passwords and credentials, within playbooks. This safeguards sensitive information from unauthorized access. Ansible vaults utilize the AES-256 encryption algorithm to encrypt playbook files. The encryption process prompts the user to provide a password, which is subsequently used to decrypt the playbook when needed.

To learn more about Ansible, click [here](https://dev.to/imsushant12/unleash-the-power-of-automation-with-ansible-337g). I have also talked about Ad-Hoc Commands, Modules, and Playbooks in Ansible. Check it out [here](https://dev.to/imsushant12/exploring-ansible-ad-hoc-commands-modules-and-playbooks-9k5).