Terraform Cost Optimization for AWS - Reduce Your Cloud Bill
Practical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity. Step-by-step guide with code examples and ...
Guides
How to manage AWS IAM roles, policies, and permissions with Terraform following security best practices. Step-by-step guide with code examples and best pract...
IAM is the foundation of AWS security. Getting it right in Terraform means following the principle of least privilege and making permissions auditable.
# Role with trust policy
resource "aws_iam_role" "lambda" {
name = "lambda-execution-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}]
})
}
# Managed policy attachment
resource "aws_iam_role_policy_attachment" "lambda_basic" {
role = aws_iam_role.lambda.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
# Custom inline policy
resource "aws_iam_role_policy" "s3_access" {
name = "s3-read-access"
role = aws_iam_role.lambda.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["s3:GetObject", "s3:ListBucket"]
Resource = [
aws_s3_bucket.data.arn,
"${aws_s3_bucket.data.arn}/*"
]
}]
})
}For complex policies, use the aws_iam_policy_document data source:
data "aws_iam_policy_document" "s3_policy" {
statement {
effect = "Allow"
actions = ["s3:GetObject"]
resources = ["${aws_s3_bucket.data.arn}/*"]
condition {
test = "StringEquals"
variable = "aws:RequestedRegion"
values = ["us-east-1"]
}
}
}
resource "aws_iam_policy" "s3_read" {
name = "s3-read-policy"
policy = data.aws_iam_policy_document.s3_policy.json
}resource "aws_iam_role" "cross_account" {
name = "cross-account-deploy"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = {
AWS = "arn:aws:iam::123456789012:root"
}
Action = "sts:AssumeRole"
Condition = {
StringEquals = {
"sts:ExternalId" = var.external_id
}
}
}]
})
}jsonencode() — over heredoc JSON for policy documents"Resource": "*" is almost always too broadPractical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity. Step-by-step guide with code examples and ...
Best practices for managing secrets, passwords, and sensitive data in Terraform configurations. Step-by-step guide with code examples and best practices for ...
Production-ready Terraform AWS VPC configuration with public/private subnets, NAT gateway, and security groups. Step-by-step guide with code examples and bes...
Fix the Terraform AssumeRole AccessDenied error for cross-account deployments. Covers trust policies, STS permissions, MFA, and external ID configuration.