← Back to Blog
Automation

Automating Cloud Infrastructure with Ansible

December 15, 202313 min readAmol Tribhuwan

Automating Cloud Infrastructure with Ansible

Ansible is a powerful, agentless automation tool that excels at configuration management and application deployment. This guide covers how to use Ansible to manage cloud infrastructure effectively.

Why Ansible?

Basic Structure

ansible/
├── inventory/
│   └── hosts.ini
├── roles/
│   ├── common/
│   └── webserver/
├── playbooks/
│   └── site.yml
└── ansible.cfg

Inventory Management

Static Inventory

[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com

Dynamic Inventory (AWS)

Use the aws_ec2 plugin to automatically discover instances:

# inventory/aws_ec2.yml
plugin: aws_ec2
regions:
  - us-east-1
filters:
  tag:Role: webserver
keyed_groups:
  - key: tags.Environment
    prefix: env

Writing Playbooks

Example: Configure a Web Server

---
- name: Configure Web Servers
  hosts: webservers
  become: true
  
  vars:
    http_port: 80
    max_clients: 200

  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present
        update_cache: yes

    - name: Copy configuration
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify:
        - Restart Nginx

    - name: Ensure Nginx is running
      service:
        name: nginx
        state: started
        enabled: yes

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

Using Roles

Roles allow you to reuse and share automation code.

Structure of a role:

Usage

- hosts: webservers
  roles:
    - common
    - webserver

Ansible Vault

Secure sensitive data like passwords and keys.

# Create encrypted file
ansible-vault create vars/secrets.yml

# Edit encrypted file
ansible-vault edit vars/secrets.yml

# Run playbook with vault password
ansible-playbook site.yml --ask-vault-pass

Best Practices

  1. Use version control: Git for all playbooks locally
  2. Naming tasks: Always give meaningful names to tasks
  3. Check Mode: Use --check to test changes (dry run)
  4. Roles: Group tasks into reusable roles
  5. Linting: Use ansible-lint to enforce standards

CI/CD Integration

Run Ansible in GitHub Actions:

- name: Run Ansible Playbook
  uses: dawidd6/action-ansible-playbook@v2
  with:
    playbook: playbooks/site.yml
    directory: ./ansible
    key: ${{ secrets.SSH_PRIVATE_KEY }}
    inventory: |
      [webservers]
      web.example.com

Conclusion

Ansible simplifies complex infrastructure management. By combining it with Terraform (for provisioning) and Jenkins/GitHub Actions (for CI/CD), you can build a completely automated DevOps pipeline.

#Ansible#Automation#Configuration Management