Terraform has no try { } catch { } block. Error handling in HCL uses the try() function, which returns the first of its arguments that evaluates without an error, and the can() function, which returns true or false. This page explains why the example above will not run, then gives a working version that decrypts Windows EC2 Administrator passwords and falls back to a message when decryption fails.
The code could be improved by adding some error handling. For example, you could check to make sure that the PEM file exists and that the password data is valid. You could also add a retry mechanism in case the AWS API call fails.
This code uses the try and catch blocks to handle errors. If the rsadecrypt function fails, the catch block will be executed and the output will be set to the specified error message.
resource "aws_instance" "example" {
ami = "ami-065b889ab5c33720e"
count = "18"
instance_type = "t2.medium"
key_name = "aws-hl-training"
vpc_security_group_ids =["sg-0541801a7a059ba17"]
get_password_data = "true"
}
output "public_ip" {
value = "${aws_instance.example.*.public_ip}"
}
output "public_dns" {
value = "${aws_instance.example.*.public_dns}"
}
output "Administrator_Password1" {
value = try {
[
for g in aws_instance.example : rsadecrypt(g.password_data,file("aws-hl-training.pem"))
]
} catch {
// Handle the error
"Unable to decrypt password data"
}
}Code language: JavaScript (javascript)
Why the example above fails
HCL is a declarative configuration language, not a general-purpose programming language, and it has no exception-handling statements. try is a built-in function, so it takes arguments in parentheses. Writing try { ... } catch { ... } gives a parse error the moment you run terraform validate or terraform plan, before anything reaches AWS.
The function form looks like this:
try(expression_1, expression_2, ..., fallback_value)Code language: JavaScript (javascript)
Terraform evaluates the arguments from left to right and returns the first one that does not produce an error. If every argument fails, try() itself returns an error. The last argument is usually a plain value such as a string, null or an empty list, so it cannot fail.
Corrected configuration
The version below keeps the intent of the original: launch Windows instances, read each encrypted password, and decrypt it with the key pair's private key. It also checks that the PEM file exists, as the text above suggests.
variable "key_name" {
type = string
default = "aws-hl-training"
}
variable "private_key_path" {
type = string
default = "aws-hl-training.pem"
validation {
condition = fileexists(var.private_key_path)
error_message = "The private key file was not found at private_key_path."
}
}
resource "aws_instance" "example" {
count = 18
ami = "ami-065b889ab5c33720e"
instance_type = "t2.medium"
key_name = var.key_name
vpc_security_group_ids = ["sg-0541801a7a059ba17"]
get_password_data = true
}
locals {
# null if the file cannot be read, instead of a hard failure
private_key = try(file(var.private_key_path), null)
}
output "public_ip" {
value = aws_instance.example[*].public_ip
}
output "public_dns" {
value = aws_instance.example[*].public_dns
}
output "administrator_passwords" {
value = [
for inst in aws_instance.example :
try(rsadecrypt(inst.password_data, local.private_key), "Unable to decrypt password data")
]
sensitive = true
}Code language: PHP (php)
Important lines:
validationwithfileexists()stops the run with a clear message if the key file is missing. That is better than letting decryption fail silently.try()is placed inside theforexpression, so each instance is handled separately. If one password is not ready, only that entry shows the fallback message and the other 17 still decrypt. Wrapping the whole list, as the original tries to do, would replace every password with one string.sensitive = trueis required. The AWS provider markspassword_dataas sensitive, and an output built from it is rejected unless the output is marked sensitive too.count = 18andget_password_data = trueuse a number and a boolean instead of the quoted strings in the original.aws_instance.example[*].public_ipreplaces the legacy"${aws_instance.example.*.public_ip}"interpolation-only syntax.
Note: The AMI ID and security group ID are region-specific and come from the original author's account. Replace them with a Windows AMI and a security group from your own account and region.
Running it and reading the passwords
- Put the private key for the
aws-hl-trainingkey pair next to the configuration.rsadecryptneeds a PEM-encoded RSA private key that is not protected with a passphrase. - Run
terraform initto download the AWS provider. - Run
terraform validateto catch syntax errors such as thetry { }block. - Run
terraform apply. Withget_password_data = true, the provider waits for Windows to generate the password before it marks the instance as created, so the apply takes longer than it does for a Linux instance. - Read the decrypted passwords with
terraform output -json administrator_passwords.
$ terraform output
administrator_passwords = <sensitive>
public_dns = [ ... ]
public_ip = [ ... ]
$ terraform output -json administrator_passwords
["p@ssExample1","Unable to decrypt password data", ...]Code language: PHP (php)
Note: Marking an output sensitive only hides it in the CLI. The encrypted password data and anything derived from it are still saved in plain text in the state file. Use an encrypted remote backend with restricted access, and do not commit terraform.tfstate or the .pem file to Git.
try, can and the other error-handling tools
try() is only one option. Choose the tool based on whether you want to fall back quietly or stop with a clear error.
| Tool | What it does | Typical use |
|---|---|---|
try(a, b, ...) | Returns the first argument that evaluates without error | Default values for optional attributes, missing map keys, failed decoding |
can(expr) | Returns true if the expression evaluates without error, false otherwise | Conditions in validation blocks and conditional expressions |
variable validation | Rejects bad input with a custom message | Checking file paths, CIDR formats, allowed values |
precondition / postcondition in lifecycle | Checks assumptions before or after a resource is planned or created | Making sure an AMI is Windows, or that an instance received a public IP |
check block | Reports a failed assertion as a warning without stopping the run | Health checks after deployment |
variable "vpc_cidr" {
type = string
validation {
condition = can(cidrhost(var.vpc_cidr, 0))
error_message = "vpc_cidr must be a valid CIDR block, for example 10.0.0.0/16."
}
}
locals {
# Optional key in a map: fall back to a default if it is missing
env = try(var.tags["Environment"], "dev")
# Parse JSON that might be malformed
settings = try(jsondecode(file("settings.json")), {})
}Code language: PHP (php)
For more on conditional logic, see Terraform Conditional Expressions and Logic. For the for expressions and count used above, see Terraform Loops and Iteration.
What try() cannot catch
- Syntax and static errors. A malformed reference such as a misspelled resource name fails during validation no matter where it sits, because Terraform can prove it is invalid for every input.
- API failures. Errors such as
UnauthorizedOperation,InsufficientInstanceCapacityor a limit being exceeded happen while the provider creates the resource, not while an expression is evaluated. No HCL function can catch them. - Values not yet known at plan time. If an argument depends on an attribute known only after apply,
try()waits until that value is known. It does not choose the fallback early.
Note: Use try() sparingly. Wrapping everything in fallbacks hides real misconfigurations. Use it where a missing or invalid value is expected and acceptable, and use validation or preconditions where it is not.
Adding retries for AWS API calls
The text above suggests a retry mechanism. You do not build this in HCL. The AWS provider already retries throttled and transient API errors, and you can raise the limit with max_retries in the provider block:
provider "aws" {
region = "us-east-1"
max_retries = 10
}Code language: JavaScript (javascript)
For errors that are not transient, such as missing permissions or a quota that is exhausted, retrying does not help. Fix the cause, then run terraform apply again. Terraform creates only the resources that are still missing.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
Parse error pointing at try { | try was written as a block | Use try(expr, fallback) |
Output refers to sensitive values | Output built from password_data is not marked sensitive | Add sensitive = true to the output |
| Every password shows the fallback message | Wrong key file, a passphrase-protected key, or an instance launched with a different key pair | Check that key_name matches the .pem file and remove the passphrase from a copy of the key |
password_data is empty | The AMI is not Windows, or get_password_data is not enabled | Use a Windows AMI and set get_password_data = true |
| Warnings about interpolation-only expressions | Legacy "${...}" syntax | Write the reference directly, for example aws_instance.example[*].public_ip |
To catch problems like these before they reach review, run terraform fmt and terraform validate automatically. See How to Configure pre-commit for Terraform.
Frequently asked questions
Does Terraform support try/catch?
No. HCL has no exception-handling blocks. Use the try() function, which returns the first argument that evaluates without error, or can(), which returns a boolean.
What is the difference between try() and can() in Terraform?
try() returns a value: the first expression that succeeds, or your fallback. can() returns true or false depending on whether the expression succeeds, which is useful in validation conditions and conditional expressions.
Can try() catch AWS API errors during terraform apply?
No. try() only handles errors that happen while an expression is evaluated. Errors from the cloud provider during resource creation are reported by the provider and cannot be caught in HCL.
How do I view a sensitive output in Terraform?
Run terraform output -json <name>, or terraform output -raw <name> for a single string value. The value is still stored in plain text in the state file, so protect the state.
Why does rsadecrypt fail on my EC2 password data?
The usual causes are a private key that does not match the instance's key pair, a key protected with a passphrase, or empty password data because the AMI is not Windows or get_password_data is not enabled.
Related tutorials
- Terraform Conditional Expressions and Logic: Complete Guide with Examples
- Terraform Loops and Iteration: Complete Guide to count, for_each, for Expressions, and Dynamic Blocks
- How to Configure pre-commit for Terraform: Complete DevOps Guide with 15 Practical Use Cases, Commands, Security Checks, and Best Practices
- More Terraform tutorials
- More AWS tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals