(大量免责声明 - 这是未经测试的,因此可能需要一些调整才能工作)
我认为这里的根本困难在于 Terraform 对复杂循环技术的支持有限。因此,您需要一种方法oci_identity_user_group_membership
来遍历单个对象。
此外,资源获取资源和资源oci_identity_user_group_membership
的 ID 。因此,在尝试将用户与组关联之前,您需要先创建这些用户。因此,您似乎需要一个变量来跟踪可能需要被授予访问权限的唯一用户集合,以便您可以创建资源。(在一个更复杂的解决方案中,您可能会从 的内容中生成该列表,但一次只有一步 :))oci_identity_group
oci_identity_user
oci_identity_user
iam_groups
iam_group_users
本节中定义的变量locals
旨在生成如下结构:
[
{ 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 与每个资源实例关联的名称,分别取自创建&时语句中key
使用的名称。此外,鉴于此,重要的是in 您的var 包含用户的资源名称(即in )。for_each
oci_identity_group
oci_identity_user
user_list
iam_groups
key
iam_users
一些额外的,可能有用的,阅读:
Terraform“扁平化”文档
Terragrunt 关于循环的博客文章