无法在我的Terraform模块上建立条件

时间:2019-06-07 08:09:42

标签: terraform terraform-provider-aws

我正在尝试查找所有AWS vpc并将vpc流日志添加到它们。 我正在将此代码部署到我的所有AWS账户(约30个账户)。 其中有4个没有任何VPC,因此它们上的VPC失败。

此vpc模块是从帐户模块(只是指定要启动的模块的模块)启动的,不幸的是,直接依赖该模块在0.12中尚不可用

我试图将bool变量vpc_exists = false传递给没有VPC的帐户,并进行一些条件设置,使其无法在没有VPC的帐户上运行,但我做不到。

如果我至少有一个VPC,可以工作,但是如果没有VPC,则失败:

data "aws_vpcs" "vpcs" {}

resource "aws_flow_log" "vpc_flow_log" {
  count           = length(data.aws_vpcs.vpcs.ids)
  vpc_id          = tolist(data.aws_vpcs.vpcs.ids)[count.index]
  iam_role_arn    = aws_iam_role.vpc_flow_logs.arn
  log_destination = aws_cloudwatch_log_group.vpc_flow_logs[count.index].arn
  traffic_type    = "REJECT"
}

resource "aws_cloudwatch_log_group" "vpc_flow_logs" {
  count = length(data.aws_vpcs.vpcs.ids)
  name  = "${var.prefix}-vpc-flow-logs-${tolist(data.aws_vpcs.vpcs.ids)[count.index]}"
}

count = var.vpc_exists ? length(data.aws_vpcs.vpcs.ids) : 0

向资源添加条件问我:


  on ../modules/vpc/vpc_flow_logs.tf line 32, in resource "aws_cloudwatch_log_group" "vpc_flow_logs":
  32:   name  = "${var.prefix}-vpc-flow-logs-${tolist(data.aws_vpcs.vpcs.ids)[count.index]}"

Because data.aws_vpcs.vpcs has "count" set, its attributes must be accessed on
specific instances.

For example, to correlate with indices of a referring resource, use:
    data.aws_vpcs.vpcs[count.index]

如果我确实在计数内添加了[count.index],它将无法正常工作。

不知道该怎么办了,有什么主意吗?

编辑:

根据一些建议,我添加了。*。,但仍然出现错误:

data "aws_vpcs" "vpcs" {
  count = var.vpc_exists ? 1 : 0
}

resource "aws_flow_log" "vpc_flow_log" {
  count = var.vpc_exists ? length(data.aws_vpcs.vpcs.*.ids) : 0
  vpc_id          = tolist(data.aws_vpcs.vpcs.ids)[count.index]
  iam_role_arn    = aws_iam_role.vpc_flow_logs.arn
  log_destination = aws_cloudwatch_log_group.vpc_flow_logs[count.index].arn
  traffic_type    = "REJECT"
}

resource "aws_cloudwatch_log_group" "vpc_flow_logs" {
  count = var.vpc_exists ? length(data.aws_vpcs.vpcs.*.ids) : 0
  name  = "${var.prefix}-vpc-flow-logs-${tolist(data.aws_vpcs.vpcs.ids)[count.index]}"
}

  on ../modules/vpc/vpc_flow_logs.tf line 32, in resource "aws_cloudwatch_log_group" "vpc_flow_logs":
  32:   name  = "${var.prefix}-vpc-flow-logs-${tolist(data.aws_vpcs.vpcs.ids)[count.index]}"

Because data.aws_vpcs.vpcs has "count" set, its attributes must be accessed on
specific instances.

For example, to correlate with indices of a referring resource, use:
    data.aws_vpcs.vpcs[count.index]

如果我添加。*。到名称行和vpc_id行,我将收到此错误:

Error: Invalid template interpolation value

  on ../modules/vpc/vpc_flow_logs.tf line 32, in resource "aws_cloudwatch_log_group" "vpc_flow_logs":
  32:   name  = "${var.prefix}-vpc-flow-logs-${tolist(data.aws_vpcs.vpcs.*.ids)[count.index]}"
    |----------------
    | count.index is 0
    | data.aws_vpcs.vpcs is tuple with 1 element

Cannot include the given value in a string template: string required.

0 个答案:

没有答案