Skip to content

LAB 44 ‐ Create instance through terraform and stack

DevWithNehaCloud edited this page Jun 27, 2026 · 18 revisions

Terraform Overview

What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows you to define, provision, and manage cloud infrastructure using simple configuration files instead of manually creating resources through a cloud console.

With Terraform, infrastructure is described as code in .tf (Terraform) files, making deployments automated, repeatable, and version-controlled.

Instead of performing multiple manual steps in the OCI Console, you can define your infrastructure once and let Terraform create and manage it automatically.


Why Use Terraform?

Terraform helps organizations:

  • Automate infrastructure deployment
  • Eliminate manual configuration errors
  • Maintain consistency across environments
  • Track infrastructure changes through version control
  • Reuse infrastructure configurations
  • Deploy resources faster and more efficiently

Example: Traditional Method vs Terraform

Traditional Manual Method

To create an OCI Compute Instance manually, you would:

  1. Log in to the OCI Console.
  2. Navigate to Compute → Instances.
  3. Select the Compartment.
  4. Enter the Instance Name.
  5. Select the Availability Domain.
  6. Choose the Image and Shape.
  7. Select the VCN and Subnet.
  8. Configure SSH Keys.
  9. Click Create Instance.

Every time a new environment is required, these steps must be repeated manually.

Terraform Method

Instead, define the infrastructure in a Terraform configuration file:

resource "oci_core_instance" "web_server" {
  display_name = "web-server"

  shape = "VM.Standard.E4.Flex"

  create_vnic_details {
    subnet_id = var.subnet_id
  }
}

Then execute:

terraform init
terraform plan
terraform apply

Terraform automatically provisions the infrastructure defined in the configuration file.


Infrastructure as Code (IaC)

Infrastructure as Code (IaC) is the practice of managing and provisioning infrastructure through code rather than manual processes.

Benefits of IaC

  • Consistency
  • Automation
  • Version Control
  • Faster Deployments
  • Reduced Human Error
  • Easy Rollback and Recovery

Terraform Core Workflow

Terraform follows a simple workflow:

Write Configuration
        │
        ▼
 terraform init
        │
        ▼
 terraform plan
        │
        ▼
 terraform apply
        │
        ▼
 Infrastructure Created
        │
        ▼
 terraform destroy
(Optional Resource Cleanup)

Step 1: Write Configuration

Create Terraform configuration files (.tf) that define the desired infrastructure.

Example:

resource "oci_core_instance" "app_server" {
  display_name = "app-server"
}

Step 2: Terraform Init

Initialize the working directory and download required provider plugins.

terraform init

Purpose:

  • Downloads the OCI Provider
  • Initializes the Terraform working directory
  • Prepares Terraform for execution

Step 3: Terraform Plan

Review the changes Terraform will make before deployment.

terraform plan

Terraform compares:

  • Current Infrastructure State
  • Desired Configuration

And generates an execution plan.


Step 4: Terraform Apply

Create or modify resources.

terraform apply

Terraform provisions the infrastructure according to the configuration.


Step 5: Terraform Destroy (Optional)

Remove resources managed by Terraform.

terraform destroy

Useful for:

  • Lab environments
  • Temporary resources
  • Testing deployments

Terraform Architecture

+-------------------+
| Terraform Config  |
|    (*.tf Files)   |
+---------+---------+
          |
          ▼
+-------------------+
| Terraform Core    |
+---------+---------+
          |
          ▼
+-------------------+
| OCI Provider      |
+---------+---------+
          |
          ▼
+-------------------+
| Oracle Cloud OCI  |
+-------------------+

Components

Terraform Configuration

Contains infrastructure definitions written in HCL (HashiCorp Configuration Language).

Terraform Core

Processes configuration files and determines what actions need to be performed.

OCI Provider

Acts as a bridge between Terraform and OCI APIs.

OCI Resources

Examples include:

  • Compute Instances
  • VCNs
  • Subnets
  • Route Tables
  • Security Lists
  • Network Security Groups (NSGs)
  • Load Balancers
  • Block Volumes

Terraform State File

Terraform maintains a state file named:

terraform.tfstate

The state file keeps track of resources created by Terraform and maps them to actual cloud resources.

State File Workflow

Terraform Configuration
          │
          ▼
    terraform.tfstate
          │
          ▼
     OCI Resources

Why is the State File Important?

  • Tracks existing infrastructure
  • Detects configuration changes
  • Prevents duplicate resource creation
  • Maintains resource mapping

When Terraform creates or manages infrastructure resources, it automatically generates a Terraform State File (terraform.tfstate).

The state file stores information about the resources managed by Terraform, such as:

  • Resource IDs
  • Resource attributes
  • Current infrastructure state
  • Resource dependencies

Terraform uses this file to compare the current infrastructure state with the desired configuration defined in the .tf files and determine what changes need to be applied.

