我正在尝试为特定环境禁用资源,在本例中是qa环境,我只希望为生产和试运行创建资源。我有相同的terraform代码,通过管道为qa,staging和production运行。
我有一些用于创建ECS集群的代码。我不希望它为qa环境创建。这是在ECS上创建集群的代码:
resource "aws_ecs_cluster" "main" {
name = "${terraform.workspace}-main"
tags = {
App = var.app_name
Environment = terraform.workspace
}
}
output "main_ecs_id" {
value = aws_ecs_cluster.main.id
}我尝试使用count来禁用qa环境,这是有效的:
resource "aws_ecs_cluster" "main" {
count = terraform.workspace != "qa" ? 1 : 0
name = "${terraform.workspace}-main"
tags = {
App = var.app_name
Environment = aws_ecs_cluster.main[count.index].name
}
}
output "main_ecs_id" {
value = aws_ecs_cluster.main.*.id
}唯一的问题是它不适用于我想要创建资源的环境(生产和暂存)。当它尝试在生产环境和登台环境中使用该代码创建资源时,我会收到以下错误:
Error: Self-referential block
on ecs.tf line 8, in resource "aws_ecs_cluster" "main":
8: Environment = aws_ecs_cluster.main[count.index].name
Configuration for aws_ecs_cluster.main may not refer to itself.你知道我会做错什么吗?谢谢
发布于 2020-08-13 17:25:33
您的问题不是使用count禁用资源,而是您不能引用其内部的资源(这里使用self keyword的置备程序是例外,但它们是资源的额外部分)。
相反,您需要重新构建名称或将名称字符串提取到本地:
resource "aws_ecs_cluster" "main" {
count = terraform.workspace != "qa" ? 1 : 0
name = "${terraform.workspace}-main"
tags = {
App = var.app_name
Environment = "${terraform.workspace}-main"
}
}或者使用本地化:
locals {
cluster_name = "${terraform.workspace}-main"
}
resource "aws_ecs_cluster" "main" {
count = terraform.workspace != "qa" ? 1 : 0
name = local.cluster_name
tags = {
App = var.app_name
Environment = local.cluster_name
}
}局部变量的使用只允许你处理资源块之外已知的事情(例如你的字符串连接)。如果你想要一些依赖于资源块中的count或each的东西,那么你就不能使用它们。有一个existing issue将资源作用域的本地变量作为一个突出的特性请求。
https://stackoverflow.com/questions/63391946
复制相似问题