Day 56: Ansible Hands-on

Day 56: Ansible Hands-on

Table of contents

Show more

??? Step 1: Install Ansible

First, we need to install Ansible on your control machine.

  1. Update your package manager:
  2. Install Ansible:
  3. Verify the installation:

?? Step 2: Set Up Your Inventory

An inventory file defines the hosts and groups of hosts upon which commands, modules, and tasks in a playbook operate.

  1. Create an inventory file:
  2. Add your hosts:

?? Step 3: Configure SSH Access

Ensure you can SSH into your hosts from the control machine without a password.

  1. Generate an SSH key:
  2. Copy the SSH key to your hosts:

?? Step 4: Write Your First Playbook

Ansible playbooks are written in YAML. Let's create a playbook to install NGINX on web servers.

  1. Create a playbook file:
  2. Add the playbook content:

?? Step 5: Run the Playbook

Execute the playbook to apply the desired configurations on the target hosts.

  1. Run the playbook:
  2. Check the status: Ansible will show you the tasks being executed and their status.

?? Step 6: Verify the Changes

Verify that NGINX has been installed and is running on your web server.

  1. SSH into the web server:
  2. Check the NGINX status:

You should see that NGINX is active and running.

?? Step 7: Using Variables

Variables make your playbooks more flexible and reusable.

  1. Update the playbook to use variables:

?? Step 8: Modularize with Roles

Roles allow you to organize tasks, variables, files, and handlers in a structured way.

  1. Create a role directory structure:
  2. Move your tasks to a role:
  3. Add the task content:
  4. Update the playbook to use the role:

?? Step 9: Documentation and Comments

Add comments to your playbooks and roles for better readability and maintenance.

COPY

COPY

yamlCopy code---
- name: Install NGINX on web servers
  hosts: webservers
  become: yes

  # Variables used in the playbook
  vars:
    nginx_package: nginx

  # Define roles to be executed
  roles:
    - nginx
        

?? Step 10: Testing and Validation

Regularly test your playbooks to ensure they work as expected. Use tools like Molecule for role testing.

  1. Install Molecule:
  2. Initialize a Molecule scenario:
  3. Run the tests:

?? Step 11: Secure Your Secrets

Use Ansible Vault to encrypt sensitive data like passwords and API keys.

  1. Create an encrypted variable file:
  2. Include the encrypted file in your playbook:
  3. Edit the encrypted file:

?? Conclusion

By following these steps, you have learned how to set up Ansible, write and run playbooks, use variables, modularize with roles, document your code, test your configurations, and handle secrets securely. Ansible makes IT automation simple, efficient, and powerful. Happy automating! ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了