Terraform - Create Security Groups for AWS Cloudfront IP Ranges

The below terraform configuration is used to create multiple security groups to allow all inbound traffic from AWS Cloudfront locations.

Multiple security groups are required because there are more than 50 AWS Cloudfront IP ranges and the default maximum number of rules for an SG is 50.

The error returned if you try to create a single security group with all of the cloudfront IPs is Error authorizing security group ingress rules: RulesPerSecurityGroupLimitExceeded: The maximum number of rules per security group has been reached.

Terraform Config for Cloudfront SGs

provider "aws" {
  access_key = "YOUR ACCESS KEY"
  secret_key = "YOUR SECRET KEY"
  region     = "YOUR AWS REGION"

resource "aws_vpc" "main" {
  cidr_block = ""

data "external" "cloudfront_ip_ranges" {
  program = ["bash", ""]

locals {
  cloudfront_ips      = ["${split("\n", data.external.cloudfront_ip_ranges.result.cloudfront_ips)}"]
  cloudfront_sg_count = "${ceil((length(local.cloudfront_ips) * 1.0) / 50)}"

resource "aws_security_group" "cloudfront" {
  name        = "cloudfront-security-group-${count.index + 1}"
  description = "Cloudfront Security Group"
  vpc_id      = "${}"
  count       = "${local.cloudfront_sg_count}"

  # allow all traffic from cloudfront ip ranges
  ingress {
    from_port   = 0
    to_port     = 65535
    protocol    = 6
    cidr_blocks = ["${slice(local.cloudfront_ips, (count.index * 50), min((count.index * 50) + 50, length(local.cloudfront_ips)))}"]

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = [""]

  tags {
    Name = "Cloudfront SG ${count.index + 1}"

Shell script for fetching Cloudfront IP ranges

This shell script is run by the external provider in the terraform config, the script fetches the current IP ranges for AWS Cloudfront and formats the results using the jq JSON processor.


IPS=$(curl -s | jq -r '.prefixes[] | select(.service == "CLOUDFRONT") | .ip_prefix')
jq -n --arg ips "$IPS" '{"cloudfront_ips":$ips}'


Need Some Terraform Help?

Search fiverr to find help quickly from experienced Terraform developers.

Exclusive Semrush Special Offer

FREE 14-day PRO trial to Semrush is available to visitors of this blog. Check your website health quickly and easily with the Semrush all-in-one site auditing tool, eliminate technical SEO issues and optimize your website's speed and performance.

Supported by