Terraform script that creates an S3 bucket, a VPC with two subnets (one public and one private), and a CloudFront distribution to access the S3 bucket

 




Terraform script that creates an S3 bucket, a VPC with two subnets (one public and one private), and a CloudFront distribution to access the S3 bucket

Assuming below (It might change according to your scenario)

This script creates an S3 bucket named "example-bucket", a VPC with a CIDR block of "10.0.0.0/16", and two subnets - one public and one private. The public subnet is in the "us-west-2a" availability zone, has a CIDR block of "10.0.1.0/24" and allows public IP to be mapped when instances are launched. 

The private subnet is in the "us-west-2b" availability zone, has a CIDR block of "10.0.2.0/24" and does not allow public IP to be mapped when instances are launched.

It also creates a CloudFront distribution that uses the S3 bucket as its origin and allows only GET and HEAD methods.

It also sets the viewer certificate to use the CloudFront default certificate, this can be replaced by a custom certificate if needed.





provider "aws" {

  region = "us-west-2"

}


resource "aws_s3_bucket" "example_bucket" {

  bucket = "example-bucket"

}


resource "aws_vpc" "example_vpc" {

  cidr_block = "10.0.0.0/16"

}


resource "aws_subnet" "example_public_subnet" {

  vpc_id            = aws_vpc.example_vpc.id

  cidr_block        = "10.0.1.0/24"

  availability_zone = "us-west-2a"

  map_public_ip_on_launch = true

}


resource "aws_subnet" "example_private_subnet" {

  vpc_id            = aws_vpc.example_vpc.id

  cidr_block        = "10.0.2.0/24"

  availability_zone = "us-west-2b"

  map_public_ip_on_launch = false

}


resource "aws_cloudfront_distribution" "example_distribution" {

origin {

domain_name = aws_s3_bucket.example_bucket.bucket_domain_name

origin_id = "S3-example-bucket"

}


default_cache_behavior {

target_origin_id = "S3-example-bucket"

allowed_methods = ["GET", "HEAD"]

cached_methods = ["GET", "HEAD"]

forwarded_values {

query_string = false

}

}


viewer_certificate {

cloudfront_default_certificate = true

}

}



##############################################
Github link will come soon ..................

Post a Comment

Previous Post Next Post

Contact Form