Saturday, 31 December 2022

Automate Linux SysAdmin tasks with Ansible in 95+ examples - part 1



1. Decrypting an Ansible Vault

You have an Ansible Vault-encrypted file and need to decrypt it to access the secrets.

ansible-vault decrypt secret_file.yml

Ansible will prompt you for the Vault password used to encrypt the file.You can now access the decrypted data in secret_file.yml.

2.Using Ansible Vault in Ansible Playbooks

---
- name: Example Playbook
  hosts: localhost
  vars:
    sensitive_data: !vault |
      $ANSIBLE_VAULT;1.1;AES256
      66366232396135343865393765653837646562306361623863343535333563373362393865393338

You can create this encrypted variable using ansible-vault encrypt_string.

3.Checking Out Git Repositories via HTTPS with Ansible

You need to automate the process of checking out a Git repository hosted on HTTPS using Ansible.

Create a Playbook to Clone the Git Repository
---
- name: Clone Git Repo via HTTPS
  hosts: your_target_host
  tasks:
    - name: Clone the Repository
      git:
        repo: https://github.com/yourusername/your-repo.git
        dest: /path/to/destination


Run the Playbook

ansible-playbook git_clone.yml


4.Checking Out Git Repositories via SSH with Ansible

Create a Playbook to Clone the Git Repository via SSH

---
- name: Clone Git Repo via SSH
  hosts: your_target_host
  tasks:
    - name: Clone the Repository
      git:
        repo: git@github.com:yourusername/your-repo.git
        dest: /path/to/destination
        accept_hostkey: yes

Run the Playbook

ansible-playbook git_clone_ssh.yml

5.Reading Environment Variables with Ansible

Create a Playbook to Read Environment Variable

---
- name: Read Environment Variable
  hosts: localhost
  tasks:
    - name: Display Environment Variable
      debug:
        var: MY_ENV_VAR

Run the Playbook with an Environment Variable

MY_ENV_VAR=my_value ansible-playbook env_var_example.yml


6.Executing Commands on the Ansible Host

Create a Playbook to Execute Commands

---
- name: Execute Commands
  hosts: localhost
  tasks:
    - name: Run a Shell Command
      command: echo "Hello, Ansible!"


Run the Playbook

ansible-playbook execute_commands.yml


7.Backing Up with Rsync in Ansible

Create a Playbook for Rsync Backup

---
- name: Rsync Backup
  hosts: your_target_host
  tasks:
    - name: Backup Directory with Rsync
      ansible.builtin.synchronize:
        src: /path/to/source_directory/
        dest: /path/to/backup_directory/
        mode: pull


Run the Playbook

ansible-playbook rsync_backup.yml


8.Managing Network Devices with Ansible:

In this example, we'll automate the configuration of a network switch using Ansible.

1. Inventory File (inventory.ini):

[network_devices]
switch ansible_host=192.168.1.1 ansible_user=admin ansible_ssh_pass=your_password

Replace 192.168.1.1 with the IP address of your network switch, and set ansible_user and ansible_ssh_pass accordingly.

2. Playbook for Network Configuration (network_config.yml):

---
- name: Configure Network Switch
  hosts: switch
  tasks:
    - name: Configure VLAN
      ios_vlan:
        vlan_id: 100
        name: Servers
        state: present
      become: yes

    - name: Configure Port
      ios_interface:
        name: GigabitEthernet0/1
        description: Connect to Server
        switchport_mode: access
        switchport_access_vlan: 100
      become: yes

Run the Playbook:

ansible-playbook -i inventory.ini network_config.yml

Ensure you have the ansible package installed and SSH access to your network device.

9.Deploying Docker Compose Applications with Ansible:

You can use Ansible to automate the deployment of Docker Compose applications across multiple hosts. In this example, we'll deploy a simple web application.

1. Inventory File (inventory.ini):

[web_servers]
webserver1 ansible_host=192.168.1.2 ansible_user=ubuntu
webserver2 ansible_host=192.168.1.3 ansible_user=ubuntu

[database_server]
dbserver ansible_host=192.168.1.4 ansible_user=ubuntu


Replace the IP addresses and ansible_user values with your server details.

2. Playbook for Docker Compose (docker_deploy.yml):

---
- name: Deploy Docker Compose Application
  hosts: web_servers
  tasks:
    - name: Copy Docker Compose File
      copy:
        src: /path/to/docker-compose.yml
        dest: /home/ubuntu/docker-compose.yml
      become: yes

    - name: Deploy Docker Compose Application
      docker_compose:
        project_src: /home/ubuntu/
        project_name: myapp
        definition: /home/ubuntu/docker-compose.yml
        state: present
      become: yes

In this playbook, we copy the Docker Compose file to the remote servers and then deploy the application using Docker Compose.

3. Docker Compose File (docker-compose.yml):

