This task aims to implement infrastructure testing using Terratest and InSpec for Terraform-managed infrastructure. The infrastructure will be provisioned in AWS, and automated tests will validate the deployment for security, compliance, and functionality before it is promoted to production.
provider "aws" {
region = "us-east-1"
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "subnet1" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
map_public_ip_on_launch = true
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
subnet_id = aws_subnet.subnet1.id
tags = {
Name = "Terraform-Test-Instance"
}
}
terraform init
terraform validate
terraform plan
terraform apply -auto-approve
Terratest is used to write test cases in Go to validate Terraform provisioning.
go mod init terraform-test
go get github.com/gruntwork-io/terratest/modules/terraform
package test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/gruntwork-io/terratest/modules/terraform"
)
func TestTerraformInfrastructure(t *testing.T) {
terraformOptions := &terraform.Options{
TerraformDir: "../terraform",
}
defer terraform.Destroy(t, terraformOptions)
terraform.InitAndApply(t, terraformOptions)
instanceID := terraform.Output(t, terraformOptions, "instance_id")
assert.NotEmpty(t, instanceID, "EC2 Instance ID should not be empty")
}
go test -v test_terraform.go
InSpec is used to ensure that the infrastructure complies with security and compliance best practices.
gem install inspec
inspec init profile aws-security-checks
cd aws-security-checks
control 'aws-instance-check' do
impact 1.0
title 'Ensure AWS EC2 instance is secure'
describe aws_ec2_instance(name: 'Terraform-Test-Instance') do
it { should exist }
its('state') { should eq 'running' }
its('instance_type') { should eq 't2.micro' }
its('image_id') { should eq 'ami-0c55b159cbfafe1f0' }
end
end
inspec exec aws-security-checks -t aws://
Infrastructure tests (Terratest & InSpec) should run automatically when a change is pushed.
pipeline {
agent any
environment {
AWS_DEFAULT_REGION = 'us-east-1'
}
stages {
stage('Checkout') {
steps {
git 'https://github.com/user/repo.git'
}
}
stage('Terraform Init & Plan') {
steps {
sh 'terraform init'
sh 'terraform plan'
}
}
stage('Terraform Apply') {
steps {
sh 'terraform apply -auto-approve'
}
}
stage('Run Terratest') {
steps {
sh 'go test -v test_terraform.go'
}
}
stage('Run InSpec Tests') {
steps {
sh 'inspec exec aws-security-checks -t aws://'
}
}
stage('Destroy Infrastructure') {
steps {
sh 'terraform destroy -auto-approve'
}
}
}
}
This project ensures robust, secure, and tested infrastructure deployment in AWS.