51_ Terraform Basics: Understanding Infrastructure as Code - Nirvan-Pandey/OCI_DOC GitHub Wiki

51_1: Introduction

Infrastructure as a Code (IaaC):

Infrastructure as Code (IaaC) is a modern provisioning and management way of computing infrastructure by which machine-readable scripts are utilized in lieu of physical hardware setup or interactive consoles. It offers several benefits like consistency, reproducibility, version control, and automation, thus positioning itself as one of the prominent DevOps and cloud computing paradigms.

Terraform:

Terraform is an open-source Infrastructure as Code (IaC) tool that allows users to define and provision infrastructure using a declarative configuration language. It enables automation, scalability, and repeatability in cloud infrastructure deployment.

With Terraform, you can manage resources across multiple cloud providers, including Oracle Cloud Infrastructure (OCI), AWS, Azure, and Google Cloud.

51_2: Why Use Terraform?

✅ Infrastructure as Code (IaC): Define infrastructure in code, making it repeatable and version-controlled.

✅ Multi-Cloud Support: Manage resources across multiple cloud providers.

✅ Declarative Syntax: Specify what you want instead of how to create it.

✅ State Management: Terraform maintains the state of infrastructure for tracking changes.

✅ Automated Provisioning: Reduces manual work and eliminates configuration drift.

51_3: Installing Terraform

Step 1: Download Terraform Terraform can be installed on Windows, Linux, or macOS. Download the latest version from the official Terraform official website

Step 2: Install Terraform

Windows: Extract the downloaded .zip file and add the path to the system environment variables.

Linux/macOS: Run the following command:

sudo unzip terraform_<version>_linux_amd64.zip -d /usr/local/bin/terraform --version

This verifies that Terraform is installed correctly.

51_4: Understanding Terraform Workflow

Terraform follows a three-step process:

1️⃣ Write → Define infrastructure in a Terraform configuration file (.tf).

2️⃣ Plan → Preview the changes before applying them.

3️⃣ Apply → Execute the plan to provision infrastructure.

Basic Terraform Workflow

terraform init # Initialize Terraform

terraform plan # Preview the changes

terraform apply # Create or update infrastructure

terraform destroy # Delete infrastructure

51_5 : Writing a Basic Terraform Configuration

A Terraform configuration consists of three key elements:

Providers → Define cloud providers (OCI, AWS, Azure, etc.).

Resources → Define cloud resources (Compute, Networking, Storage).

Variables & Outputs → Store reusable values and return outputs.

51_6: Terraform_Basics_Setup_In_OCI

Step 1: Configure the OCI Provider

Create a file named provider.tf and add the following:

provider "oci" {
  tenancy_ocid     = "ocid1.tenancy.oc1..xxxxxxEXAMPLExxxxxx"  # Replace with your tenancy OCID
  user_ocid        = "ocid1.user.oc1..xxxxxxEXAMPLExxxxxx"    # Replace with your user OCID
  fingerprint      = "12:34:56:78:90:AB:CD:EF:12:34:56:78:90:AB:CD:EF"  # API Key fingerprint
  private_key_path = "/path/to/private_key.pem"  # Path to private key file
  region           = "us-ashburn-1"  # Set the region where resources will be created
}

✅ This tells Terraform how to connect to your OCI account.

Step 2: Create a Virtual Cloud Network (VCN) and Subnet

Create a file named network.tf and add the following:

resource "oci_core_vcn" "example_vcn" {
  cidr_block     = "10.0.0.0/16"  # Define the IP range for the network
  display_name   = "ExampleVCN"
  compartment_id = var.compartment_id  # Reference compartment ID from variables
}

resource "oci_core_subnet" "example_subnet" {
  cidr_block     = "10.0.1.0/24"  # Define subnet range
  vcn_id         = oci_core_vcn.example_vcn.id  # Attach subnet to the VCN
  display_name   = "ExampleSubnet"
  compartment_id = var.compartment_id
}

✅ This creates a VCN and a subnet for network communication.

Step 3: Create a Compute Instance

Create a file named compute.tf and add the following:

resource "oci_core_instance" "example_instance" {
  availability_domain = "Uocm:PHX-AD-1"  # Replace with your AD
  compartment_id      = var.compartment_id
  shape              = "VM.Standard2.1"  # Define the instance type

  create_vnic_details {
    subnet_id = oci_core_subnet.example_subnet.id  # Attach instance to subnet
  }

  source_details {
    source_type = "image"
    source_id   = "ocid1.image.oc1..xxxxxxEXAMPLExxxxxx"  # Replace with a valid image OCID
  }

  metadata = {
    ssh_authorized_keys = file("~/.ssh/id_rsa.pub")  # Path to public SSH key for access
  }
}

✅ This creates a virtual machine in OCI with SSH access.

Step 4: Initialize and Apply Configuration

Now, we will deploy the infrastructure using Terraform.

1️⃣ Initialize Terraform:

terraform init

🔹 Downloads required Terraform plugins for OCI.

2️⃣ Preview Changes:

terraform plan

🔹 Shows what Terraform will create before applying.

3️⃣ Apply Changes (Deploy the resources):

terraform apply

🔹 Confirms changes and provisions the resources. Type yes when prompted.

Step 5: Verify the Compute Instance

✔️ Log in to the OCI Console

✔️ Go to Compute → Instances

✔️ You should see your Terraform-created instance running

Step 6: Destroy the Infrastructure (Optional)

terraform destroy

🔹 This removes all Terraform-managed OCI resources.

51_7: Terraform State Management

Terraform maintains a state file (terraform.tfstate) to track infrastructure changes.

  • To check the current state:
terraform show
  • To refresh the state:
terraform refresh
  • To destroy the infrastructure:
terraform destroy

51_8: Best Practices for Using Terraform

✔ Use Remote State Storage → Store state files securely in an OCI Object Storage bucket or Terraform Cloud.

✔ Use Modules → Create reusable infrastructure components.

✔ Implement Version Control → Keep Terraform configurations in Git repositories.

✔ Automate with CI/CD → Integrate Terraform with CI/CD pipelines for automatic deployments.

✔ Least Privilege Principle → Use IAM roles and policies to restrict access.

51_9: Conclusion

Terraform simplifies infrastructure management by automating deployment, reducing manual effort, and ensuring consistency. By leveraging Infrastructure as Code (IaC), teams can efficiently manage cloud resources across different environments.

⚠️ **GitHub.com Fallback** ⚠️