(大量免责声明 - 这是未经测试的,因此可能需要一些调整才能工作)
我认为这里的根本困难在于 Terraform 对复杂循环技术的支持有限。因此,您需要在 oci_identity_user_group_membership 中使用一种方法来循环单个对象。
此外,oci_identity_user_group_membership 资源采用 oci_identity_group 资源和 oci_identity_user 资源的 ID。因此,在尝试将用户与组关联之前,您需要先创建这些用户。因此,您似乎需要一个变量来跟踪可能需要被授予访问权限的唯一用户集合,以便您可以创建oci_identity_user 资源。 (在更复杂的解决方案中,您可能会从iam_groups 的内容中生成该列表,但每次只有一步:)
locals 部分中定义的变量iam_group_users 旨在生成如下结构:
[
{ group_name = 'iamg1', user_name = 'test'}
{ group_name = 'iamg1', user_name = 'test1'}
{ group_name = 'iamg2', user_name = 'test'}
{ group_name = 'iamg2', user_name = 'test1'}
]
所以尝试一下实际的解决方案:
(请注意,我已将您的 iam_group 变量名称复数)
# Group Definitions
variable "iam_groups" {
default = {
iamg1 = { group_name = "group_test", group_desc = "group test", user_list = ["test", "test1"] }
iamg2 = { group_name = "group_test1", group_desc = "group test1", user_list = ["test", "test1"] }
}
}
# Unique User Definitions
variable "iam_users" {
default = {
test = {user_name = "test", user_desc = "user test"}
test1 = {user_name = "test1", user_desc = "user test1"}
}
}
locals {
# Create a list of maps, containing unique group name/user name combinations
iam_group_users = flatten([
for group, group_data in var.iam_groups : [
for user in group_data.user_list : {
group_name = group
user_name = user
}
]
])
}
# Iterate iam_groups, to create a collection of group resources
resource "oci_identity_group" "this" {
for_each = var.iam_groups
compartment_id = var.tenancy_ocid
name = each.value.group_name
description = each.value.group_desc
}
# Iterate iam_users, to create a colelction of user resources
resource "oci_identity_user" "this" {
for_each = var.iam_users
compartment_id = var.tenancy_ocid
name = each.value.user_name
description = each.value.user_desc
}
# Iterate the mapping of users that are members of each group to create the association
resource "oci_identity_user_group_membership" "test_user_group_membership" {
for_each = toset(local.iam_group_users)
group_id = oci_identity_group.this[each.value.group_name].id
user_id = oci_identity_user.this[each.value.user_name].id
}
注意:each.value.group_name & each.value.user_name 是 Terraform 与每个资源实例关联的名称,取自创建 for_each 语句时使用的 key oci_identity_group & @987654339 @, 分别。此外,鉴于此,iam_groups 变量中的 user_list 包含用户的资源名称(即 iam_users 中的 key)很重要。
一些额外的,可能有用的阅读:
Terraform 'flatten' docs
Terragrunt Blog post on Loops