In this article, you’ll learn how to enforce validation for a Terraform variable during the plan phase, specifically for an AMI ID used in an EC2 instance. Validating your variables early on helps catch errors before any changes are applied, ensuring a smoother deployment process. When provisioning an EC2 instance with Terraform, you might encounter issues if the AMI ID provided by the user doesn’t follow the proper format. For example, instead of a correctly formatted AMI ID (like “ami-1234abcd”), a user could mistakenly supply a simple number. Such errors, if not caught early, lead to failures during the Terraform apply phase, causing unnecessary confusion and troubleshooting delays.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.

Explanation
Breaking Down the Code
-
Variable Declaration
Theamivariable is defined with several attributes:- Type: It is declared as a string.
- Description: Provides context about what the variable represents.
- Default Value: Supplies a fallback AMI ID in case the user doesn’t define their own.
-
Validation Block
The validation block contains a condition that checks two requirements:- The provided AMI string must be longer than 4 characters.
- The first four characters of the string must be “ami-”.
This check is performed using thesubstr()function to extract the initial segment of the string.
-
Custom Error Message
If the AMI ID does not meet the conditions (for instance, if it is too short or does not start with “ami-”), Terraform will output the custom error message: “Enter a proper AMI ID.” This process runs during the plan phase, ensuring any errors are caught early.
Implementing validation blocks in Terraform not only prevents runtime errors but also enhances the overall robustness of your infrastructure code. This proactive approach is beneficial both for production deployments and technical interviews.
Why Validate During the Plan Phase?
Validating variables during the plan phase offers significant advantages:- Error Prevention: Catch formatting errors before any changes are applied.
- Efficient Troubleshooting: Identify mistakes quickly, reducing downtime.
- Robust Configurations: Maintain high-quality and error-resistant Terraform code.