Automating Cloud Infrastructure with Ansible
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?
- Agentless: Uses SSH, no software to install on nodes
- Simple: YAML-based playbooks are easy to read
- Idempotent: Actions can be run multiple times safely
- Extensible: Huge library of modules for AWS, Azure, GCP, etc.
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:
tasks/: Main list of tasks to be executedhandlers/: Handlers, which may be used within or outside this roletemplates/: Templates which the role deploysfiles/: Files which the role deploysvars/: Variables for the 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
- Use version control: Git for all playbooks locally
- Naming tasks: Always give meaningful names to tasks
- Check Mode: Use
--checkto test changes (dry run) - Roles: Group tasks into reusable roles
- Linting: Use
ansible-lintto 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.