Terraform使用输出变量作为另一个资源的输入



我在output.tf文件中定义了一个输出变量,如下所示:

output "cluster_arn" {
description = "MSK Cluster ARN"
value       = aws_msk_cluster.msk.arn
}
data "terraform_remote_state" "msk_vpc" {
backend = "s3"
count = var.use_msk_peering ? 1 : 0
config = {
bucket = "${var.env}-tf-state"
key    = "${var.msk_peer_name}/${var.msk_peer_region}/msk/terraform.tfstate"
region = "us-west-2"
}
}

我需要的是将此输出用作aws_iam_role_policy资源中的输入,因为我需要限制特定集群的评估。我该怎么办?我在下面这样尝试,但Terraform在下面返回了一个错误。。Terraform似乎无法按照我预期的方式解析输出变量
不正确的PolicyDocument:资源数据.terraform_remote_state.msk_vpc[0].outputs.cluster_arn必须为arn格式或"&">

resource "aws_iam_role_policy" "msk_access" {
name = "${element(split("-", var.product), 0)}-${var.env}-${var.region}-msk-access"
role = module.instance_role.instance_role
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"kafka:Describe*",
"kafka:List*",
"kafka:Get*"
],
"Effect": "Allow",
"Resource": "data.terraform_remote_state.msk_vpc[0].outputs.cluster_arn"              
}
]
}
EOF
}
"Resource": "data.terraform_remote_state.msk_vpc[0].outputs.cluster_arn"

这一行不引用变量本身,它只是用引号中的内容创建一个字符串。

你要做的是删除引号:

"Resource": data.terraform_remote_state.msk_vpc[0].outputs.cluster_arn

或使用字符串插值:

"Resource": "${data.terraform_remote_state.msk_vpc[0].outputs.cluster_arn}"

您可以使用Terraform的templatefile()函数对JSON文件进行一些变量插值。类似于:

data "terraform_remote_state" "msk_vpc" {
backend = "s3"
count   = var.use_msk_peering ? 1 : 0
config = {
bucket = "${var.env}-tf-state"
key    = "${var.msk_peer_name}/${var.msk_peer_region}/msk/terraform.tfstate"
region = "us-west-2"
}
}
resource "aws_iam_role_policy" "msk_access" {
name = "${element(split("-", var.product), 0)}-${var.env}-${var.region}-msk-access"
role = module.instance_role.instance_role
policy = templatefile("${path.module}/policy.json", {
cluster_arn = data.terraform_remote_state.msk_vpc[0].outputs.cluster_arn
})
}

随附的policy.json存在于您的模块根目录中:

{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"kafka:Describe*",
"kafka:List*",
"kafka:Get*"
],
"Effect": "Allow",
"Resource": "${cluster_arn}"
}
]
}

相关内容

  • 没有找到相关文章

最新更新