Terraform Made Simple: Day 3 - Terraform Variables
After learning the basics, it's time to understand Terraform variables.
Variables are important because we don’t want to hardcode values directly in our configuration. Instead, we define variables and pass values when needed.
This makes our Terraform code flexible, reusable, and easier to manage across different environments.
Let's see how it works-
1. What are Terraform Variables?
Variables act as customizable inputs that remove the need for static, "hard-coded" values in your files:
> Parameterize Configurations: Use placeholders for values like regions or instance types.
> Accept Values at Runtime: Pass data into your code from various sources when you run Terraform.
> Enable Reusability: Allow the same configuration to be passed into different modules or environments.
2. Types of Variables & Values:
There are three main ways to handle data within your project:
> Input Variables: Accept values from outside the module (like from a user or a file).
> Local Values: Compute a value once to reuse it multiple times within a single module.
> Output Values: Expose specific information (like an IP address) after the infrastructure is built.
> Common Properties: You can define a type constraint, a default value, and even custom validation rules.
3. Declaring and Using Variables:
Managing variables is a straightforward process of defining the input and then referencing it:
> Declare in variables. tf: Use the variable block to set the name, type, and description.
> Reference in main. tf: Access your inputs using the var.<name> syntax, or use local.<name> for computed values.
4. Setting Variable Values:
You have several ways to provide the actual data to your variables:
> Variable Files: Use a terraform.tfvars file to store your environment-specific values.
> CLI Flags: Pass values directly in the terminal using the -var flag.
> Environment Variables: Use system variables (prefixed with TF_VAR_) to map values to Terraform.
That’s all for today!
Next, we’ll understand Datasources and Locals in Terraform. Then we’ll move on to a hands-on project where we create a VPC from scratch using everything we’ve learned so far.
Comments
Post a Comment