terraform-training/NetworkContentDelivery/Exercise3/main.tf

123 lines
2.9 KiB
HCL

data "aws_availability_zones" "available" {}
locals {
PrivataSubnets = cidrsubnets(var.VpcCidr, 8, 8)
}
module "Vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.8.1"
name = var.VpcName
cidr = var.VpcCidr
azs = slice(data.aws_availability_zones.available.names, 0, 2)
private_subnets = local.PrivataSubnets
private_subnet_names = [for k, v in local.PrivataSubnets : "${var.VpcName}Private${k}"]
enable_dns_hostnames = true
enable_dns_support = true
enable_nat_gateway = false
enable_dhcp_options = true
dhcp_options_domain_name = "${var.VpcName}.aws"
}
module "VpcEndpoints" {
source = "terraform-aws-modules/vpc/aws//modules/vpc-endpoints"
version = "5.8.1"
vpc_id = module.Vpc.vpc_id
create_security_group = false
endpoints = {
s3 = {
service = "s3"
service_type = "Gateway"
route_table_ids = flatten([
module.Vpc.intra_route_table_ids, module.Vpc.private_route_table_ids, module.Vpc.public_route_table_ids
])
policy = data.aws_iam_policy_document.s3_endpoint_policy.json
tags = { Name = "S3VpcEp" }
},
dynamodb = {
service = "dynamodb"
service_type = "Gateway"
route_table_ids = flatten([
module.Vpc.intra_route_table_ids, module.Vpc.private_route_table_ids, module.Vpc.public_route_table_ids
])
policy = data.aws_iam_policy_document.dynamodb_endpoint_policy.json
tags = { Name = "DynamodbVpcEp" }
}
}
}
data "aws_iam_policy_document" "s3_endpoint_policy" {
statement {
effect = "Deny"
actions = ["s3:*"]
resources = ["*"]
principals {
type = "*"
identifiers = ["*"]
}
condition {
test = "StringNotEquals"
variable = "aws:sourceVpc"
values = [module.Vpc.vpc_id]
}
}
}
data "aws_iam_policy_document" "dynamodb_endpoint_policy" {
statement {
effect = "Deny"
actions = ["dynamodb:*"]
resources = ["*"]
principals {
type = "*"
identifiers = ["*"]
}
condition {
test = "StringNotEquals"
variable = "aws:sourceVpc"
values = [module.Vpc.vpc_id]
}
}
}
data "http" "CloudflareIps" {
url = "https://api.cloudflare.com/client/v4/ips"
request_headers = {
Accept = "application/json"
}
}
resource "aws_ec2_managed_prefix_list" "pl1" {
name = "CloudflareIpRanges"
address_family = "IPv4"
max_entries = 20
dynamic "entry" {
for_each = jsondecode(data.http.CloudflareIps.response_body)["result"]["ipv4_cidrs"]
content {
cidr = entry.value
description = "Cloudflare IP"
}
}
}
module "CloudflareSg" {
source = "../../Modules/Compute/security_group"
description = "Cloudflare Ip Ranges"
egress = {
}
ingress = {
r1 = "tcp,443,443,${aws_ec2_managed_prefix_list.pl1.id},Cloudflare Prefix List"
}
name = "cloudflare-ips"
vpc-id = module.Vpc.vpc_id
}