Tuesday, April 16, 2024

50 Essential Terraform Scripts for AWS: A Comprehensive Guide to Automating Your Infrastructure

50 Essential Terraform Scripts for AWS: A Comprehensive Guide to Automating Your Infrastructure


1-10: EC2 Instances

1. Basic EC2 Instance

provider "aws" { region = "us-east-1" } resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" tags = { Name = "BasicEC2" } }

2. EC2 with Auto Scaling

resource "aws_autoscaling_group" "example" { launch_configuration = aws_launch_configuration.example.id min_size = 1 max_size = 10 vpc_zone_identifier = ["subnet-123456"] }

3. EC2 with EBS Volume

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"

  root_block_device {
    volume_size = "8"
  }
}

4. EC2 with Elastic IP

resource "aws_eip" "example" { instance = aws_instance.example.id }

5. EC2 in a Placement Group

resource "aws_placement_group" "example" {
  name     = "example"
  strategy = "cluster"
}

resource "aws_instance" "example" {
  ami              = "ami-123456"
  instance_type    = "m5.large"
  placement_group  = aws_placement_group.example.id
}

6. EC2 with Specific Key Pair

resource "aws_key_pair" "example" {
  key_name   = "example_key"
  public_key = "ssh-rsa AAA..."
}

resource "aws_instance" "example" {
  ami        = "ami-123456"
  instance_type = "t2.micro"
  key_name   = aws_key_pair.example.key_name
}

7. EC2 with User Data

resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" user_data = <<-EOF #!/bin/bash echo "Hello World" > /var/www/html/index.html EOF }

8. EC2 with Multiple Network Interfaces

resource "aws_network_interface" "example" { subnet_id = "subnet-123456" private_ips = ["10.0.1.50"] } resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" network_interface { network_interface_id = aws_network_interface.example.id device_index = 1 } }

9. EC2 with Monitoring Enabled

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
  monitoring    = true
}

10. EC2 with Spot Pricing

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
  spot_price    = "0.03"
}


11-20: S3 Buckets

11. Basic S3 Bucket

resource "aws_s3_bucket" "example" { bucket = "example-bucket" }

12. S3 Bucket with Versioning

resource "aws_s3_bucket" "example" { bucket = "example-bucket" versioning { enabled = true } }

13. S3 Bucket with Server-Side Encryption

resource "aws_s3_bucket" "example" {
  bucket = "example-bucket"

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"
      }
    }
  }
}

14. S3 Bucket with Logging

resource "aws_s3_bucket" "log_bucket" { bucket = "example-log-bucket" } resource "aws_s3_bucket" "example" { bucket = "example-bucket" logging { target_bucket = aws_s3_bucket.log_bucket.id target_prefix = "log/" } }

15. S3 Bucket with Lifecycle Rule

resource "aws_s3_bucket" "example" { bucket = "example-bucket" lifecycle_rule { id = "log" enabled = true transition { days = 30 storage_class = "GLACIER" } expiration { days = 365 } } }

16. S3 Bucket with Public Access Block

resource "aws_s3_bucket" "example" { bucket = "example-bucket" public_access_block { block_public_acls = true ignore_public_acls = true block_public_policy = true restrict_public_buckets = true } }

17. S3 Bucket with Cross-Region Replication

resource "aws_s3_bucket" "example" { bucket = "example-bucket" region = "us-west-1" replication_configuration { role = aws_iam_role.replication.arn rules { id = "replicate" status = "Enabled" destination { bucket = aws_s3_bucket.destination.arn storage_class = "STANDARD" } } } } resource "aws_s3_bucket" "destination" { bucket = "example-destination-bucket" region = "us-east-1" }

18. S3 Bucket with Object Lock

resource "aws_s3_bucket" "example" { bucket = "example-bucket" object_lock_configuration { object_lock_enabled = "Enabled" rule { default_retention { mode = "GOVERNANCE" days = 90 } } } }

19. S3 Bucket with Transfer Acceleration

resource "aws_s3_bucket" "example" { bucket = "example-bucket" acceleration_status = "Enabled" }

20. S3 Bucket with Website Configuration

resource "aws_s3_bucket" "example" { bucket = "example-bucket" website { index_document = "index.html" error_document = "error.html" } }

21-30: IAM Roles

21. Basic IAM Role for EC2

resource "aws_iam_role" "example_ec2" { name = "example_ec2_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "ec2.amazonaws.com" } }, ] }) }

22. IAM Role with Attached Policy

resource "aws_iam_role" "example" { name = "example_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "lambda.amazonaws.com" } }, ] }) } resource "aws_iam_role_policy_attachment" "example_attach" { role = aws_iam_role.example.name policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" }

23. IAM Role for S3 Access

resource "aws_iam_role" "example_s3" {
  name = "example_s3_role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "ec2.amazonaws.com"
        }
      },
    ]
  })
}

resource "aws_iam_policy" "s3_access" {
  name        = "s3AccessPolicy"
  description = "Policy that allows access to S3"

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "s3:GetObject",
          "s3:PutObject"
        ]
        Effect = "Allow"
        Resource = [
          "arn:aws:s3:::example-bucket/*"
        ]
      },
    ]
  })
}

resource "aws_iam_role_policy_attachment" "s3_access_attach" {
  role       = aws_iam_role.example_s3.name
  policy_arn = aws_iam_policy.s3_access.arn
}

24. IAM Role with Inline Policy

resource "aws_iam_role" "example_inline" { name = "example_inline_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "lambda.amazonaws.com" } }, ] }) } resource "aws_iam_role_policy" "inline_policy" { name = "exampleInlinePolicy" role = aws_iam_role.example_inline.id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "logs:CreateLogGroup" Effect = "Allow" Resource = "arn:aws:logs:us-west-2:123456789012:*" }, { Action = [ "logs:CreateLogStream", "logs:PutLogEvents" ] Effect = "Allow" Resource = [ "arn:aws:logs:us-west-2:123456789012:log-group:/aws/lambda/example:*" ] }, ] }) }

25. IAM Role for API Gateway Execution

resource "aws_iam_role" "api_exec_role" {
  name = "api_exec_role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "apigateway.amazonaws.com"
        }
      },
    ]
  })
}

resource "aws_iam_role_policy_attachment" "api_exec_attach" {
  role       = aws_iam_role.api_exec_role.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs"
}

26. IAM Role for RDS Access

resource "aws_iam_role" "rds_access_role" { name = "rds_access_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "rds.amazonaws.com" } }, ] }) } resource "aws_iam_role_policy" "rds_policy" { role = aws_iam_role.rds_access_role.id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "s3:GetObject", Effect = "Allow", Resource = "arn:aws:s3:::mydb-backup-bucket/*" }, ] }) }


27. IAM Role for CloudWatch Logs Access

resource "aws_iam_role" "cw_logs_role" {
  name = "cw_logs_role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "logs.amazonaws.com"
        }
      },
    ]
  })
}

resource "aws_iam_policy" "cw_logs_policy" {
  name        = "cwLogsPolicy"
  description = "Policy for CloudWatch Logs access"

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "logs:CreateLogGroup",
          "logs:CreateLogStream",
          "logs:PutLogEvents",
          "logs:DescribeLogStreams"
        ],
        Effect = "Allow",
        Resource = "arn:aws:logs:*:*:*"
      },
    ]
  })
}

resource "aws_iam_role_policy_attachment" "cw_logs_attach" {
  role       = aws_iam_role.cw_logs_role.name
  policy_arn = aws_iam_policy.cw_logs_policy.arn
}

28. IAM Role for Elastic Beanstalk Environment

resource "aws_iam_role" "eb_role" { name = "eb_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "elasticbeanstalk.amazonaws.com" } }, ] }) } resource "aws_iam_role_policy" "eb_policy" { role = aws_iam_role.eb_role.id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = [ "ec2:Describe*", "elasticloadbalancing:Describe*", "autoscaling:Describe*", "s3:GetObject" ], Effect = "Allow", Resource = "*" }, ] }) }

29. IAM Role for DynamoDB Access

resource "aws_iam_role" "dynamodb_role" { name = "dynamodb_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "dynamodb.amazonaws.com" } }, ] }) } resource "aws_iam_policy" "dynamodb_policy" { name = "DynamoDBAccessPolicy" description = "Policy that allows access to DynamoDB" policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = [ "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem" ], Effect = "Allow", Resource = "arn:aws:dynamodb:us-west-2:123456789012:table/MyTable" }, ] }) } resource "aws_iam_role_policy_attachment" "dynamodb_attach" { role = aws_iam_role.dynamodb_role.name policy_arn = aws_iam_policy.dynamodb_policy.arn }

30. IAM Role for EKS Cluster

resource "aws_iam_role" "eks_role" { name = "eks_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "eks.amazonaws.com" } }, ] }) } resource "aws_iam_policy" "eks_policy" { name = "EKSClusterPolicy" description = "Policy for EKS cluster management" policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = [ "eks:CreateCluster", "eks:DeleteCluster", "eks:DescribeCluster", "eks:ListClusters", "eks:UpdateClusterVersion", "eks:UpdateClusterConfig" ], Effect = "Allow", Resource = "*" }, ] }) } resource "aws_iam_role_policy_attachment" "eks_attach" { role = aws_iam_role.eks_role.name policy_arn = aws_iam_policy.eks_policy.arn }

31-40: RDS and DynamoDB Instances

31. Basic RDS Instance

resource "aws_db_instance" "example_rds" { allocated_storage = 20 engine = "mysql" engine_version = "5.7" instance_class = "db.t2.micro" name = "mydb" username = "user" password = "pass1234" }

32. Multi-AZ RDS for High Availability

resource "aws_db_instance" "example_rds_multi_az" { allocated_storage = 20 engine = "mysql" engine_version = "5.7" instance_class = "db.t2.micro" multi_az = true name = "mydb" username = "user" password = "pass1234" }

33. RDS with Read Replica

resource "aws_db_instance" "example_rds_replica" {
  replicate_source_db = aws_db_instance.example_rds.id
  instance_class      = "db.t2.micro"
}

34. Encrypted RDS Instance

resource "aws_db_instance" "example_rds_encrypted" { allocated_storage = 20 engine = "mysql" engine_version = "5.7" instance_class = "db.t2.micro" storage_encrypted = true name = "mydb" username = "user" password = "pass1234" }

35. DynamoDB Table with Auto Scaling

resource "aws_dynamodb_table" "example_dynamodb" {
  name           = "example_table"
  billing_mode   = "PROVISIONED"
  read_capacity  = 5
  write_capacity = 5
  hash_key       = "id"

  attribute {
    name = "id"
    type = "S"
  }
}

36. RDS Instance with Backup Configuration

resource "aws_db_instance" "example_rds_backup" { allocated_storage = 20 engine = "mysql" engine_version = "5.7" instance_class = "db.t2.micro" backup_retention_period = 7 name = "mydb" username = "user" password = "pass1234" }

37. DynamoDB Table for Session Management

resource "aws_dynamodb_table" "example_dynamodb_sessions" {
  name           = "sessions_table"
  billing_mode   = "PROVISIONED"
  read_capacity  = 10
  write_capacity = 10
  hash_key       = "session_id"

  attribute {
    name = "session_id"
    type = "S"
  }
}

38. RDS Instance with Parameter Group

resource "aws_db_parameter_group" "example_param_group" { name = "example_parameter_group" family = "mysql5.7" parameter { name = "character_set_server" value = "utf8mb4" } } resource "aws_db_instance" "example_rds_param" { allocated_storage = 20 engine = "mysql" engine_version = "5.7" instance_class = "db.t2.micro" parameter_group_name = aws_db_parameter_group.example_param_group.name name = "mydb" username = "user" password = "pass1234" }

39. DynamoDB Table with Stream Enabled

resource "aws_dynamodb_table" "example_dynamodb_streams" {
  name           = "example_streams_table"
  billing_mode   = "PROVISIONED"
  read_capacity  = 10
  write_capacity = 10
  hash_key       = "id"

  attribute {
    name = "id"
    type = "S"
  }

  stream_enabled   = true
  stream_view_type = "NEW_AND_OLD_IMAGES"
}

40. RDS Instance with Enhanced Monitoring

resource "aws_db_instance" "example_rds_monitoring" { allocated_storage = 20 engine = "mysql" engine_version = "5.7" instance_class = "db.t2.micro" monitoring_interval = 30 monitoring_role_arn = aws_iam_role.example_monitoring_role.arn name = "mydb" username = "user" password = "pass1234" }

41-50: VPC and Networking

41. Basic VPC Creation

resource "aws_vpc" "example_vpc" { cidr_block = "10.0.0.0/16" }


42. Subnet in a VPC

resource "aws_subnet" "example_subnet" {
  vpc_id     = aws_vpc.example_vpc.id
  cidr_block = "10.0.1.0/24"
}

43. Internet Gateway for a VPC

resource "aws_internet_gateway" "example_igw" { vpc_id = aws_vpc.example_vpc.id }

44. NAT Gateway for Private Subnet

resource "aws_eip" "example_eip" {
  vpc = true
}

resource "aws_nat_gateway" "example_nat" {
  subnet_id     = aws_subnet.example_subnet.id
  allocation_id = aws_eip.example_eip.id
}

45. VPC Peering Connection

resource "aws_vpc_peering_connection" "example_peer" { peer_vpc_id = aws_vpc.peer_vpc.id vpc_id = aws_vpc.example_vpc.id }

46. Security Group with Custom Rules

resource "aws_security_group" "example_sg" {
  vpc_id = aws_vpc.example_vpc.id

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

47. Route Table for Subnet

resource "aws_route_table" "example_rt" { vpc_id = aws_vpc.example_vpc.id route { cidr_block = "0.0.0.0/0" gateway_id = aws_internet_gateway.example_igw.id } }


48. Elastic Load Balancer (ELB) in VPC

resource "aws_elb" "example_elb" {
  name               = "example-elb"
  availability_zones = ["us-west-2a", "us-west-2b"]

  listener {
    instance_port     = 80
    instance_protocol = "HTTP"
    lb_port           = 80
    lb_protocol       = "HTTP"
  }
}

49. VPN Connection to a VPC

resource "aws_vpn_connection" "example_vpn" { customer_gateway_id = aws_customer_gateway.example_cg.id type = "ipsec.1" vpn_gateway_id = aws_vpn_gateway.example_vgw.id }

50. AWS Direct Connect for a VPC

resource "aws_dx_connection" "example_dx" {
  name      = "example-dx-conn"
  bandwidth = "1Gbps"
  location  = "EqDC2"
}


No comments:

Post a Comment