Skip to content

Instantly share code, notes, and snippets.

@hrmsk66
Created September 20, 2024 02:40
Show Gist options
  • Save hrmsk66/db67d422e8196b5d2145cfa7beaf5565 to your computer and use it in GitHub Desktop.
Save hrmsk66/db67d422e8196b5d2145cfa7beaf5565 to your computer and use it in GitHub Desktop.

Updating AWS Security Group with Fastly IP Ranges Using Terraform

In this example, Fastly IP addresses are obtained using the fastly_ip_ranges data resource. Since this resource doesn't require an API token, no_auth is set to true in the provider configuration. The aws_security_groups data resource is used to retrieve the Security Group ID for the target fastly-src-ip, and then the aws_security_group_rule resource is used to update the rules.

This gist is a concise memo summarizing the key points from the following blog post: https://zenn.dev/jrsyo/articles/841c2d73d85a16

terraform {
  required_providers {
    fastly = {
      source  = "fastly/fastly"
      version = ">= 5.13.0"
    }
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

provider "fastly" {
  no_auth = true
  alias   = "no_auth"
}

data "fastly_ip_ranges" "fastly" {
  provider = fastly.no_auth
}

provider "aws" {
  # assume configurations are supplied via env variables
}

data "aws_security_groups" "fastly" {
  filter {
    name   = "group-name"
    values = ["fastly-src-ip"]
  }
}

resource "aws_security_group_rule" "fastly-http" {
  type              = "ingress"
  from_port         = 80
  to_port           = 80
  protocol          = "tcp"
  cidr_blocks       = data.fastly_ip_ranges.fastly.cidr_blocks
  ipv6_cidr_blocks  = data.fastly_ip_ranges.fastly.ipv6_cidr_blocks
  security_group_id = data.aws_security_groups.fastly.ids[0]
}

resource "aws_security_group_rule" "fastly-https" {
  type              = "ingress"
  from_port         = 443
  to_port           = 443
  protocol          = "tcp"
  cidr_blocks       = data.fastly_ip_ranges.fastly.cidr_blocks
  ipv6_cidr_blocks  = data.fastly_ip_ranges.fastly.ipv6_cidr_blocks
  security_group_id = data.aws_security_groups.fastly.ids[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment