我的目标是针对此示例代码提出自定义错误,而不是从 terraform 收到的错误:
resource "aws_instance" "example" {
ami = "ami-0f" # Invalid AMI ID intentionally causing an error
instance_type = "t2.micro"
}
对于这段代码,我得到了错误输出:
aws_instance.example: Creating...
╷
│ Error: creating EC2 Instance: InvalidAMIID.NotFound: The image id '[ami-0f]' does not exist
│ status code: 400, request id: 2d665c80-8918-4940-92cc-11f7a14ecd57
│
│ with aws_instance.example,
│ on main.tf line 27, in resource "aws_instance" "example":
│ 27: resource "aws_instance" "example" {
│
╵
上面的错误是一个正确的错误..但我想创建一个如下所示的自定义错误:
Custom message: Failed to create the AWS instance.
请提出建议:
复选框: 我已经正确配置了 aws 提供程序、访问令牌和秘密令牌
谢谢你
validation
块。根据
这篇文章,亚马逊系统映像 (AMI) ID 应以 ami-
开头,后跟 17 个字母数字字符的字符串。变量验证的快速示例:
variable "ami" {
description = "The AMI to use for the server"
type = string
validation {
condition = can(regex("^ami-[a-f0-9]{17}$", var.ami))
error_message = "The ami variable must be a valid AMI ID in the format ami-xxxxxxxxxxxxxxxxx."
}
}
resource "null_resource" "aws_instance" {
triggers = {
ami = var.ami
}
}
正在运行terraform plan -var 'ami=foobar'
(无效值):
│ Error: Invalid value for variable
│
│ on main.tf line 1:
│ 1: variable "ami" {
│ ├────────────────
│ │ var.ami is "foobar"
│
│ The ami variable must be a valid AMI ID in the format ami-xxxxxxxxxxxxxxxxx.
│
│ This was checked by the validation rule at main.tf:5,3-13.