Terraform Variables

Terraform Variables

What is Terraform Variables:

Terraform variables are fundamental components of Terraform configurations, providing a means to parameterize and customize infrastructure deployments. In essence, they serve as placeholders for values that can be dynamically supplied or changed without altering the underlying infrastructure code. This flexibility enables users to create reusable, modular, and maintainable infrastructure as code (IaC) solutions.

There are several types of variables in Terraform, each serving distinct purposes:

  1. Input Variables: These are used to define parameters that users can input values for when running Terraform commands. Input variables allow users to tailor the configuration to specific requirements without modifying the Terraform code directly. For instance, a user may specify different AWS regions or instance types based on their deployment needs.

  2. Output Variables: These are used to expose information about the deployed infrastructure to other Terraform configurations or external systems. Output variables capture relevant data such as IP addresses, DNS names, or other attributes of provisioned resources. This information can be consumed by subsequent Terraform modules or scripts for further automation or integration with external systems.

  3. Local Values: These are used to define intermediate values or calculations within Terraform configurations. Local values allow users to assign names to expressions or complex calculations, improving readability and maintainability. They are particularly useful for storing repetitive or computed values that are used multiple times within a configuration.

  4. Environment Variables: Terraform also supports the use of environment variables to supply values for variables. Environment variables prefixed with TF_VAR_ are automatically detected by Terraform and can be used to set values for input variables. This feature provides an alternative mechanism for supplying variable values, particularly useful in automated or scripted workflows.

By leveraging variables in Terraform, users gain several benefits:

  • Flexibility: Variables enable users to customize infrastructure deployments based on specific requirements or environmental factors. This flexibility accommodates diverse use cases and deployment scenarios without requiring modifications to the underlying codebase.

  • Reusability: Variables promote code reuse by decoupling configuration details from specific deployments. Modular configurations can be developed with generic variables that are easily adapted to different environments or projects, reducing duplication and enhancing maintainability.

  • Abstraction: Variables abstract configuration details into parameterized values, enhancing readability and comprehensibility. Abstracting configuration details into variables improves the clarity of Terraform code, making it easier to understand and modify.

  • Automation: Variables facilitate automation by allowing dynamic assignment of values based on external inputs or conditions. Automation scripts or CI/CD pipelines can leverage variables to drive infrastructure deployments with minimal manual intervention.

In summary, Terraform variables are essential components of infrastructure as code workflows, offering flexibility, reusability, abstraction, and automation capabilities. By effectively utilizing variables, users can create scalable, maintainable, and adaptable infrastructure configurations that meet the evolving needs of modern cloud environments.

Why we need Terraform Variables:

Terraform variables play a pivotal role in infrastructure as code (IaC) workflows, offering a multitude of benefits that significantly enhance the flexibility, maintainability, and scalability of infrastructure deployments. Here's why Terraform variables are essential:

  1. Flexibility: Terraform variables provide a mechanism to parameterize configurations, allowing users to customize infrastructure deployments without modifying the underlying code. By abstracting configurable values into variables, Terraform enables dynamic adjustments based on varying requirements, such as deploying resources in different regions, specifying instance types, or setting environment-specific parameters. This flexibility ensures that infrastructure configurations can adapt to evolving needs and diverse deployment scenarios without extensive manual intervention or code changes.

  2. Reusability: Variables promote code reuse by decoupling configuration details from specific deployments. Modular configurations can be developed with generic variables that are easily adapted to different environments or projects. This not only reduces duplication of code but also facilitates the creation of standardized templates or modules that can be shared across teams or projects. By leveraging reusable variables, organizations can streamline development efforts, improve consistency, and accelerate the deployment of infrastructure components.

  3. Abstraction: Abstracting configuration details into variables enhances the readability and comprehensibility of Terraform code. By assigning meaningful names to variables, developers can convey the purpose and significance of configurable values, making the code easier to understand and maintain. Additionally, local values allow users to define intermediate values or calculations, further improving code readability by encapsulating complex expressions or repetitive computations within named variables. This abstraction layer simplifies the management of infrastructure configurations, facilitating collaboration and knowledge sharing among team members.

  4. Automation: Variables enable automation by facilitating dynamic assignment of values based on external inputs or conditions. Automation scripts, continuous integration/continuous deployment (CI/CD) pipelines, or orchestration tools can leverage variables to drive infrastructure deployments with minimal manual intervention. Environment variables, in particular, provide a convenient mechanism for supplying values from external sources, allowing seamless integration with automated workflows. By automating the provisioning and configuration of infrastructure using variables, organizations can increase efficiency, reduce errors, and achieve faster time-to-market for their applications and services.

  5. Scalability: As infrastructure requirements evolve and grow, Terraform variables enable scalable management of configurations across large, complex environments. By parameterizing configurations, organizations can easily scale deployments to accommodate changes in workload, traffic patterns, or business needs. Whether deploying a single service or managing a multi-cloud, multi-region infrastructure, Terraform variables provide a flexible and scalable approach to provisioning and managing resources. This scalability empowers organizations to adapt to changing requirements, optimize resource utilization, and maintain consistency across diverse environments.

In summary, Terraform variables are indispensable tools for managing infrastructure as code effectively. By providing flexibility, reusability, abstraction, and automation capabilities, variables empower organizations to streamline development workflows, enhance collaboration, and achieve agility in deploying and managing infrastructure at scale. Embracing Terraform variables enables organizations to harness the full potential of infrastructure as code, driving innovation, efficiency, and resilience in the modern cloud-native landscape.

We can create a variables.tf file which will hold all the variables.

Create an EC2 machine and install the terraform pacakges:

Sure, here's a step-by-step guide on how to create an EC2 instance on AWS and install the Terraform packages:

  1. Sign in to the AWS Management Console: Go to the AWS Management Console (https://aws.amazon.com/console/) and sign in to your AWS account.

  2. Navigate to the EC2 Dashboard: Once logged in, navigate to the EC2 service by either typing "EC2" in the search bar or selecting it from the list of services under the "Compute" section.

  3. Launch Instance: On the EC2 dashboard, click the "Launch Instance" button to start the process of creating a new EC2 instance.

  4. Choose an Amazon Machine Image (AMI): In the "Step 1: Choose an Amazon Machine Image (AMI)" section, select an AMI for your EC2 instance. You can choose from a variety of Amazon-provided AMIs or use your own custom AMI.

  5. Choose an Instance Type: In the "Step 2: Choose an Instance Type" section, select the instance type that meets your requirements. For example, you can choose a t2.micro instance type for testing purposes, as it falls under the AWS Free Tier.

  6. Configure Instance Details: In the "Step 3: Configure Instance Details" section, configure the instance details such as the number of instances, network settings, and other options. You can leave most of the settings as default for a basic setup.

  7. Add Storage: In the "Step 4: Add Storage" section, specify the storage requirements for your EC2 instance. You can add additional EBS volumes if needed, but for a basic setup, the default settings should be sufficient.

  8. Add Tags (Optional): In the "Step 5: Add Tags" section, add any tags that you want to associate with your EC2 instance. Tags are key-value pairs that help you organize and manage your AWS resources.

  9. Configure Security Group: In the "Step 6: Configure Security Group" section, configure the security group settings for your EC2 instance. Make sure to allow SSH (port 22) access if you plan to connect to the instance using SSH.

  10. Review and Launch: In the "Step 7: Review Instance Launch" section, review the configuration settings for your EC2 instance. Once you're satisfied, click the "Launch" button.

  11. Select Key Pair: In the popup window, select an existing key pair or create a new key pair to connect to your EC2 instance securely via SSH. Then click "Launch Instances".

  12. View Instances: Once the instance is launched successfully, you can view it under the "Instances" section of the EC2 dashboard.

  13. Connect to the Instance: Use SSH to connect to your EC2 instance using the key pair you selected during launch. For example:

    ssh -i your-key.pem ec2-user@your-ec2-instance-public-ip
    
  14. Install Terraform: Once connected to the EC2 instance, you can install Terraform by downloading the appropriate package from the Terraform website (https://www.terraform.io/downloads.html) and following the installation instructions. For example, on a Linux-based EC2 instance:

    sudo yum install wget unzip -y
    wget https://releases.hashicorp.com/terraform/1.1.0/terraform_1.1.0_linux_amd64.zip
    unzip terraform_1.1.0_linux_amd64.zip
    sudo mv terraform /usr/local/bin/
    
  15. Verify Installation: After installing Terraform, verify the installation by running the following command:

    terraform --version
    

    You should see the Terraform version information printed to the console, confirming that Terraform has been successfully installed on your EC2 instance.

That's it! You've successfully created an EC2 instance on AWS and installed the Terraform packages on it. You can now use Terraform to provision and manage infrastructure as code.

We can create a variables.tf file which will hold all the variables.

filename.tf:

variable "filename" {
default = "/home/ubuntu/terrform-tutorials/terraform-variables/demo-var.txt"
}

variable "content" {
default = "This is coming from a variable which was updated"
}

Create a local file using Terraform Hint:

main.tf

resource "local_file" "devops" {
filename = var.filename
content = var.content
}

Now need to run terraform init command.

Now need to run plan command.

Now need to apply command.

Now go the /home/ubuntu/terrform-tutorials/terraform-variables/demo-var.txt and check we habe demo-var.txt file

Now you can see we have demo-var.txt file.

Now you can see we have also content this demo-var.txt file.