在 terraform 中构建输出地图

Build output map in terraform

我有一个要创建的用户列表,一个 sns 主题列表,并要创建策略以向用户授予主题权限。这些都是针对用户的命名空间...

鉴于:

main.tf


provider "aws" {
  region                  = "eu-west-1"
  profile                 = "terraform"
}

module "topics" {
  source = "./queues/topics"
}

module "users" {
  source = "./users"
}

module "policies" {
  source = "./policies"

  sns_topics = "${module.topics.sns_topics}"
}

./queues/topics.tf

resource "aws_sns_topic" "svc_topic" {
  count = "${length(var.sns_topics)}"
  name = "${element(var.sns_topics, count.index)}"
}

./queues/topics/vars.tf

# List of topics
variable "sns_topics" {
  type = "list"

  default = [
    "a-topic",
    "b-topic",
    "c-topic",
  ]
}

./queues/topics/output.tf

output "sns_topics" {
  value = "${var.sns_topics}"
}

./users/main.tf

resource "aws_iam_user" "usrs" {
  count = "${length(var.topic_user)}"
  name = "usr-msvc-${element(var.topic_user, count.index)}"
}

./users/vars.tf

variable "topic_user" {
  type = "list"

  default =[
    "user-a",
    "user-b",
    "user-c",
  ]
}

./users/output.tf

output "topic_user" {
  value = "${var.topic_user}"
}

./policies/main.tf

resource "aws_iam_policy" "sns_publisher" {
  count = "${length(var.sns_topics)}"

  name = "sns-${element(var.sns_topics, count.index)}-publisher"
  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:*:*:${element(var.sns_topics, count.index)}"
    }
  ]
}
POLICY
}

这是我想在输出中构建地图的地方 将用户映射到主题

output "usr_topic_map" {
  value = {
    "user-a" = "a-topic
    "user-b" = "c-topic
    "user-c" = "c-topic
  }
}

我可以将用户列表传递给策略模块,但我不知道如何在输出中生成此地图。

我想用这个将策略附加到相应的用户。

如果可以简化任务,也愿意改进结构。

您可以使用 Terraform 函数 zipmap. Since your keys are output from the users module as the list module.users.topic_user and your values are output from the topics modules as the list module.topics.sns_topics (module output doc) 执行此操作,您可以将它们作为输出中函数的参数:

output "user_topic_map" {
  value = "${zipmap(module.users.topic_user, module.topics.sns_topics)}"
}

请记住 zipmap 的两个参数列表需要长度相等,因此可能在 resource/variable/output 块中的某处也有保护代码。

你可以这样做:

output "iam_user" {
  value = map(
    "key", aws_iam_access_key.user.id,
    "secret", aws_iam_access_key.user.secret
  )
}

您也可以使用这种方法。

output "outputs" {
  value       = {
    vpc_id        = aws_vpc.vpc.id
    pub_sbnt_ids  = aws_subnet.public.*.id
    priv_sbnt_ids = aws_subnet.private.*.id
  }
  description = "VPC id, List of all public, private and db subnet IDs"
}