version: '3'
services:
  web:
    image: nginx:latest
    ports:
      - "80:80"
  db:
    image: postgres:latest
    environment:
      POSTGRES_PASSWORD: mypassword

4. Run the Playbook:

ansible-playbook -i inventory.ini docker_deploy.yml

Ensure you have Ansible installed on your control machine and SSH access to the target servers. Adjust the paths and configurations according to your setup.

10.Securing Ansible Playbooks with Ansible Vault:

Ansible Vault is a tool for encrypting sensitive data within Ansible playbooks. Let's see how to secure a playbook using Ansible Vault.

1. Create an Encrypted File:

ansible-vault create mysecrets.yml

You will be prompted to set a vault password. Enter the password and add your sensitive data to the file.

2. Edit the Encrypted File:

ansible-vault edit mysecrets.yml

3. Playbook Using the Encrypted File (secure_playbook.yml):

---
- name: Secure Playbook Example
  hosts: localhost
  tasks:
    - name: Include Vaulted File
      include_vars: mysecrets.yml
    - name: Display Sensitive Data
      debug:
        var: secret_variable

4. Run the Playbook:

ansible-playbook secure_playbook.yml --ask-vault-pass

You'll be prompted for the vault password when running the playbook.

11.Dynamic Inventory in Ansible:

Dynamic inventory enables Ansible to use external scripts to access your inventory data. Let's create a simple dynamic inventory script for AWS.

1. Create an AWS Dynamic Inventory Script (aws_ec2_inventory.py):

#!/usr/bin/env python3

import boto3
import json

ec2 = boto3.client('ec2', region_name='us-east-1')
response = ec2.describe_instances()

inventory = {}

for instance in response['Reservations']:
    for i in instance['Instances']:
        inventory[i['InstanceId']] = {
            'ansible_host': i['PublicIpAddress'],
            'ansible_user': 'ec2-user',
            'ansible_ssh_private_key_file': '/path/to/key.pem'
        }

print(json.dumps(inventory))

Make sure to replace /path/to/key.pem with the path to your AWS SSH key.

2. Make the Script Executable:

chmod +x aws_ec2_inventory.py

3. Run the Dynamic Inventory Script:

./aws_ec2_inventory.py

This will generate a JSON output representing your AWS instances.

12.Integrating Ansible with Jenkins for Continuous Integration:

Integrating Ansible with Jenkins allows you to automate and schedule Ansible playbooks. Here's how to set up a Jenkins job to run Ansible playbooks.

1. Install Jenkins:

Follow the official Jenkins installation guide for your platform.

2. Install Jenkins Plugins:

Install the "Ansible" plugin from the Jenkins plugin manager.

3. Create a Jenkins Job:

Create a new Jenkins job and choose the "Build a free-style software project" option.

4. Configure the Job:

In the job configuration, add a build step to "Invoke Ansible Playbook." Specify your playbook and inventory file.

5. Build the Job:

Trigger the job manually or set up triggers as needed.

13.Ansible Best Practices for Role Organization:

Organizing your Ansible roles properly makes your playbook structure clean and maintainable. Here's an example of a well-organized Ansible role structure:

my_role/
|-- tasks/
|   |-- main.yml
|-- handlers/
|   |-- main.yml
|-- templates/
|-- files/
|-- defaults/
|   |-- main.yml
|-- vars/
|   |-- main.yml
|-- meta/
|   |-- main.yml

Each directory serves a specific purpose, such as tasks, handlers, templates, files, defaults, vars, and meta.

14.Deploying a Load Balancer with Ansible:

Deploying a load balancer with Ansible can automate the distribution of traffic. Here's an example of deploying an HAProxy load balancer.

1. Install HAProxy on the Load Balancer Host:

sudo apt-get install haproxy

2. Playbook for Deploying HAProxy (haproxy.yml):

---
- name: Deploy HAProxy Load Balancer
  hosts: load_balancer
  tasks:
    - name: Install HAProxy
      apt:
        name: haproxy
        state: present
      become: yes

    - name: Copy HAProxy Configuration
      template:
        src: haproxy.cfg.j2
        dest: /etc/haproxy/haproxy.cfg
      become: yes

    - name: Start HAProxy Service
      service:
        name: haproxy
        state: started
        enabled: yes
      become: yes

3. HAProxy Configuration Template (haproxy.cfg.j2):

global
    log /dev/log local0
    log /dev/log local1 notice

defaults
    log global
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http-in
    bind *:80
    default_backend servers

backend servers
    balance roundrobin
    server web1 192.168.1.2:80 check
    server web2 192.168.1.3:80 check


4. Run the Playbook:

ansible-playbook -i inventory.ini haproxy.yml

Ensure you have the inventory set up with your load balancer host and web server hosts.

15.Automating Database Deployments with Ansible:

