provider "aws"{
region = "us-east-1"
}
resource "aws_s3_bucket" "website_bucket" {
bucket = "${var.name_domain}.${var.root_domain}"
acl = "private"
website {
index_document = "index.html"
error_document = "error.html"
}
tags = {
Name = "${var.Customer}"
Environment = "${var.Environment}"
}
region = "us-east-1"
}
data "aws_s3_bucket" "get_s3_zone" {
bucket = "${var.name_domain}.${var.root_domain}"
depends_on = ["aws_s3_bucket.website_bucket"]
}
data "aws_route53_zone" "getZone" {
count = "${var.hostedZone == "yes" ? 1 : 0}"
name = "${var.root_domain}"
private_zone = false
}
resource "aws_route53_zone" "website_zone" {
count = "${var.hostedZone == "yes" ? 0 : 1}"
name = "${var.root_domain}"
tags = {
Name = "${var.Customer}"
Environment = "${var.Environment}"
}
}
data "aws_acm_certificate" "fetch_certificate_arn" {
domain = "${var.certificate}"
statuses = ["ISSUED"]
most_recent = true
}
resource "aws_cloudfront_distribution" "website_cloudfront" {
origin {
domain_name = "${aws_s3_bucket.website_bucket.website_endpoint}"
origin_id = "${var.Customer}_S3_origin"
custom_origin_config {
origin_protocol_policy = "http-only"
https_port = 443
http_port = 80
origin_ssl_protocols = ["TLSv1", "SSLv3"]
}
}
enabled = true
aliases = ["${var.name_domain}.${var.root_domain}"]
price_class = "PriceClass_200"
retain_on_delete = true
default_cache_behavior {
allowed_methods = [ "GET", "HEAD"]
cached_methods = [ "GET", "HEAD" ]
target_origin_id = "${var.Customer}_S3_origin"
forwarded_values {
query_string = false
cookies {
forward = "none"
}
}
viewer_protocol_policy = "redirect-to-https"
min_ttl = 0
default_ttl = 3600
max_ttl = 86400
}
viewer_certificate {
acm_certificate_arn = "${data.aws_acm_certificate.fetch_certificate_arn.arn}"
ssl_support_method = "sni-only"
minimum_protocol_version = "TLSv1.1_2016"
}
restrictions {
geo_restriction {
restriction_type = "none"
}
}
depends_on = ["aws_s3_bucket.website_bucket"]
}
resource "aws_route53_record" "www"{
zone_id = "${var.hostedZone == "no" ? join("", aws_route53_zone.website_zone.*.zone_id) : join ("",data.aws_route53_zone.getZone.*.zone_id)}"
name = "${var.name_domain}.${var.root_domain}"
type = "A"
alias {
name = "${aws_cloudfront_distribution.website_cloudfront.domain_name}"
zone_id = "${aws_cloudfront_distribution.website_cloudfront.hosted_zone_id}"
evaluate_target_health = "false"
}
depends_on = [aws_route53_zone.website_zone]
}
output "website_endpoint" {
value = aws_s3_bucket.website_bucket.website_endpoint
}