Important Notes

  • The terraform.tfstate file is created automatically after a successful terraform apply.
  • Terraform updates the state file whenever infrastructure changes are made.
  • A backup file named terraform.tfstate.backup is also maintained automatically.
  • The state file is critical for Terraform operations and should not be modified manually.

Note: The Terraform State File is stored in JSON format. Although it can be opened and edited manually, direct modification of the state file is not recommended, as it may create inconsistencies between Terraform and the actual infrastructure.

Frequently Used Terraform Commands

Command Description
terraform init Initialize Terraform
terraform validate Validate configuration syntax
terraform fmt Format Terraform files
terraform plan Preview infrastructure changes
terraform apply Create or update resources
terraform show Display Terraform state information
terraform destroy Delete managed resources

Terraform vs Traditional Manual Method

Feature Terraform Manual Console Method
Automation ✅ Yes ❌ No
Repeatability ✅ High ❌ Low
Version Control ✅ Supported ❌ Not Supported
Deployment Speed ✅ Fast ❌ Slower
Human Error ✅ Reduced ❌ Higher
Scalability ✅ Excellent ❌ Limited
Infrastructure Documentation ✅ Built into Code ❌ Separate Documentation Required
Multi-Environment Deployment ✅ Easy ❌ Time Consuming
Resource Reusability ✅ High ❌ Low

Common OCI Resources Managed by Terraform

Terraform can automate the creation and management of:

  • Compute Instances
  • Virtual Cloud Networks (VCNs)
  • Public and Private Subnets
  • Internet Gateways
  • NAT Gateways
  • Service Gateways
  • Route Tables
  • Security Lists
  • Network Security Groups (NSGs)
  • Load Balancers
  • Block Volumes
  • Object Storage Resources

Advantages of Terraform

  • Infrastructure as Code (IaC)
  • Consistent Deployments
  • Reusable Configurations
  • Faster Provisioning
  • Version Control Integration
  • Reduced Operational Errors
  • Easy Resource Management
  • Multi-Cloud Support

Conclusion

Terraform enables administrators and DevOps engineers to manage OCI infrastructure through code rather than manual console operations.

By following Infrastructure as Code (IaC) principles, Terraform provides:

  • Automation
  • Consistency
  • Repeatability
  • Scalability
  • Efficient Infrastructure Management

This makes Terraform one of the most widely adopted tools for modern cloud infrastructure deployment and management.

Steps to Create Instance through terraform and stack

Step 1. First create instance in OCI console

image

Step 2 Create Stack

Stack Configuration

In the Stack configuration page, all settings are already configured with the default values, so no changes are required. Simply review the details and click Next.

Things to Check

Stack Name: terraform-dev-instance

Compartment: Hub_compute_and_storage_compartment

Terraform Version: 1.5.x (Latest version available for the stack)

image image image image

Important Note

On the Review page, there is a checkbox option called Run Apply.

Do not select this checkbox. If you enable Run Apply and then click Create, OCI will immediately execute the Terraform configuration and create the instance automatically.

but as of now our objective is only to create the Stack and review the Terraform scripts generated by the stack. Therefore, leave the Run Apply checkbox unchecked and click Create directly.

Download the Terraform Configuration

Now we will download the Terraform Configuration file in to our local computer. This file contains all the Terraform scripts generated by the stack and can be used later for review, modification, or deployment.

image image

Now open code editor within OCI

image image image

press ctrl+s, give the name instance.tf and click on save to save the file

image

now copy the entire content of main.tf

image

and paste it here in the code editor

image

now right click on the file name(instance.tf here) and then click on open in integrated terminal

image

now in terminal type terraform init

image image

now in terminal type terraform plan

image

throwing an error here

image

remove this line, save the file and run again terraform plan

image

again throwing an error

image

add this provider block

image

you can take the provider details from here and download the private key

After downloading the private key (.pem) file, copy its entire contents and create a new file named privkey.pem in your code editor. Paste the copied private key content into this file and save it.

Next, update the provider block in your Terraform configuration and specify the path to this privkey.pem file. This enables Terraform to use the private key for authentication when connecting to OCI.

image image image

Once again, the terraform plan command is hanging during execution

Now add this line

image

Terraform plan was hanging because the OCI Cloud Shell environment was defaulting to Instance Principal authentication. The OCI Provider ignored the API key credentials specified in the provider block. Explicitly setting auth = "APIKey" in the OCI provider configuration resolved the issue and Terraform was able to generate the execution plan successfully.

After adding this line, the terraform plan command executed successfully without any errors.

Now run the command terraform apply

type yes

Now check in console instance has been created successfully

image image

Now I am creating another terraform-database-server in private subnet only with private IP using terraform script. this time i will not take help of OCI console, I already have a script I will only modify it and create an instance

image image image

throwing an error

