So, I am trying to create mutiple origins based on a list to my terraform module
What I am trying to do is the following:
resource "aws_cloudfront_distribution" "photos" {
origin {
for_each = { for redirection in var.redirections : redirection.origin_id => redirection }
domain_name = each.value.origin
origin_access_control_id = each.value.origin_id
origin_id = each.value.origin_id
}
#... rest of terraform resource code
}
I know that It alows me to add more than one origin like the following:
resource "aws_cloudfront_distribution" "photos" {
origin {
domain_name = "orig1"
origin_access_control_id = "origin1.com"
origin_id = "origi1"
}
origin {
domain_name = "orig2"
origin_access_control_id = "origin2.com"
origin_id = "origi2"
}
However, with this pattern I can't send this as variables to iterate
is there any way to iterate over an array on a terraform subfield only? I tried to put the for each under aws_cloudfront_distribution resource, but that creates a cloudfront distribution for each element in the array, which isn't what I want.
You can use a dynamic block, documented here.
resource "aws_cloudfront_distribution" "photos" {
dynamic "origin" {
for_each = { for redirection in var.redirections : redirection.origin_id => redirection }
content {
domain_name = each.value.origin
origin_access_control_id = each.value.origin_id
origin_id = each.value.origin_id
}
}
#... rest of terraform resource code
}
(this can be likely simplified to just for_each = toset(var.redirections)
, since you don't use a key and cannot refer to these origin
blocks from outside, so the actual key value is of no particular interest for you, and order does not matter here anyway)