如何让 Terraform 根据用户所在的帐户抛出特定的错误消息?

How do I get Terraform to throw a specific error message depending on what account the user is in?

我有一个执行域委托的 terraform 模块。对于几个变量,有一些针对硬编码值的验证,以检查用户是否使用有效输入,例如:

resource "null_resource" "validate_region" {
  count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"
}

其中 local.regions 是硬编码的,var.region 是用户设置的变量。上面的代码的工作原理是当用户设置变量错误时,它会抛出这样的错误:

Error: Incorrect value type

  on .terraform/foo/main.tf line 46, in resource "null_resource" "validate_region":
  46:   count = contains(local.regions, var.region) == true ? 0 : "Please provide a valid AWS region. E.g. (us-west-2)"

Invalid expression value: a number is required.

我现在需要验证用户当前使用的 AWS 账户是否正确。在这种情况下,由用户在他们的变量中设置正确帐户的帐户 ID,我的代码需要提取 运行 模块帐户的帐户 ID,并将其与用户的变量进行比较。我试过这样的事情:

data "aws_caller_identity" "account" {}

resource "null_resource" "validate_account" {
  count = data.aws_caller_identity.account.account_id == var.primary_account_id ? 0 : "Please check that you are using the AWS creds for the primary account for this domain."
}

data "aws_route53_zone" "primary" {
  name = local.primary_name
}

"{data.aws_caller_identity.account.account_id == var.primary_account_id}" ? 0 部分进行了各种语法更改以使逻辑正常工作,但运气不佳。我希望它像区域验证那样抛出一个错误,它会显示我写的错误消息。相反(取决于语法),它将对正确的帐户按预期工作并为不正确的帐户抛出 Error: no matching Route53Zone found 错误,或者它会抛出一个完全不同的错误,大概是因为语法搞砸了。

如何让它工作?可能吗?

我发现这个块:

data "aws_route53_zone" "primary" {
  name = local.primary_name
}

在帐户验证资源块之前是 运行。像这样添加 depends_on

data "aws_route53_zone" "primary" {
  name       = local.primary_name
  depends_on = [null_resource.validate_account,
  ]
}

一切都很好。

这里的另一个选项应该可以简化您正在做的事情,那就是设置区域和帐户限制,这样 Terraform 将自动使用正确的区域,如果凭据不适合正确的帐户,则会失败。

您可以在 aws 提供程序块中定义它。示例可能如下所示:

provider "aws" {
  region              = "eu-west-1"
  allowed_account_ids = ["123456789012"]
}

现在,如果您尝试为不同的 AWS 账户使用凭据,那么 Terraform 将在计划阶段失败:

Error: AWS Account ID not allowed: 234567890123

我所做的是在 locals 块中创建一个 if 语句并获取一个包含我要显示的错误消息的文件。

variable "stage" {
   type = string
   desciption = "The stage to run the deployment in"
}
locals {
   stage_validation = var.stage == "prod" || var.stage == "dev" 
        ? var.stage 
        : file("[Error] this module should only be ran for stages ['prod' or 'dev' ]")
}

将阶段变量设置为 'dev' 或 'prod' 以外的任何值的输出如下所示

╷
│ Error: Invalid function argument
│ 
│   on main.tf line 10, in locals:
│   10:     stage_validation = var.stage == "prod" || var.stage == "dev" 
│           ? var.stage 
│           : file("[Error] this module should only be ran for stages ['prod' or 'dev' ]")
│ 
│ Invalid value for "path" parameter: no file exists at This module should only be run for stages ['prod' or 'dev']; this function works only
│ with files that are distributed as part of the configuration source code, so if this file will be created by a resource in this
│ configuration you must instead obtain this result from an attribute of that resource.
╵

这很有用,因为它允许您编写一条错误消息,该消息将显示给尝试 运行 代码的人。