image

delete the provider block because in the same directory int should be only once and give the unique instance name here(this name is not the name that will be visible in console) and save the file again

Terraform treats all .tf files within the same directory as a single configuration. Therefore, the default OCI provider configuration should be defined only once. Defining multiple default provider "oci" blocks in the same Terraform configuration will result in a Duplicate Provider Configuration error.

image

now it has been initialized successfully

image image

Now run terraform plan

image

ran successfully

Now run terraform apply

image image

instance has been created successfully you can check in console now

image

instace has been created with only private IP

image

To stop an OCI Compute Instance using Terraform, update the instance resource by setting the state attribute to STOPPED save the file and then run terraform plan and then terraform apply .

  state = "STOPPED"
image

Now you can check in console that this instance that I have created just now is in stopped mode

image

to again run the instance type

state = "RUNNING" 

save the file and then run terraform plan and then terraform apply .

image

Important Considerations Before Running Terraform Destroy

Before executing the terraform destroy command, it is recommended to review the resources that Terraform plans to delete.

Use the following command to preview the resources that will be destroyed:

terraform plan -destroy

This command provides a detailed execution plan showing all resources that Terraform intends to remove.

Why Review the Destroy Plan?

Terraform manages resources based on its current state file (terraform.tfstate). If multiple resources exist within the same Terraform configuration, the terraform destroy command will attempt to delete all resources managed by that state.

For example, if the current Terraform configuration contains two compute instances:

  • Terraform Server
  • Database Server

Running the following command:

terraform destroy

will destroy both instances, along with any other resources managed by the Terraform state.

Therefore, reviewing the destroy plan before execution helps prevent accidental deletion of critical resources.


Destroying a Specific Resource

If only a specific resource needs to be deleted, use the -target option.

Example: Destroy a Specific OCI Compute Instance

terraform destroy -target=oci_core_instance.database_server

In this example, only the database_server instance will be destroyed, while all other Terraform-managed resources will remain unchanged.

Another Example

terraform destroy -target=oci_core_instance.terraform_server

This command destroys only the terraform_server instance.


Recommended Workflow

Always follow this sequence before deleting infrastructure:

terraform plan -destroy
terraform destroy

This approach allows you to:

  • Review the resources that will be deleted.
  • Validate the destroy operation before execution.
  • Avoid accidental removal of production or shared infrastructure.
  • Ensure only the intended resources are affected.
image image image image image image image

instance has been terminated, now you can check in console

image

Create Instance through Stack using GUI

1. Save the Instance Configuration as a Stack

In the OCI Console, begin creating a Compute Instance and provide all the required configuration details. On the Review page, click Save as Stack instead of Create. This action saves the instance configuration as an OCI Resource Manager Stack, allowing the resource to be provisioned and managed using Terraform within OCI.

image image

2: Verify the Created Stack in Resource Manager

After clicking Save as Stack, the stack is created in OCI Resource Manager. Navigate to Developer Services → Resource Manager → Stacks and verify that the newly created stack appears in the list with an Active status.

image

3: Open the Stack and Run a Plan Job

Open the newly created stack in Resource Manager and run a Plan job. The Plan job analyzes the Terraform configuration and displays the resources that will be created, modified, or deleted without actually provisioning any resources.

image image

4: Review the Plan Job Output

Once the Plan job completes successfully, navigate to the Jobs section of the stack and review the plan output. Verify the resources that Terraform intends to create and ensure the configuration is correct before proceeding with the Apply operation.

image

5: Run the Apply Job

After reviewing the Plan job output, click Apply to provision the resources defined in the Terraform configuration. The Apply job executes the Terraform code and creates the required resources in OCI.

image image

6: Review the Apply Job Output

Once the Apply job completes, navigate to the Jobs section of the stack and verify that the job status is Succeeded, confirming that the resources have been created successfully.

image

7: Verify the Created Compute Instance

After the Apply job completes successfully, navigate to the OCI Console and verify that the Compute Instance has been created and is running as expected.

image

8: Run the Destroy Job

To remove the resources created by the stack, open the stack in OCI Resource Manager and run a Destroy job. The Destroy job executes the Terraform configuration in reverse and deletes all resources managed by the stack.

Running a Plan job before Destroy is optional. If required, you can run a plan to review the resources that will be deleted. However, in most cases, you can directly execute the Destroy job from the stack without running a plan first.

image image image image image

9: Review the Destroy Job Output

Once the Destroy job completes, navigate to the Jobs section of the stack and verify that the job status is Succeeded, confirming that all resources managed by the stack have been deleted successfully.

image

10: Verify Resource Deletion

After the Destroy job completes successfully, navigate to the OCI Console and verify that the Compute Instance and any other resources created by the stack have been removed successfully. This confirms that all resources managed by the stack have been deleted as expected.

image

Clone this wiki locally