Bird
Raised Fist0
Terraformcloud~10 mins

Integration testing strategies in Terraform - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Integration testing in Terraform helps ensure that multiple infrastructure components work together correctly. It checks that resources connect and behave as expected when combined, preventing issues before deployment.
When you want to verify that a network and a virtual machine can communicate properly after deployment.
When you need to confirm that a database and an application server are correctly linked and accessible.
When you want to test that security groups and firewall rules allow the right traffic between services.
When you want to validate that a load balancer distributes traffic correctly to backend instances.
When you want to ensure that infrastructure changes do not break existing resource dependencies.
Config File - main.tf
main.tf
terraform {
  required_version = ">= 1.3.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_vpc" "test_vpc" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "test-vpc"
  }
}

resource "aws_subnet" "test_subnet" {
  vpc_id            = aws_vpc.test_vpc.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"
  tags = {
    Name = "test-subnet"
  }
}

resource "aws_security_group" "test_sg" {
  name        = "test-sg"
  description = "Allow SSH and HTTP"
  vpc_id      = aws_vpc.test_vpc.id

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    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 = "test-sg"
  }
}

resource "aws_instance" "test_instance" {
  ami                    = "ami-0c94855ba95c71c99"
  instance_type          = "t2.micro"
  subnet_id              = aws_subnet.test_subnet.id
  vpc_security_group_ids = [aws_security_group.test_sg.id]
  tags = {
    Name = "test-instance"
  }
}

This Terraform file creates a simple AWS setup for integration testing:

  • VPC: A private network for resources.
  • Subnet: A smaller network segment inside the VPC.
  • Security Group: Rules to allow SSH and HTTP traffic.
  • Instance: A virtual machine inside the subnet using the security group.

This setup allows testing connectivity and resource interaction.

Commands
Initializes Terraform in the current directory, downloading required providers and preparing the environment.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding hashicorp/aws versions matching "~> 4.0"... - Installing hashicorp/aws v4.60.0... - Installed hashicorp/aws v4.60.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
Shows the planned changes Terraform will make to create the infrastructure defined in the config file.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_vpc.test_vpc will be created + resource "aws_vpc" "test_vpc" { + cidr_block = "10.0.0.0/16" + id = (known after apply) + tags = { + "Name" = "test-vpc" } } # aws_subnet.test_subnet will be created + resource "aws_subnet" "test_subnet" { + cidr_block = "10.0.1.0/24" + id = (known after apply) + vpc_id = (known after apply) + availability_zone = "us-east-1a" + tags = { + "Name" = "test-subnet" } } # aws_security_group.test_sg will be created + resource "aws_security_group" "test_sg" { + description = "Allow SSH and HTTP" + id = (known after apply) + name = "test-sg" + tags = { + "Name" = "test-sg" } + vpc_id = (known after apply) } # aws_instance.test_instance will be created + resource "aws_instance" "test_instance" { + ami = "ami-0c94855ba95c71c99" + id = (known after apply) + instance_type = "t2.micro" + subnet_id = (known after apply) + vpc_security_group_ids = [ + (known after apply), ] + tags = { + "Name" = "test-instance" } } Plan: 4 to add, 0 to change, 0 to destroy. ───────────────────────────────────────────────────────────────────────────── Note: You didn't specify an "-out" parameter to save this plan, so Terraform can't guarantee that exactly these actions will be performed if "terraform apply" is subsequently run.
Applies the planned changes to create the infrastructure without asking for confirmation.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_vpc.test_vpc: Creating... aws_vpc.test_vpc: Creation complete after 3s [id=vpc-0a1b2c3d4e5f67890] aws_subnet.test_subnet: Creating... aws_subnet.test_subnet: Creation complete after 2s [id=subnet-0a1b2c3d4e5f67890] aws_security_group.test_sg: Creating... aws_security_group.test_sg: Creation complete after 1s [id=sg-0a1b2c3d4e5f67890] aws_instance.test_instance: Creating... aws_instance.test_instance: Still creating... [10s elapsed] aws_instance.test_instance: Creation complete after 15s [id=i-0a1b2c3d4e5f67890] Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
-auto-approve - Skips manual approval to apply changes immediately
Displays the outputs defined in the Terraform state, useful to verify resource attributes after deployment.
Terminal
terraform output
Expected OutputExpected
No output (command runs silently)
Key Concept

If you remember nothing else from this pattern, remember: integration testing in Terraform means deploying multiple resources together and verifying they work as expected in combination.

