Data Source

Terraform is capabale of connecting to external APIs and querying them. AWS exposes it's services through a REST API. Terraform AWS provider is capable of querying this REST API and make the results available to the infrastructure code.

In the below example I am going to query for the CIDRs avaiable in a region and assign them in a security group.

First things first, let's create a file with the name providers.tf,

provider "aws" {
  region = var.AWS_REGION
}

Create a file with the name vars.tf,

variable "AWS_REGION" {
  default = "eu-west-1"
}

Create a file with the name securitygroup.tf,

data "aws_ip_ranges" "european_ec2" {
  regions  = ["eu-west-1", "eu-central-1"]
  services = ["ec2"]
}

resource "aws_security_group" "from_europe" {
  name = "from_europe"

  ingress {
    from_port   = "443"
    to_port     = "443"
    protocol    = "tcp"
    cidr_blocks = slice(data.aws_ip_ranges.european_ec2.cidr_blocks, 0, 50)
  }
  tags = {
    CreateDate = data.aws_ip_ranges.european_ec2.create_date
    SyncToken  = data.aws_ip_ranges.european_ec2.sync_token
  }
}

In here, first I define the data source that querys the aws_ip_ranges which returns the IP ranges and I filter the returned values to contain only what's available in european_ec2. Next I define the security group itself. This includes a CIDR block defined using the values returned by the data source. Finally, I've added some tags in there again by consuming the values returned by data source.

Initialize the providers,

Apply the changes,

Don't forget to clean up once experiments are done,

Last updated

Was this helpful?