Published: July 16 2018

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 = "10.0.0.0/16"
}

data "external" "cloudfront_ip_ranges" {
  program = ["bash", "fetch-cloudfront-ips.sh"]
}

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      = "${aws_vpc.main.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 = ["0.0.0.0/0"]
  }

  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.

#!/bin/bash

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

 


Need Some Terraform Help?

Search fiverr for freelance Terraform developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by