Using Terraform for every region in a given account, find all VPCs and for each VPC enable flow logs

232 views
Skip to first unread message

Prateek Rastogi

unread,
Oct 1, 2018, 12:33:08 PM10/1/18
to Terraform
I want to find all VPCs for every region in a given account and for each VPC enable flow logs.How this can be done using Terraform?

fotios.l...@enigma.com

unread,
Oct 2, 2018, 10:35:31 AM10/2/18
to Terraform
Most resources have a related "data" resource that helps you find items; some of them only work with an explicit ID while others let you search/filter for multiple items.

What you're trying to do is actually pretty much the example given with the "aws_vpcs" resource. https://www.terraform.io/docs/providers/aws/d/vpcs.html

-- fotios

Prateek Rastogi

unread,
Oct 2, 2018, 1:54:45 PM10/2/18
to Terraform
I have come up with the below solution using the reference given by you.

provider "aws" {
  alias  = "use1"
  region = "us-east-1"
}

provider "aws" {
  alias  = "euw2"
  region = "eu-west-2"
}

provider "aws" {
  alias  = "sae2"
  region = "sa-east-1"
}

module "flowlogen" {
    source = "./flowlogen"
providers = {
aws.use1 = "aws.use1"
aws.euw2 = "aws.euw2"
aws.sae2 = "aws.sae2"
}
}

-----------------------------------flowlogen module------------------------------------

data "aws_vpcs" "all" {}

resource "aws_flow_log" "a_flow_log" {
  count = "${length(data.aws_vpcs.all.ids)}"
  vpc_id = "${element(data.aws_vpcs.all.ids, count.index)}"

Bill Anderson

unread,
Oct 3, 2018, 10:19:53 AM10/3/18
to Terraform
A couple things to be clear about: you would need to have already defined all the VPCs in Terraform - it can't go find them and operate on them for you. Also, I don't think count works for flow logs: https://www.terraform.io/docs/providers/aws/r/flow_log.html

Each "resource "aws_flow_log"" defines a singular resource, and each flow log is a single resource rather than a collection of them. You would need to define a flow log resource for each flow log you want to store logs in. Which reminds me, your code below doesn't have the required entries for a flow log. It needs a name and an IAM role ARN. Flow logs aren't an attribute of a VPC you can switch on.
Reply all
Reply to author
Forward
0 new messages