Day 27 of 100: CI/CD with Terraform & Ansible – Automating Infrastructure Deployment on Azure

Day 27 of 100: CI/CD with Terraform & Ansible – Automating Infrastructure Deployment on Azure

Welcome to Day 27 of the 100-Day Challenge!

Today, we focus on using Terraform & Ansible to automate infrastructure deployment in Microsoft Azure with a CI/CD pipeline.

?? Why Automate Infrastructure Deployment?

Automating infrastructure deployment is essential for modern IT and cloud environments, providing numerous benefits in terms of speed, reliability, scalability, and cost-efficiency.

Below are key reasons why organizations should automate their infrastructure deployment:


1. Speed and Efficiency

  • Faster Deployment: Automation reduces the time required to provision and configure infrastructure, allowing teams to deploy environments in minutes rather than hours or days.
  • Continuous Delivery & Integration (CI/CD): Enables automated testing and deployment pipelines, ensuring faster development cycles.
  • Reduced Manual Effort: Eliminates repetitive manual tasks, allowing engineers to focus on innovation and strategic work.


2. Consistency and Standardization

  • Eliminates Human Errors: Manual configurations are prone to mistakes, leading to inconsistent environments. Automation ensures all deployments follow the same process and best practices.
  • Version Control: Infrastructure as Code (IaC) tools like Terraform, Ansible, and AWS CloudFormation enable versioning, rollback, and tracking of infrastructure changes.
  • Uniformity Across Environments: Ensures that development, testing, staging, and production environments are identical, reducing deployment issues.


3. Scalability and Flexibility

  • Dynamic Scaling: Automated infrastructure allows systems to scale up or down based on demand, optimizing resource utilization.
  • Multi-Cloud and Hybrid Cloud Support: Automates deployments across AWS, Azure, Google Cloud, and on-premises data centers with minimal effort.
  • Rapid Expansion: Businesses can quickly expand operations without the need for extensive manual setup.


4. Cost Savings

  • Optimized Resource Utilization: Automation ensures resources are provisioned only when needed, reducing waste.
  • Reduces Operational Costs: Less need for manual intervention means fewer staff hours spent on infrastructure management.
  • Predictable Costs: Infrastructure as Code (IaC) allows organizations to estimate costs accurately before deployment.


5. Improved Security and Compliance

  • Automated Security Policies: Security controls and compliance policies can be embedded in deployment scripts, ensuring consistent enforcement.
  • Audit and Compliance Tracking: Infrastructure automation logs every change, making compliance audits easier.
  • Reduced Attack Surface: Automating patching and updates helps keep infrastructure secure.


6. Disaster Recovery and Reliability

  • Automatic Backups and Failover: Automated scripts can regularly back up infrastructure and enable failover mechanisms.
  • Rapid Recovery: Infrastructure can be rebuilt quickly in case of failure, minimizing downtime.
  • Self-Healing Systems: Monitoring tools can trigger automatic remediation steps when failures occur.


7. DevOps and Collaboration

  • Better Team Collaboration: Automation fosters collaboration between development and operations teams by providing a shared framework.
  • Infrastructure as Code (IaC): Code-based infrastructure allows teams to collaborate using version-controlled repositories like Git.
  • Improved Developer Productivity: Developers can self-provision infrastructure, reducing dependency on operations teams.


8. Future-Proofing and Innovation

  • Supports Modern Workflows: Automates the deployment of microservices, Kubernetes clusters, and serverless applications.
  • Enables Experimentation: Teams can spin up and tear down test environments quickly without worrying about costs or effort.
  • Adapts to New Technologies: Infrastructure automation frameworks continuously evolve, supporting emerging cloud and on-prem technologies.


By combining Terraform (Provisioning) and Ansible (Configuration Management) with a CI/CD pipeline, we ensure that:

?? Every deployment is fast, consistent, and repeatable

?? Infrastructure changes are automated & version-controlled

?? Teams collaborate better with Infrastructure as Code (IaC)


Terraform & Ansible on Azure: The Perfect Combo

? Terraform: Defines and provisions Azure resources like VMs, networks, and storage

? Ansible: Configures VMs by installing software, setting up services, and managing dependencies

? CI/CD Pipeline: Ensures automated deployments with GitHub Actions


Use Case: Deploying a Scalable Web App on Azure

Imagine you are part of a DevOps team at a company that frequently needs new Azure environments. Instead of manually setting up resources, you:

