- Create a provider.tf file and add your provider i.e AWS
- Also, add the required access keys so that you can access you aws console
provider.tf
provider "aws" {
region = "ap-south-1"
access_key = var.access_key
secret_key = var.secret_key
}
- We are not using the hardcode variables in provider file
- So, we need to declare variable name and there types in variable file ( optional: default value )
- To store the variable value we will be using tfvars file
variable.tf
variable "access_key" {
type = string
}
variable "secret_key" {
type = string
}
variable "bucketname" {
type = string
}
terraform.tfvars
access_key = "yourkey"
secret_key = "yourkey"
bucketname = "testingbucket0511"
- Create a main.tf file which will be having all the resources and there configurations
create s3 bucket
resource "aws_s3_bucket" "mybucket" {
bucket = var.bucketname
}
change its ownership and make it public accessible
resource "aws_s3_bucket_ownership_controls" "example" {
bucket = aws_s3_bucket.mybucket.id
rule {
object_ownership = "BucketOwnerPreferred"
}
}
resource "aws_s3_bucket_public_access_block" "example" {
bucket = aws_s3_bucket.mybucket.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}
enable access control to public-read for s3
resource "aws_s3_bucket_acl" "example" {
depends_on = [
aws_s3_bucket_ownership_controls.example,
aws_s3_bucket_public_access_block.example,
]
bucket = aws_s3_bucket.mybucket.id
acl = "public-read"
}
create s3 objects index.html, error.html and profile.png which is required for website hosting
resource "aws_s3_object" "index" {
bucket = aws_s3_bucket.mybucket.id
key = "index.html"
source = "index.html"
acl = "public-read"
content_type = "text/html"
}
resource "aws_s3_object" "error" {
bucket = aws_s3_bucket.mybucket.id
key = "error.html"
source = "error.html"
acl = "public-read"
content_type = "text/html"
}
resource "aws_s3_object" "profile" {
bucket = aws_s3_bucket.mybucket.id
key = "profile.png"
source = "profile.png"
acl = "public-read"
}
add s3 website resource and its configuration
resource "aws_s3_bucket_website_configuration" "website" {
bucket = aws_s3_bucket.mybucket.id
index_document {
suffix = "index.html"
}
error_document {
key = "error.html"
}
depends_on = [ aws_s3_bucket_acl.example ]
}
- terraform init - to initialize terraform backend
- terraform plan - which creates an execution plan, that lets you preview the changes that Terraform plans to make to your infrastructure
- terraform apply - which executes the actions proposed in a terraform plan
- check the bucket with its objects
- check for the website link in properties section
- click the link and check your resume
- you can use terraform destroy as it is a convenient way to destroy all remote objects managed by a particular Terraform configuration.