hello. can we call csv function in aws recource?
I have a csv file of security group rule and I’m trying to call is from resource rather than calling from local. How can I do so?
CSV FILE
type,protocol,from,to,cidr_blocks,description
ingress,-1,0,0,10.100.0.0/16,
ingress,tcp,3389,3389,10.100.10.81/32,AWS
Hi @dipendra.chaudhary,
The first step would be to load this CSV file using the csvdecode
function:
locals {
security_group_rules = csvdecode(file("${path.module}/security_group_rules.csv"))
}
The rest of this will follow a similar pattern to the Use with the for_each
meta-argument section of the csvdecode
documentation.
Using for_each
will require each of your security group rules to have a unique key for Terraform to track it by. Since there isn’t an explicit unique key column in your CSV I suppose we’ll need to make a compound key with all of the relevant attributes concatenated together:
locals {
security_group_rules_map = {
for r in local.security_group_rules :
"${r.type} ${r.protocol} ${r.from} ${r.to} ${r_cidr_blocks}" => r
}
}
This local.security_group_rules_map
is now a suitable shape to use with for_each
: a map with one element per security group rule:
resource "aws_security_group_rule" "example" {
for_each = local.security_group_rules_map
security_group_id = "sg-123456"
description = each.value.description
type = each.value.type
from_port = each.value.from
to_port = each.value.to
protocol = each.value.protocol
cidr_blocks = split(" ", each.value.cidr_blocks)
}
In this case your security group rule resources will have instance addresses like this, due to how we had to construct unique keys from various attributes of each object:
aws_security_group_rule.example["ingress -1 0 0 10.100.0.0/16"]
aws_security_group_rule.example["ingress tcp 3389 3389 10.100.10.81/32"]
I mention this because it’s helpful to know that Terraform considers those string keys to be the identity of each instance, and so if you edit your CSV file to change any of them then Terraform will understand it as destroying an existing object and creating a new one, rather than editing the existing object in-place. However, since I didn’t include description
as part of the key, you can change the description column of your CSV file and Terraform will understand it as a change to an existing object, because the unique key won’t change in that case.