Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Change a Terraform-Managed Security Group Outside Terraform, Detect the Drift with plan -refresh-only, and Fix It by Reverting or by Updating the Code

Intermediate35 minTerraform 1.6+ · AWS CLI v2 · An AWS account

Course: DevOps · Chapter 42: Terraform Drift and Troubleshooting · Lesson: 42.1 Drift: when AWS no longer matches the code

Chapter 42 explains drift, TF_LOG and the common errors; this lab creates drift on purpose and fixes it.

Chala mitrano! Ratri koNitari console madhe port ughadla, ani code la mahitach nahi. Aaj drift pakduya.

Suppose we are…

Suppose we are on an Infosys support team. During a night incident an engineer opened port 22 to the world "just for five minutes" and forgot. The Terraform code still says the port is closed. That gap between code and cloud is drift.

In this lab we create a security group with Terraform, make two changes outside Terraform, see them in the plan, and fix them properly.

Goal of this lab

By the end you will have:

  • A security group created by Terraform in the default VPC.
  • Two manual changes (an extra SSH rule and a tag) seen in terraform plan.
  • The extra rule removed by Terraform, and the tag decision moved into code.

What you need

  • Terraform 1.6 or newer (terraform version).
  • AWS CLI v2 signed in to your own AWS account with an IAM user or SSO role that may create these resources (aws sts get-caller-identity works). Never use the root user, and never paste access keys into .tf files.
  • Region Mumbai (ap-south-1) is used; change region if you prefer another.
  • 35 minutes.

Cost and cleanup

A security group is free. Small charges are possible even on the free tier. Finish the lab in one sitting and always run the Clean up part at the end.

Part 1: Create the security group

  1. Create a folder and main.tf:

    main.tf

    terraform {
      required_version = ">= 1.6"
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.0"
        }
      }
    }
    
    provider "aws" {
      region = "ap-south-1"
    }
    
    data "aws_vpc" "default" {
      default = true
    }
    
    resource "aws_security_group" "web" {
      name        = "drift-lab-web"
      description = "HTTP only"
      vpc_id      = data.aws_vpc.default.id
    
      ingress {
        description = "HTTP"
        from_port   = 80
        to_port     = 80
        protocol    = "tcp"
        cidr_blocks = ["0.0.0.0/0"]
      }
    
      egress {
        from_port   = 0
        to_port     = 0
        protocol    = "-1"
        cidr_blocks = ["0.0.0.0/0"]
      }
    
      tags = { Name = "drift-lab-web", owner = "platform" }
    }
    
    output "sg_id" {
      value = aws_security_group.web.id
    }
    
    mkdir tf-drift-lab && cd tf-drift-lab
    

    This lab uses inline ingress blocks on purpose: Terraform then owns the full rule list and reports any extra rule as drift.

  2. Apply:

    terraform init
    terraform apply
    

    What you should see: Apply complete! Resources: 1 added and the sg_id output.

Part 2: Make drift outside Terraform

  1. Add an SSH rule open to the world and change a tag with the CLI (this plays the "night incident"):

    SG=$(terraform output -raw sg_id)
    aws ec2 authorize-security-group-ingress --group-id $SG --protocol tcp --port 22 --cidr 0.0.0.0/0
    aws ec2 create-tags --resources $SG --tags Key=owner,Value=night-shift
    
  2. See the drift without planning any change:

    terraform plan -refresh-only
    

    What you should see: Objects have changed outside of Terraform with the new port 22 rule and owner = "night-shift".

  3. See what a normal plan wants to do:

    terraform plan
    

    What you should see: ~ update in-place that removes the port 22 rule and sets owner back to platform; Plan: 0 to add, 1 to change, 0 to destroy.

Part 3: Fix it the right way

  1. Decide per change. The open SSH rule is wrong: let Terraform remove it. The tag change is a real ownership change: put it in code. Edit main.tf so owner = "night-shift", then:

    terraform plan
    

    What you should see: the plan now only removes the port 22 rule.

  2. Apply and confirm:

    terraform apply
    aws ec2 describe-security-groups --group-ids $SG --query "SecurityGroups[0].IpPermissions[].FromPort"
    terraform plan
    

    What you should see: [ 80 ] only, then No changes.

Clean up: destroy everything

  1. Delete everything this lab created. Type yes when asked:

    terraform destroy
    

    What you should see: Destroy complete! Resources: 1 destroyed.

Ravindra Bagale's Tip

Run terraform plan on a schedule (a nightly pipeline) and alert when it is not "No changes". Drift found the same night is a small fix; drift found in six months is an outage.

Common mistakes

MistakeWhat happensFix
Running terraform apply -refresh-only without reading itThe bad SSH rule is accepted into stateRead the refresh-only plan; fix the code or revert first
Fixing drift by clicking in the console againCode and cloud still differChange code, then apply
Mixing inline rules and separate rule resources on one groupRules fight each other on every applyUse one style per security group

Self-check checklist

0 of 5 done

Try-at-home challenge

Run a plan with TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform plan, search the log for DescribeSecurityGroups, then unset both variables and delete the log (it can contain sensitive details).

Samajla ka? Code is the truth; drift is a question you answer on purpose. Aata pudhe jaauya real AWS guides.