Automating database deployments with Ansible involves defining your database configurations and using Ansible playbooks to manage them. Let's take MySQL as an example.

1. Install MySQL Server:

sudo apt-get update
sudo apt-get install mysql-server

2. Playbook for Database Deployment (mysql_deploy.yml):

---
- name: Deploy MySQL Database
  hosts: database_server
  tasks:
    - name: Install MySQL Python package
      apt:
        name: python-mysqldb
        state: present
      become: yes

    - name: Create MySQL Database
      mysql_db:
        name: mydb
        state: present
      become: yes

    - name: Create MySQL User
      mysql_user:
        name: myuser
        password: mypassword
        priv: 'mydb.*:ALL'
        state: present
      become: yes

3. Run the Playbook:

ansible-playbook -i inventory.ini mysql_deploy.yml

Ensure you have your inventory file set up with the database_server.

16.Integrating Ansible with AWS for Infrastructure as Code:

Integrating Ansible with AWS allows you to manage AWS resources programmatically. Here's an example of provisioning an EC2 instance using Ansible.

1. Install Boto3 (Python AWS SDK):

pip install boto3

2. Playbook for EC2 Instance Creation (aws_ec2_provision.yml):

---
- name: Provision EC2 Instance
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Launch EC2 Instance
      ec2:
        instance_type: t2.micro
        image: ami-12345678  # Replace with your desired AMI ID
        key_name: my-key
        region: us-east-1
        count: 1
        security_groups:
          - my-security-group
      register: ec2_instance

    - name: Add the new EC2 instance to host group
      add_host:
        hostname: "{{ item.public_ip }}"
        groupname: launched
      with_items: "{{ ec2_instance.instances }}"

3. Run the Playbook:

ansible-playbook aws_ec2_provision.yml

Ensure you've configured your AWS credentials using aws configure.

17.Automating Kubernetes Deployments with Ansible:

Automating Kubernetes deployments with Ansible can simplify the process of managing Kubernetes clusters and applications. Here's an example of deploying a simple Nginx application.

1. Install Kubernetes Modules for Ansible:

ansible-galaxy collection install community.kubernetes

2. Playbook for Deploying Nginx on Kubernetes (nginx_deploy.yml):

---
- name: Deploy Nginx on Kubernetes
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Create Namespace
      community.kubernetes.k8s_namespace:
        name: my-namespace
        state: present

    - name: Deploy Nginx
      community.kubernetes.k8s:
        state: present
        definition:
          apiVersion: apps/v1
          kind: Deployment
          metadata:
            name: nginx-deployment
            namespace: my-namespace
          spec:
            replicas: 2
            selector:
              matchLabels:
                app: nginx
            template:
              metadata:
                labels:
                  app: nginx
              spec:
                containers:
                - name: nginx
                  image: nginx
                  ports:
                  - containerPort: 80

    - name: Expose Nginx Service
      community.kubernetes.k8s:
        state: present
        definition:
          apiVersion: v1
          kind: Service
          metadata:
            name: nginx-service
            namespace: my-namespace
          spec:
            selector:
              app: nginx
            ports:
            - protocol: TCP
              port: 80
              targetPort: 80
        wait: yes

3. Run the Playbook:

ansible-playbook nginx_deploy.yml

Make sure you have a Kubernetes cluster configured.

18.Ansible Automation of Cloud Resources on Azure:

Ansible can automate the provisioning and management of Azure resources. Here's an example of provisioning an Azure Virtual Machine.

1. Install Azure SDK for Ansible:

pip install ansible[azure]

2. Playbook for Provisioning Azure VM (azure_vm_provision.yml):

---
- name: Provision Azure VM
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Create Azure Resource Group
      azure_rm_resourcegroup:
        name: myResourceGroup
        location: East US
        state: present

    - name: Create Azure Virtual Network
      azure_rm_virtualnetwork:
        resource_group: myResourceGroup
        name: myVnet
        address_prefixes: 10.0.0.0/16
        state: present

    - name: Create Azure Subnet
      azure_rm_subnet:
        resource_group: myResourceGroup
        virtual_network_name: myVnet
        name: mySubnet
        address_prefix: 10.0.0.0/24
        state: present

    - name: Create Azure Virtual Machine
      azure_rm_virtualmachine:
        resource_group: myResourceGroup
        name: myVM
        vm_size: Standard_DS2_v2
        admin_username: azureuser
        admin_password: "{{ my_password }}"
        image:
          offer: UbuntuServer
          publisher: Canonical
          sku: 18.04-LTS
        network_interfaces:
          - name: myVMnic
            primary: true
        os_disk_caching: ReadWrite
      vars_prompt:
        - name: "my_password"
          prompt: "Enter the admin password for the VM"
          private: yes

3. Run the Playbook:

ansible-playbook azure_vm_provision.yml

Ensure you've authenticated with Azure using az login.




















Labels: , ,

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home