My goal here is to raise a custom error instead of the error received from terraform for this sample code:
resource "aws_instance" "example" {
ami = "ami-0f" # Invalid AMI ID intentionally causing an error
instance_type = "t2.micro"
}
for this code I got an error output:
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" {
│
╵
The above error is a proper error.. But I want to create a custom error like below:
Custom message: Failed to create the AWS instance.
Kindly give suggestions on:
- How to display my custom error instead of the proper error displayed by terraform?
- and also How to display my custom error along with the proper error displayed by terraform?
If you have any standard logics for error handling and exception handling in terraform please do share.
How to add my own custom error messages (like we do exceptions handling in python) for any type of errors caused by terraform ?
Thank you
2
Answers
One option would be to specify custom validation rules for your variables.
Quick example with the variable validation:
Notes:
ami-
followed by a string of 17 alphanumeric characters.Running
terraform plan -var 'ami=foobar'
(invalid value):See also custom conditions in order to produce custom error messages for several types of objects in a configuration.
As far as I know you can’t raise a custom error from terraform, but you can achieve the desired result by capturing the error message from the terraform process and then handling it accordingly, e.g.:
you can extend this to add handling for any error message.