Open In App

AWS CloudFront Using Terraform

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

CloudFront is a generally used service provided by AWS. CloudFront utilizes edge areas to load extra website data. Suppose you launch your website using EC2. So regularly you would store all the website code as well as website data(i.e images, recordings, and so on.) in a similar EC2 machine. Be that as it may, this isn’t very much an optimized arrangement, and latency is high. This is because EC2 is a territorial help and can’t utilize edge areas. What we can do rather is make a S3 container and store all the site information on it. S3 is a worldwide help so we are involving CloudFront for S3 we can utilize edge locations to load our website information quickly with reduced latency. AWS CloudFront is a content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to customers globally with low latency and high transfer speeds. In this article, we’ll explore how to provision and manage CloudFront distributions using Terraform, a popular Infrastructure as Code (IaC) tool.

AWS CloudFront and Terraform

AWS CloudFront

  • Content Delivery Network(CDN): A distributed network of servers that speeds up the conveyance of web content, including static and dynamic resources, to clients internationally, decreasing latency and improving execution.
  • Distribution: A collection of worldwide disseminated edge areas that cooperate to work content to end-users. Every Distribution has a one of a kind CloudFront domain name.
  • Origin: The source of the files that CloudFront delivers to clients. This can be an Amazon S3 container, an HTTP server, or other web servers.
  • Edge Area: The physical location where content is stored and served to clients. These are decisively positioned all over the planet to guarantee low-inactivity access.
  • Viewer Certificate: An SSL/TLS certificate used to scramble the association between CloudFront and end-users. It tends to be the default CloudFront certificate or a custom uploaded transferred to AWS Identity and Access Management (IAM).

Terraform

  • Infrastructure as Code (IaC): A technique for overseeing and provisioning framework utilizing code instead of manual cycles. Terraform is an open-source IaC tool that permits clients to characterize and automate the deployment of Infrastructure.
  • Provider: In Terraform, a provider is liable for overseeing assets in a particular cloud or service. For AWS, the provider is “aws.” without a provider we cannot create an infrastructure by using Terraform
  • Resource: A block in Terraform setup that defines a particular infrastructure part (e.g., EC2 instance, S3 bucket, CloudFront distribution).
  • Variable: A parameter in Terraform that allows you to enter values dynamically, giving adaptability to your infrastructure definitions.
  • Module: An assortment of Terraform configuration files and scripts gathered to make reusable and shareable parts.
  • State: The record of the present status of the foundation overseen by Terraform. The state document is fundamental for Terraform to understand the current infrastructure and track changes after some time.

Step-By-Step Process for AWS CloudFront Using Terraform

Step 1: Launch EC2 instance with Amazon Linux2 Kernel 5.10(AMI) along with port numbers set SSH – 22, HTTP 8o and select storage t3.micro.

EC2 instance

Step 2: Now connect with git bash terminal by using SSH Client

SSH Client

Step 3: Now install terraform from official site of hashicorp or follow below commands

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
sudo yum -y install terraform

sudo yum install

Step 4: Now create a file for terraform configuration to write a script with .tf extension by using following command

vi <filename.tf>

Now write a terraform script to create AWS CloudFront

Provider section

This section specifies the AWS provider and sets the desired region to “us-east-1”. Replace it with your preferred AWS region.

provider "aws" {
region = "us-east-1"
}

Creating S3 bucket

Here, you define an S3 bucket named “my-s3-bucket”. The acl parameter sets the bucket access control list to “private”. Additionally, the website block is used to configure the S3 bucket as a static website, specifying the index_document and error_document.

resource "aws_s3_bucket" "my_bucket" {
bucket = "bucket" # Replace with your desired S3 bucket name
acl = "private" # Replace with your desired private or public
website {
index_document = "index.html"
error_document = "error.html"
}
}

Terraform script

Defining AWS CloudFront Distribution

resource "aws_cloudfront_distribution" "my_distribution" {
origin {
domain_name = aws_s3_bucket.my_bucket.website_endpoint
origin_id = "s3-origin"
s3_origin_config {
origin_access_identity = aws_cloudfront_origin_access_identity.my_oai.cloudfront_access_identity_path
}
}
default_cache_behavior {
target_origin_id = "s3-origin"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"]
cached_methods = ["GET", "HEAD"]
min_ttl = 0
default_ttl = 3600
max_ttl = 86400
forwarded_values {
query_string = false
headers = ["*"]
cookies {
forward = "all"
}
}
}
restrictions {
geo_restriction {
restriction_type = "none"
}
}
viewer_certificate {
cloudfront_default_certificate = true
}
enabled = true
is_ipv6_enabled = true
default_root_object = "index.html"
}

Creating AWS CloudFront origin access

resource "aws_cloudfront_origin_access_identity" "my_oai" {
comment = "CloudFront OAI for S3 bucket"
}

Creating AWS CloudFront origin access

Step 5: Now execute terraform commands

terraform init
terraform fmt
terraform validate
terraform plan

terraform init

terraform validate

terraform apply --auto-approve

terraform apply

AWS services created by Terraform Infrastructure

Cloudfront distributions

After completion of creating a infrastructure, we can destroy whole infrastructure with a single command

terraform destroy --auto-approve

Terraform Destroy

Conclusion

AWS CloudFront upsets content conveyance by offering a versatile, secure, and elite execution answer for circulating web content worldwide. By utilizing an organization of edge areas decisively situated all over the planet, CloudFront lessens inertness and speeds up the conveyance of sites, APIs, streaming media, and other computerized resources for end-clients. This upgraded presentation further develops client experience as well as lifts site rankings in web search tools and increments client commitment.

CloudFront gives vigorous security features, including SSL/TLS encryption, access control strategies, and DDoS assurance, defending substance against unapproved access and digital dangers. The assistance’s adaptability guarantees consistent treatment of differing traffic volumes, empowering organizations to oblige quick development and variances sought after without compromising execution.

AWS CloudFront enables associations to convey satisfied with speed, dependability, and security, changing the manner in which they cooperate with clients and clients around the world. Whether serving static sites or dynamic applications, CloudFront’s creative elements and worldwide arrive at make it a key device for enhancing content conveyance and making business success.

CloudFront Using Terraform – FAQ’s

What is the principal motivation behind AWS CloudFront?

AWS CloudFront is a Content Delivery Network (CDN) service designed to accelerate the delivery of websites, APIs, video content, and other web resources globally. It enhances performance and reduces latency, providing an improved experience for users worldwide.

How does AWS CloudFront further develop website execution?

CloudFront caches content at edge locations distributed globally, bringing it closer to end-users and reducing the distance and time required to deliver content. This results in faster loading times and an enhanced user experience.

Could I at any point utilize AWS CloudFront with dynamic substance?

Indeed, AWS CloudFront supports dynamic content delivery by allowing you to configure behavior based on HTTP headers, cookies, query strings, and more. Additionally, you can integrate CloudFront with AWS Lambda@Edge for advanced customization.

Is AWS CloudFront secure?

AWS CloudFront provides several security features, including SSL/TLS encryption, access control policies, origin access identities (OAIs) for S3 buckets, and integration with AWS Web Application Firewall (WAF). These features help protect your content and applications from unauthorized access and attacks.

How does AWS CloudFront deal with adaptability?

AWS CloudFront is highly scalable and automatically scales resources based on demand. It can handle sudden traffic spikes and fluctuations in customer demand without compromising performance. Additionally, CloudFront seamlessly integrates with other AWS services for added scalability and flexibility.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads