OCI Terraform Part 2 - Terraform variables

Understanding and Using Variables in Terraform

Introduction to Variables and Why They're Important

In Terraform, variables play a crucial role in making your configuration flexible, reusable, and easy to manage. Without variables, every piece of information, like resource IDs or network configurations, would need to be hardcoded into your scripts, making them difficult to adapt to different environments or use cases. By using variables, you can separate the configuration from the code logic, allowing for easy changes without needing to modify the underlying code.

Types of Variables

Terraform supports various types of variables that you can use to parameterize your configurations. Here are the primary types:

String


variable "cms_string" {
  description = "A simple string variable"
  type        = string
  default     = "Hello, Terraform!"
}
    

Number


variable "cms_number" {
  description = "A simple number variable"
  type        = number
  default     = 42
}
    

Boolean


variable "cms_boolean" {
  description = "A simple boolean variable"
  type        = bool
  default     = true
}
    

List


variable "cms_list" {
  description = "A list of strings"
  type        = list(string)
  default     = ["value1", "value2", "value3"]
}
    

Map


variable "cms_map" {
  description = "A map of values"
  type        = map(string)
  default     = {
    key1 = "value1"
    key2 = "value2"
  }
}
    

How to Define, Use, and Override Variables

Scenario 1: Defining and Using Variables

Let's consider a scenario where you have variables defined in a variables.tf file, and you use these variables in your Terraform configuration:

variables.tf


variable "compartment_id" {
  description = "Root Compartment ID"
  type        = string
}

variable "network_compartment" {
  description = "Network compartment"
  type        = string
}

variable "cmsvcn" {
  description = "My VCN"
  type        = string
}
    

Usage in Configuration


resource "oci_identity_compartment" "compartment" {
  compartment_id = var.compartment_id
  name           = "cmsterraform"
  description    = "Compartment for compute"
}

resource "oci_core_vcn" "cmsvcn" {
  compartment_id = var.network_compartment
  cidr_block     = "10.0.0.0/16"
  display_name   = var.cmsvcn
}

resource "oci_core_subnet" "subnet1" {
  compartment_id = var.network_compartment
  cidr_block     = "10.0.1.0/24"
  vcn_id         = var.cmsvcn
}

resource "oci_core_subnet" "subnet2" {
  compartment_id = var.network_compartment
  cidr_block     = "10.0.2.0/24"
  vcn_id         = var.cmsvcn
  display_name   = "subnet2"
}
    

Scenario 2: Directly Referencing Resources

Sometimes, you may want to directly reference a resource’s attribute without defining a variable for it. Terraform automatically handles dependencies, so you can directly use resource attributes in your configuration:


resource "oci_core_vcn" "cmsvcn" {
  compartment_id = var.network_compartment
  cidr_block     = "10.0.0.0/16"
  display_name   = "cmsvcn"
}

resource "oci_core_subnet" "subnet1" {
  compartment_id = var.network_compartment
  cidr_block     = "10.0.1.0/24"
  vcn_id         = oci_core_vcn.cmsvcn.id
  display_name   = "subnet1"
}

resource "oci_core_subnet" "subnet2" {
  compartment_id = var.network_compartment
  cidr_block     = "10.0.2.0/24"
  vcn_id         = oci_core_vcn.cmsvcn.id
  display_name   = "subnet2"
}
    

Best Practices for Organizing Variables

Here are some best practices to consider when organizing your variables:

  • Group Related Variables Together: Keep related variables together in the same file or section to make them easier to manage.
  • Use Descriptive Names: Always use meaningful and descriptive names for your variables so that anyone reading the code can easily understand their purpose.
  • Provide Descriptions: Include descriptions for all variables. This helps others (or your future self) understand the role of each variable without needing to guess.
  • Set Defaults Where Possible: If a variable is likely to have the same value across multiple environments, consider setting a default value.
  • Separate Sensitive Variables: Keep sensitive variables (like passwords or API keys) in a separate file and use Terraform’s sensitive attribute to prevent them from being exposed.

Conclusion

Understanding and effectively using variables in Terraform is crucial for writing scalable, reusable, and maintainable infrastructure-as-code. By leveraging variables, you can easily manage different environments, configurations, and resources without hardcoding values, making your code more adaptable and less prone to errors.

In this post, we've explored the various types of variables, how to define and use them, and best practices for organizing them in your Terraform projects. As you continue working with Terraform, incorporating these practices will enhance your ability to manage complex infrastructures efficiently.

In the next part of this series, we will delve into more advanced Terraform topics, further expanding your knowledge and capabilities. Stay tuned, and don't hesitate to share your thoughts or questions in the comments below!

Getting Started with Terraform in OCI - Part 1

Getting Started with Terraform in OCI

In today’s, cloud-driven world, managing infrastructure efficiently isn’t just a nice-to-have—it’s essential. As businesses scales, the complexity of managing infrastructure grows, making automation a critical part of any IT strategy. This is where Infrastructure as Code (IaC) comes in, and Terraform is at the forefront of this revolution.

Provisioning manual infrastructure can be a feel good factor only when there is a limited resources to provision. Imagine to provision 100's compute with same configuration, it will end with frustration resulting in improper configuration or some other mistakes.

If you’re working with Oracle Cloud Infrastructure (OCI), this blog series is your guide to mastering Terraform. In this first post, we’ll cover the key concepts you need to understand before diving into code, followed by practical examples that you can try out yourself.

No Deep Theories—Just Practical Learning

Our focus in this series is on practical implementation. We won’t go deep into theories, but instead, will highlight the essential concepts that you need to understand. This post is all about getting hands-on with Terraform, using hardcoded values to declare your infrastructure. In later parts of this series, we’ll revisit the same infrastructure using advanced topics, such as variables, outputs, and modules, to make it more dynamic and scalable.

Step 1: Setting Up Your Environment

Before we jump into writing Terraform code, let’s get your environment set up. Whether you’re new to Terraform or just need a refresher, here’s what you’ll need:

  • Install Terraform: Follow the official installation guide to get it up and running on your machine.
  • Install Visual Studio Code (VS Code): Download it here.
  • Add the OCI Provider Plugin: To manage OCI resources, you’ll need to configure Terraform with the OCI provider.

Key Concepts in Terraform

Understanding Terraform’s core concepts is crucial to using it effectively. Let’s break down the most important ones, with practical insights along the way.

1. Providers

Providers are the link between Terraform and the services you want to manage. Think of them as plugins that extend Terraform’s capabilities. In our case, the OCI provider is what enables Terraform to create and manage resources in Oracle Cloud.

Practical Tip: Always ensure you’re using the latest version of the OCI provider to take advantage of new features and improvements.

2. Resources

Resources are the building blocks of your infrastructure. In Terraform, every cloud component, whether it’s a compute instance, a database, or a network, is defined as a resource. Each resource has attributes and properties that determine its configuration.

Practical Tip: When defining resources, start with hardcoded values to understand the basics. As you advance, you can use variables to make your code more dynamic and reusable.

3. State Management

Terraform keeps track of your infrastructure using state files. These files act as a snapshot of your managed resources, enabling Terraform to determine what changes need to be applied.

Practical Tip: Store your state files in a remote backend (like OCI Object Storage) when working in teams. This prevents conflicts and ensures everyone is working with the latest state.

Practical Examples

Now, let’s put these concepts into practice. Below are simple, hardcoded Terraform configurations to get you started. As you progress, you can expand these examples to match your specific needs.

1. Creating a Compartment

resource "oci_identity_compartment" "chetan" {
  #Required
  compartment_id = ""
  description    = "New compartment"
  name           = "ChetanTerraform"
}
            

2. Setting Up a Virtual Cloud Network (VCN)

resource "oci_core_vcn" "cms_vcn" {
    compartment_id = <"compartment-id">
    cidr_block = "10.0.0.0/16"
    display_name = "terraform_vcn"
  }
            

3. Creating a Load Balancer

resource "oci_load_balancer_load_balancer" "example_load_balancer" {
  compartment_id       = <"compartment-id">
  display_name         = "cms-load-balancer"
  shape                = "flexible"  # Can be "flexible" or a fixed shape like "100Mbps"
  shape_details {
    maximum_bandwidth_in_mbps = "10"
    minimum_bandwidth_in_mbps = "10"
  }
  subnet_ids           = [<"subnet.ocid">]
  is_private           = false  # Set to true for a private load balancer
  #idle_timeout_in_seconds = 300
}
            

4. Provisioning a Compute Instance

resource "oci_core_instance" "cms01" {
  availability_domain = <"AD-name">
  compartment_id      = <"compartment-id">
  shape               = "VM.Standard.A1.Flex"
  shape_config {
    ocpus = "1"
    memory_in_gbs = "6"
  }

  source_details {
    source_id               = <"image-ocid">
    source_type             = "image"
    boot_volume_size_in_gbs = "50"
  }
  display_name = "cms01"
  metadata = {
    ssh_authorized_keys = file(<"Path to key file">)
    }
  create_vnic_details {
    subnet_id = <"subnet.ocid">
  }
  preserve_boot_volume = "false"
}
            

This blog post is your launchpad into the world of Terraform with OCI. We’ve covered the essential concepts—providers, resources, and state management—and provided practical examples to get you started.

In this part, we’ve focused on hardcoded values for simplicity. In future posts, we’ll implement the same infrastructure using advanced topics like variables, outputs, and more.

Check out the complete code on GitHub here: https://github.com/cmschetan/OCI--Terraform/tree/main/Part-1

Stay tuned for the next blog in the series!