? Use Terraform to provision Azure Virtual Machines, Storage Accounts, and Networking ? Use Ansible to configure VMs (installing Nginx, setting up firewall rules, etc.)

? Automate the entire process using GitHub Actions


?? Step-by-Step: CI/CD Pipeline for Azure with Terraform & Ansible

?? Step 1: Set Up Your GitHub Repository

1?? Create a GitHub repo

2?? Organize your directory:

?? terraform/
   ├── main.tf
   ├── variables.tf
   ├── outputs.tf
?? ansible/
   ├── playbook.yml
   ├── inventory.ini
?? .github/workflows/
   ├── ci-cd.yml
        

?? Step 2: Define Infrastructure in Terraform for Azure

Inside terraform/main.tf:

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "rg" {
  name     = "myResourceGroup"
  location = "East US"
}

resource "azurerm_virtual_network" "vnet" {
  name                = "myVNet"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  address_space       = ["10.0.0.0/16"]
}

resource "azurerm_subnet" "subnet" {
  name                 = "mySubnet"
  resource_group_name  = azurerm_resource_group.rg.name
  virtual_network_name = azurerm_virtual_network.vnet.name
  address_prefixes     = ["10.0.1.0/24"]
}

resource "azurerm_public_ip" "pip" {
  name                = "myPublicIP"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  allocation_method   = "Static"
}

resource "azurerm_network_interface" "nic" {
  name                = "myNIC"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.subnet.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.pip.id
  }
}

resource "azurerm_linux_virtual_machine" "vm" {
  name                = "myVM"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  size               = "Standard_B1s"
  admin_username      = "adminuser"

  network_interface_ids = [azurerm_network_interface.nic.id]

  admin_ssh_key {
    username   = "adminuser"
    public_key = file("~/.ssh/id_rsa.pub")  # Replace with your SSH public key
  }

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  source_image_reference {
    publisher = "Canonical"
    offer     = "UbuntuServer"
    sku       = "18.04-LTS"
    version   = "latest"
  }
}
        

This Terraform configuration:

? Creates an Azure Resource Group

? Provisions a Virtual Network & Subnet

? Creates a Public IP & Network Interface

? Deploys an Ubuntu Virtual Machine


?? Step 3: Write an Ansible Playbook to Configure the VM

Inside ansible/playbook.yml:

- name: Configure Azure VM
  hosts: all
  become: yes
  tasks:
    - name: Update package lists
      apt:
        update_cache: yes

    - name: Install Nginx
      apt:
        name: nginx
        state: present

    - name: Start Nginx
      service:
        name: nginx
        state: started
        

This playbook installs and starts Nginx on the Azure VM.


?? Step 4: Automate Everything with GitHub Actions

Inside .github/workflows/ci-cd.yml:

name: CI/CD for Azure with Terraform & Ansible

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v1
      
      - name: Terraform Init & Apply
        run: |
          cd terraform
          terraform init
          terraform apply -auto-approve

      - name: Setup Ansible & Run Playbook
        run: |
          sudo apt update && sudo apt install -y ansible
          ansible-playbook -i ansible/inventory.ini ansible/playbook.yml
        

This automates the entire process whenever code is pushed to the main branch.


Final Thoughts

By integrating Terraform, Ansible, and CI/CD in Azure, you’ve:

? Eliminated manual infrastructure provisioning

? Ensured repeatability & consistency ??

? Automated end-to-end infrastructure deployment


?? Next Up: Day 28 – Bicep: Infrastructure as Code for Azure Tomorrow,

we explore Bicep, Microsoft’s native Infrastructure as Code (IaC) tool that’s an alternative to Terraform. Stay tuned!

Stay tuned for Day 28 – Bicep: Infrastructure as Code for Azure

If you found this useful, follow Shruthi Chikkela for more deep-dive DevOps content!

?? Follow Shruthi Chikkela for daily insights ??

Subscribe to my 100-day DevOps challenge for expert-level content

#DevOps #CloudComputing #Azure #Terraform #Ansible #InfrastructureAsCode #CI_CD #Automation #CloudAutomation #AzureDevOps #Learnwithshruthi



?? Ishita Sah

?Helping Startups Grow with No-Code Solutions?

3 天前

Automating infrastructure deployment truly revolutionizes cloud management. Have you found this approach reduces human error significantly?

回复

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

Shruthi Chikkela的更多文章