Common Mistakes
Running terraform apply without terraform init first
Terraform needs to download providers and initialize the working directory before applying changes.
Always run terraform init before terraform apply in a new or changed directory.
Not verifying the plan output before applying
Skipping terraform plan can cause unexpected changes or resource destruction without warning.
Always run terraform plan and review changes before applying.
Not cleaning up test resources after integration testing
Leaving test infrastructure running can incur unnecessary costs and clutter your environment.
Use terraform destroy to remove test resources when done.
Summary
Initialize Terraform with 'terraform init' to prepare the environment.
Use 'terraform plan' to preview infrastructure changes before applying.
Apply infrastructure changes with 'terraform apply -auto-approve' to deploy resources for integration testing.

Practice

(1/5)
1. What is the main goal of integration testing in Terraform?
easy
A. To create user interfaces for cloud services
B. To check if multiple cloud resources work together correctly
C. To deploy resources without any errors
D. To write Terraform code faster

Solution

  1. Step 1: Understand integration testing purpose

    Integration testing focuses on verifying that different parts work together as expected.
  2. Step 2: Apply this to Terraform

    In Terraform, it means checking if cloud resources connect and interact properly.
  3. Final Answer:

    To check if multiple cloud resources work together correctly -> Option B
  4. Quick Check:

    Integration testing = check resource cooperation [OK]
Hint: Integration testing checks resource cooperation, not code speed [OK]
Common Mistakes:
  • Confusing integration testing with deployment
  • Thinking it tests only single resources
  • Assuming it improves coding speed
2. Which Terraform feature helps share data between resources during integration testing?
easy
A. Terraform variables
B. Terraform modules
C. Terraform providers
D. Terraform outputs

Solution

  1. Step 1: Identify data sharing methods in Terraform

    Terraform outputs expose values from one resource to be used elsewhere.
  2. Step 2: Match with integration testing needs

    Outputs allow tests to verify connections by passing resource info between them.
  3. Final Answer:

    Terraform outputs -> Option D
  4. Quick Check:

    Outputs share data between resources [OK]
Hint: Outputs expose resource data for testing connections [OK]
Common Mistakes:
  • Confusing variables with outputs
  • Thinking providers share data
  • Assuming modules handle data passing
3. Given this Terraform snippet, what will output "db_endpoint" show after apply?
resource "aws_db_instance" "db" {
  identifier = "mydb"
  endpoint   = "mydb.example.com"
}

output "db_endpoint" {
  value = aws_db_instance.db.endpoint
}
medium
A. "mydb"
B. "aws_db_instance.db.endpoint"
C. An error because endpoint is not a valid attribute
D. "mydb.example.com"

Solution

  1. Step 1: Understand resource attributes

    The resource aws_db_instance.db does not have a valid attribute named endpoint accessible directly; endpoint is an attribute returned by AWS after creation but is accessed differently.
  2. Step 2: Check output value

    Since endpoint is not a valid attribute in this context, Terraform will raise an error when trying to output it.
  3. Final Answer:

    An error because endpoint is not a valid attribute -> Option C
  4. Quick Check:

    Outputting invalid attribute causes error [OK]
Hint: Not all resource attributes are directly accessible; check docs [OK]
Common Mistakes:
  • Thinking output shows attribute value without validation
  • Assuming endpoint is valid attribute
  • Confusing identifier with endpoint
4. You wrote a Terraform test to check resource connections but it fails with a dependency error. What is the likely cause?
medium
A. Missing explicit resource dependency using depends_on
B. Using outputs instead of variables
C. Applying in the wrong cloud region
D. Incorrect provider version

Solution

  1. Step 1: Identify cause of dependency errors

    Terraform needs explicit dependencies to know resource creation order.
  2. Step 2: Check for missing depends_on

    If depends_on is missing, Terraform may try to create resources in wrong order causing errors.
  3. Final Answer:

    Missing explicit resource dependency using depends_on -> Option A
  4. Quick Check:

    Dependency errors = missing depends_on [OK]
Hint: Add depends_on to fix resource creation order errors [OK]
Common Mistakes:
  • Blaming outputs for dependency errors
  • Ignoring resource creation order
  • Assuming provider version causes dependencies
5. You want to run integration tests on Terraform resources without affecting production. Which strategy is best?
hard
A. Use isolated test environments with separate state files
B. Run tests directly on production resources
C. Disable Terraform state locking during tests
D. Use the same state file but different workspaces

Solution

  1. Step 1: Understand risk of testing on production

    Testing on production can cause unintended changes or downtime.
  2. Step 2: Choose isolated environments

    Using separate environments and state files keeps tests safe and independent from production.
  3. Final Answer:

    Use isolated test environments with separate state files -> Option A
  4. Quick Check:

    Isolated environments prevent production impact [OK]
Hint: Always isolate test environments to protect production [OK]
Common Mistakes:
  • Testing directly on production
  • Disabling state locking unsafely
  • Using same state file for tests and prod