'How to create several different policies with terraform
I need to create a several different policies this is my code:
This is my main.tf
resource "aws_iam_policy" "policy" {
count = length(var.name) != [] ? length(var.name) : 0
name = var.name[count.index]
path = var.path
description = var.description
policy = jsonencode(var.policy[count.index])
This is my variables.tf
variable "policy" {
description = "The policy in IAM (tpl file)"
type = list(any)
default = []
}
variable "name" {
description = "The name of the policy"
type = list
default = []
}
And for examples my var.tfvars
policy = [policy1,policy2]
This is the error
Error: Invalid value for module argument
│
│ on main.tf line 14, in module "test":
│ 14: policy = var.policy
│
│ The given value is not suitable for child module variable "policy" defined at ../policy/variables.tf:19,1-18: all list
│ elements must have the same type.
Solution 1:[1]
Here is how I would approach that code you posted:
variable "policies" {
description = "The policies in IAM"
type = map(object({
path = string
description = string
file = string
}))
default = {
"foo": {path : ".", description : "", file : "foo.json"},
"bar": {path : ".", description : "", file : "bar.json"}
}
}
resource "aws_iam_policy" "role_policy" {
for_each = var.policies
name = each.key
path = each.value.path
description = each.value.description
policy = file( each.value.file)
}
You can see that now the variables are all in one
with type = map(object({
We can loop over that, and that is exactly what I do in the resource:for_each = var.policies
and of course the default in my code is just an example
I strongly recommend against type = list(any) that could makes the next developer what type is the list in use:
...and error looks straight forward:Invalid valueall list elements must have the same type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
