簡體   English   中英

如何使用 terraform 創建多個不同的策略

[英]How to create several different policies with terraform

我需要創建幾個不同的策略這是我的代碼:

這是我的 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])

這是我的變量.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 = []
}

例如我的 var.tfvars

policy = [policy1,policy2]

這是錯誤

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.

以下是我將如何處理您發布的代碼:

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)
}

你可以看到現在變量都在一個
type = map(object({
我們可以遍歷它,這正是我在資源中所做的:
for_each = var.policies
當然我代碼中的默認值只是一個例子


我強烈建議不要type = list(any) ,這可能會讓下一個開發人員使用什么類型的列表:
...錯誤看起來很直接:
Invalid value
all list elements must have the same type.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM