dippynark
dippynark

Reputation: 3003

How to find AWS Lambda nameservers using Terraform?

I am using a Lambda function to connect to a service in my VPC and it needs to resolve an internal address, therefore I need to allow connections from Lambda to hit the my internal nameservers, but don't want to allow UDP to 0.0.0.0/0 on port 53.

How can I find out the IP addresses of the nameservers Lambda will use so I can put them into my security groups rules?

Upvotes: 1

Views: 247

Answers (1)

Mark B
Mark B

Reputation: 200850

In your VPC, the DNS server will be the the base of the VPC network range plus two. For example if your VPC CIDR block is 10.0.0.0/24 then the Amazon will reserve 10.0.0.2 for the DNS server. This is documented here.

You could also just allow outbound connections to your VPC CIDR block instead of having to open up 0.0.0.0/0. Although you should note that a Lambda function inside a VPC does not have a public IP address, so it can't access anything outside of the VPC without going through a NAT gateway anyway.


To calculate this in Terraform, let's assume you have a reference to the VPC somehow, like so:

data "aws_vpc" "my_vpc" {
  id = "${var.vpc_id}"
}

Then you can use Terraform's cidrhost() function to find the IP address, like this:

locals {
  dns_server = cidrhost(data.aws_vpc.my_vpc.cidr_block, 2)
}

resource "aws_security_group_rule" "allow_dns" {
  type            = "outbound"
  from_port       = 53
  to_port         = 53
  protocol        = "udp"
  cidr_blocks     = "${local.dns_server}/32"

  security_group_id = "sg-123456"
}

Upvotes: 1

Related Questions