Lab_Final_terraform
Lab_Final_terraform
Lab Overview
Learning Objectives
Directory Structure
variable "region" {
default = "ap-southeast-2"
}
2. Define Global Variables
variable "instance_type" {
description = "Type of the EC2 instance"
default = "t2.micro"
}
variable "lambda_function_name" {
description = "Name of the Lambda function"
default = "shutdown-ec2-instance"
}
tags = {
Name = var.instance_name
}
}
output "instance_id" {
value = aws_instance.instance.id
}
output "public_ip" {
value = aws_instance.instance.public_ip
}
modules/ec2/variables.tf
variable "instance_type" {
description = "Type of the EC2 instance"
}
environment {
variables = {
INSTANCE_ID = var.instance_id
}
}
}
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Effect = "Allow",
Principal = {
Service = "lambda.amazonaws.com"
},
Action = "sts:AssumeRole"
}
]
})
}
modules/lambda/variables.tf
variable "instance_id" {
description = "ID of the EC2 instance to shut down"
}
modules/lambda/scripts/shutdown_instance.py
python
-
import boto3
import os
try:
response =
ec2_client.stop_instances(InstanceIds=[instance_id])
return {
"statusCode": 200,
"body": f"Shutting down instance {instance_id}"
}
except Exception as e:
return {
"statusCode": 500,
"body": f"Error: {str(e)}"
}
modules/cloudwatch/variables.tf
variable "lambda_arn" {
description = "ARN of the Lambda function"
}
6. Main Orchestration
main.tf
module "lambda" {
source = "./modules/lambda"
lambda_function_name = var.lambda_function_name
instance_id = module.ec2.instance_id
}
module "cloudwatch" {
source = "./modules/cloudwatch"
lambda_function_name = var.lambda_function_name
lambda_arn = module.lambda.shutdown_lambda_arn
}
7. Debugging Tips
1. Initialize Terraform:
Your code is here...
-
terraform init
2. Plan the Deployment:
Your code is here...
-
terraform plan