π main.tf
.
βββ main.tf
βββ terraform {} β write providers in it
βββ provider {} β auth / region
βββ resource {} β resources to create (S3, VPC, EC2)
βββ data {} β Read-only info from cloud e.g ami_id
βββ variable {} β inputs
βββ output {} β outputs
π§ Data Source
β Read-only lookups β Fetch info, donβt create
Example:
data "aws_ami" "latest" {
most_recent = true
owners = ["amazon"]
}π¦ Lambda Packaging (archive_file)
Structure
.
βββ main.tf
βββ lambda/
βββ handler.py
Package Code β ZIP
data "archive_file" "lambda_zip" {
type = "zip"
source_dir = "${path.module}/lambda"
output_path = "${path.module}/lambda.zip"
}Use ZIP in Lambda
resource "aws_lambda_function" "my_lambda" {
function_name = "demo-lambda"
role = aws_iam_role.lambda_role.arn
handler = "handler.lambda_handler"
runtime = "python3.12"
filename = data.archive_file.lambda_zip.output_path
source_code_hash = data.archive_file.lambda_zip.output_base64sha256
}π¨ State File (terraform.tfstate)
β Terraformβs memory
β Stores IDs, attributes
Must be:
- Protected
- Not edited manually
- Stored remotely (S3 + DynamoDB lock recommended)
πͺ Variables
β Avoid hardcoding
variable "region" {
default = "us-east-1"
}π« Outputs
β Print useful info
output "vpc_id" {
value = aws_vpc.main.id
}