Created
September 24, 2020 19:28
-
-
Save michaeljoy/60b586b95da922df339f1d2027dd70be to your computer and use it in GitHub Desktop.
Creating Dynamic AWS Cloudfront IP CIDR Block Based Security Groups in Terraform - terraform >= 0.13
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data "aws_ip_ranges" "cloudfront" { | |
services = ["cloudfront"] | |
} | |
locals { | |
tags = map("Environment", "my_environment") | |
cloudfront_ipv4_cidr_blocks = chunklist(data.aws_ip_ranges.cloudfront.cidr_blocks, 40) | |
cloudfront_ipv6_cidr_blocks = chunklist(data.aws_ip_ranges.cloudfront.ipv6_cidr_blocks, 40) | |
cloudfront_ipv4_cidr_blocks_map = { for i in local.cloudfront_ipv4_cidr_blocks : index(local.cloudfront_ipv4_cidr_blocks, i) => i } | |
cloudfront_ipv6_cidr_blocks_map = { for i in local.cloudfront_ipv6_cidr_blocks : index(local.cloudfront_ipv6_cidr_blocks, i) => i } | |
} | |
resource "aws_security_group" "cloudfront_ipv4" { | |
for_each = local.cloudfront_ipv4_cidr_blocks_map | |
name = "my-vpc-name-cf-sg-ipv4-${each.key}" | |
description = "my-vpc-name - Cloudfront Public Security Group - IPv4 - ${each.key}" | |
vpc_id = module.vpc.vpc_id | |
ingress { | |
from_port = 0 | |
to_port = 0 | |
protocol = -1 | |
cidr_blocks = each.value | |
} | |
egress { | |
from_port = 0 | |
to_port = 0 | |
protocol = -1 | |
cidr_blocks = ["0.0.0.0/0"] | |
ipv6_cidr_blocks = ["::/0"] | |
} | |
tags = merge( | |
local.tags, | |
map( | |
"Name", "my-vpc-name-cf-sg-ipv4-${each.key}", | |
"CreateDate", "${data.aws_ip_ranges.cloudfront.create_date}", | |
"SyncToken", "${data.aws_ip_ranges.cloudfront.sync_token}" | |
) | |
) | |
} | |
resource "aws_security_group" "cloudfront_ipv6" { | |
for_each = local.cloudfront_ipv6_cidr_blocks_map | |
name = "my-vpc-name-cf-sg-ipv6-${each.key}" | |
description = "my-vpc-name - Cloudfront Public Security Group - IPv6 - ${each.key}" | |
vpc_id = module.vpc.vpc_id | |
ingress { | |
from_port = 0 | |
to_port = 0 | |
protocol = -1 | |
ipv6_cidr_blocks = each.value | |
} | |
egress { | |
from_port = 0 | |
to_port = 0 | |
protocol = -1 | |
cidr_blocks = ["0.0.0.0/0"] | |
ipv6_cidr_blocks = ["::/0"] | |
} | |
tags = merge( | |
local.tags, | |
map( | |
"Name", "my-vpc-name-cf-sg-ipv6-${each.key}", | |
"CreateDate", "${data.aws_ip_ranges.cloudfront.create_date}", | |
"SyncToken", "${data.aws_ip_ranges.cloudfront.sync_token}" | |
) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment