MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Terraform Error Handing with Try Catch

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:

  • validation with fileexists() 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 the for expression, 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 = true is required. The AWS provider marks password_data as sensitive, and an output built from it is rejected unless the output is marked sensitive too.
  • count = 18 and get_password_data = true use a number and a boolean instead of the quoted strings in the original.
  • aws_instance.example[*].public_ip replaces 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

  1. Put the private key for the aws-hl-training key pair next to the configuration. rsadecrypt needs a PEM-encoded RSA private key that is not protected with a passphrase.
  2. Run terraform init to download the AWS provider.
  3. Run terraform validate to catch syntax errors such as the try { } block.
  4. Run terraform apply. With get_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.
  5. 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.

ToolWhat it doesTypical use
try(a, b, ...)Returns the first argument that evaluates without errorDefault values for optional attributes, missing map keys, failed decoding
can(expr)Returns true if the expression evaluates without error, false otherwiseConditions in validation blocks and conditional expressions
variable validationRejects bad input with a custom messageChecking file paths, CIDR formats, allowed values
precondition / postcondition in lifecycleChecks assumptions before or after a resource is planned or createdMaking sure an AMI is Windows, or that an instance received a public IP
check blockReports a failed assertion as a warning without stopping the runHealth 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, InsufficientInstanceCapacity or 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

SymptomCauseFix
Parse error pointing at try {try was written as a blockUse try(expr, fallback)
Output refers to sensitive valuesOutput built from password_data is not marked sensitiveAdd sensitive = true to the output
Every password shows the fallback messageWrong key file, a passphrase-protected key, or an instance launched with a different key pairCheck that key_name matches the .pem file and remove the passphrase from a copy of the key
password_data is emptyThe AMI is not Windows, or get_password_data is not enabledUse a Windows AMI and set get_password_data = true
Warnings about interpolation-only expressionsLegacy "${...}" syntaxWrite 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Terraform Project โ€“ Assignment โ€“ Exercise โ€“ Lab#1: Variables

How to submit Assignment? Please submit assignment @https://www.debug.school/ and POST url share in the comments of this post. Assignment – 1 Write a terraform script using aws…

Read More

Quick Tutorials of Hashicorp Packer

Packer AWS – Builders & Provisionars – aws-ubuntu.pkr.hcl Rajesh Kumar I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge,…

Read More

Terraform Tutorials: Variables – Data Type – Map

In this example, the instance_tags variable is defined with a type of map(string), and it is given a default value of { Name = “my-instance” }. The…

Read More

Terraform Tutorials: Variables – Data Type – String

In this example, the instance_name variable is defined with a type of string, and it is given a default value of “my-instance”. The AWS provider is then…

Read More

Terraform Tutorials: Variables – Data Type – List

In this example, the security_groups variable is defined with a type of list(string), and it is given a default value of [“default”]. The AWS provider is then…

Read More

Terraform Tutorials: Variables – Data Type – Number

In this example, the instance_count variable is defined with a type of number, and it is given a default value of 1. The AWS provider is then…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x