24、Advanced Ansible Techniques: A Comprehensive Guide

Advanced Ansible Techniques: A Comprehensive Guide

1. Running Playbooks Locally

Running a playbook locally with Ansible is not the same as running it on localhost . When you run a playbook on localhost , Ansible sets up an SSH connection to localhost .

1.1. Running on localhost with SSH

We can create a local inventory file with the following contents:

[local]
localhost

Then, run the ping module in an ad - hoc command against this inventory:

$ ansible -i localhosts -m ping all --ask - pass

The output will prompt you to confirm the host authenticity and enter the SSH password.

1.2. Running Locally without SSH

We can modify the inventory to use a direct local connection:

[local]
localhost ansible_connection=local

The ansible_connection variable defines the connection protocol. If we change the inventory like this:

[local]
frt01.example.com ansible_connection=local

Ansible will connect locally to the machine running the playbook without SSH.

We can demonstrate this by the following steps:
1. Check for the absence of a test file in the local /tmp directory:

ls -l /tmp/foo
  1. Run an ad - hoc command to touch this file on all hosts in the new inventory:
$ ansible -i localhosts2 -m file -a "path=/tmp/foo state=touch" all
  1. Check if the test file is present on the local machine:
$ ls -l /tmp/foo

This ability to run commands locally without SSH setup can be very useful for quick local operations.

2. Working with Proxies and Jump Hosts

When configuring core network devices, they are often isolated via a proxy or jump host. Ansible can automate network device configuration over SSH, and it can work through a jump host.

2.1. Example Setup

Assume we have two Cumulus Networks switches ( cmls01.example.com and cmls02.example.com ) that can only be accessed from bastion.example.com .

  1. Define an inventory group with the switches:
[switches]
cmls01.example.com
cmls02.example.com
  1. Add special SSH arguments to the inventory variables for this group:
[switches:vars]
ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q bastion.example.com"'
  1. Run the Ansible ping module against this inventory:
$ ansible -i switches -m ping all

Ansible will proxy via bastion.example.com behind the scenes.

2.2. Note

This example assumes the same username and SSH credentials for the bastion host and switches. There are more advanced ways to provide separate credentials using OpenSSH.

3. Configuring Playbook Prompts

Ansible can prompt you for user input during a playbook run and store the input in a variable for future processing.

3.1. Example Playbook

  1. Create a simple play definition:
---
- name: A simple play to demonstrate prompting in a playbook
  hosts: frontends
  1. Add a vars_prompt section to prompt for a user ID and a password:
vars_prompt:
  - name: loginid
    prompt: "Enter your username"
    private: no
  - name: password
    prompt: "Enter your password"
    private: yes
  1. Add a task to demonstrate the prompting process:
tasks:
  - name: Proceed with login
    debug:
      msg: "Logging in as {{ loginid }}..."
  1. Run the playbook:
$ ansible - playbook - i hosts prompt.yml

The password will not be echoed to the terminal for security reasons.

3.2. Table of Prompt Variables

Variable Name Prompt Message Private
loginid Enter your username No
password Enter your password Yes

4. Placing Tags in the Plays and Tasks

As your Ansible playbooks grow in scale and complexity, you may want to run a subset of a playbook. Tags in Ansible plays are the solution.

4.1. Example Playbook with Tags

  1. Create a simple playbook with two tasks:
---
- name: Simple play to demonstrate use of tags
  hosts: frontends
  tasks:
    - name: Install nginx
      yum:
        name: nginx
        state: present
      tags:
        - install
    - name: Install nginx configuration from template
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx.conf
      tags:
        - customize
  1. Run the playbook with the --tags switch to run only the install - tagged tasks:
$ ansible - playbook - i hosts tags.yml --tags install
  1. Use the --skip - tags switch to skip the customize - tagged tasks:
$ ansible - playbook - i hosts tags.yml --skip - tags customize

4.2. Tag Rules

  • Each task can have more than one tag, specified in a YAML list format.
  • If you use the --tags switch, a task will run if any of its tags match the specified tag.
  • Tags can be reused.

4.3. Using --list - tasks

You can add --list - tasks to the command to list the tasks that would run without actually running the playbook. For example:

$ ansible - playbook - i hosts tags.yml --skip - tags customize --list - tasks
$ ansible - playbook - i hosts tags.yml --tags install,customize --list - tasks
$ ansible - playbook - i hosts tags.yml --list - tasks

The following mermaid flowchart shows the decision - making process for running tasks based on tags:

graph TD;
    A[Run Playbook] --> B{Specify --tags or --skip - tags?};
    B -- Yes --> C{--tags?};
    B -- No --> D[Run all tasks];
    C -- Yes --> E[Run tasks with matching tags];
    C -- No --> F[Skip tasks with specified tags];

5. Securing Data with Ansible Vault

Ansible Vault is a tool that allows you to encrypt sensitive data at rest while still using it in a playbook. This is crucial when storing login credentials or other sensitive information to run a playbook unattended.

5.1. Creating a Vault

  1. Start by creating a new vault file named secret.yml :
$ ansible-vault create secret.yml
  1. You will be prompted to enter and confirm a new vault password.
  2. After entering the password, you will be taken to your default editor (defined by the EDITOR shell variable). In the editor, create a vars file with your sensitive data:
---
secretdata: "Ansible is cool!"
  1. Save and exit the editor. The contents of the secret.yml file will now be encrypted. You can verify this by running:
$ cat secret.yml

The output will show the encrypted data, starting with $ANSIBLE_VAULT;1.1;AES256 .

5.2. Using an Encrypted Vault in a Playbook

  1. Create a simple playbook that uses the encrypted vault file:
---
- name: A play that makes use of an Ansible Vault
  hosts: frontends
  vars_files:
    - secret.yml
  tasks:
    - name: Tell me a secret
      debug:
        msg: "Your secret data is: {{ secretdata }}"
  1. Try running the playbook without providing the vault password:
$ ansible-playbook -i hosts vaultplaybook.yml

You will receive an error message indicating that no vault secrets were found.
3. To run the playbook successfully, provide the vault password using the --ask-vault-pass option:

$ ansible-playbook -i hosts vaultplaybook.yml --ask-vault-pass

Enter the vault password when prompted, and the playbook will decrypt the vault file and load the variables.

5.3. Inline Encryption in a Playbook

You can also encrypt sensitive data inline in a playbook.
1. Encrypt a string using Ansible Vault:

$ ansible-vault encrypt_string 'Ansible is cool!' --name secretdata

Enter and confirm the vault password. The output will be an encrypted string that you can copy and paste into your playbook.
2. Modify the playbook to use the inline encrypted data:

---
- name: A play that makes use of an Ansible Vault
  hosts: frontends
  vars:
    secretdata: !vault |
      $ANSIBLE_VAULT;1.1;AES256
      ... (encrypted data here)
  tasks:
    - name: Tell me a secret
      debug:
        msg: "Your secret data is: {{ secretdata }}"
  1. Run the playbook with the --ask-vault-pass option as before:
$ ansible-playbook -i hosts inlinevaultplaybook.yml --ask-vault-pass

5.4. Table of Ansible Vault Commands

Command Description
ansible-vault create <filename> Create a new encrypted vault file
ansible-vault encrypt_string <string> --name <variable_name> Encrypt a string inline
ansible-playbook <playbook.yml> --ask-vault-pass Run a playbook with a vault password prompt

The following mermaid flowchart shows the process of using Ansible Vault:

graph TD;
    A[Create Vault File] --> B[Encrypt Data in Editor];
    B --> C[Save and Exit Editor];
    C --> D[Use Vault in Playbook];
    D --> E{Provide Vault Password?};
    E -- Yes --> F[Decrypt and Run Playbook];
    E -- No --> G[Error: No Vault Secrets Found];

Ansible Vault is a powerful and versatile tool for protecting sensitive playbook data. By using it, you can run most of your playbooks unattended without exposing passwords or other sensitive information. If you add multiple encrypted files in your group_vars directory, all files need to contain the same password.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值