Repository navigation
LAB 44 ‐ Create instance through terraform and stack
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.
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
To create an OCI Compute Instance manually, you would:
- Log in to the OCI Console.
- Navigate to Compute → Instances.
- Select the Compartment.
- Enter the Instance Name.
- Select the Availability Domain.
- Choose the Image and Shape.
- Select the VCN and Subnet.
- Configure SSH Keys.
- Click Create Instance.
Every time a new environment is required, these steps must be repeated manually.
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 applyTerraform automatically provisions the infrastructure defined in the configuration file.
Infrastructure as Code (IaC) is the practice of managing and provisioning infrastructure through code rather than manual processes.
- Consistency
- Automation
- Version Control
- Faster Deployments
- Reduced Human Error
- Easy Rollback and Recovery
Terraform follows a simple workflow:
Write Configuration
│
▼
terraform init
│
▼
terraform plan
│
▼
terraform apply
│
▼
Infrastructure Created
│
▼
terraform destroy
(Optional Resource Cleanup)
Create Terraform configuration files (.tf) that define the desired infrastructure.
Example:
resource "oci_core_instance" "app_server" {
display_name = "app-server"
}Initialize the working directory and download required provider plugins.
terraform initPurpose:
- Downloads the OCI Provider
- Initializes the Terraform working directory
- Prepares Terraform for execution
Review the changes Terraform will make before deployment.
terraform planTerraform compares:
- Current Infrastructure State
- Desired Configuration
And generates an execution plan.
Create or modify resources.
terraform applyTerraform provisions the infrastructure according to the configuration.
Remove resources managed by Terraform.
terraform destroyUseful for:
- Lab environments
- Temporary resources
- Testing deployments
+-------------------+
| Terraform Config |
| (*.tf Files) |
+---------+---------+
|
▼
+-------------------+
| Terraform Core |
+---------+---------+
|
▼
+-------------------+
| OCI Provider |
+---------+---------+
|
▼
+-------------------+
| Oracle Cloud OCI |
+-------------------+
Contains infrastructure definitions written in HCL (HashiCorp Configuration Language).
Processes configuration files and determines what actions need to be performed.
Acts as a bridge between Terraform and OCI APIs.
Examples include:
- Compute Instances
- VCNs
- Subnets
- Route Tables
- Security Lists
- Network Security Groups (NSGs)
- Load Balancers
- Block Volumes
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.
Terraform Configuration
│
▼
terraform.tfstate
│
▼
OCI Resources
- 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.
- The
terraform.tfstatefile is created automatically after a successfulterraform apply. - Terraform updates the state file whenever infrastructure changes are made.
- A backup file named
terraform.tfstate.backupis 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.
| 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 |
| 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 |
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
- Infrastructure as Code (IaC)
- Consistent Deployments
- Reusable Configurations
- Faster Provisioning
- Version Control Integration
- Reduced Operational Errors
- Easy Resource Management
- Multi-Cloud Support
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.
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)
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.
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.
Now open code editor within OCI
press ctrl+s, give the name instance.tf and click on save to save the file
now copy the entire content of main.tf
and paste it here in the code editor
now right click on the file name(instance.tf here) and then click on open in integrated terminal
now in terminal type terraform init
now in terminal type terraform plan
throwing an error here
remove this line, save the file and run again terraform plan
again throwing an error
add this provider block
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.
Once again, the terraform plan command is hanging during execution
Now add this line
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
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
throwing an error
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.
now it has been initialized successfully
Now run terraform plan
ran successfully
Now run terraform apply
instance has been created successfully you can check in console now
instace has been created with only private IP
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"
Now you can check in console that this instance that I have created just now is in stopped mode
to again run the instance type
state = "RUNNING"
save the file and then run terraform plan and then terraform apply .
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 -destroyThis command provides a detailed execution plan showing all resources that Terraform intends to remove.
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 destroywill 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.
If only a specific resource needs to be deleted, use the -target option.
terraform destroy -target=oci_core_instance.database_serverIn this example, only the database_server instance will be destroyed, while all other Terraform-managed resources will remain unchanged.
terraform destroy -target=oci_core_instance.terraform_serverThis command destroys only the terraform_server instance.
Always follow this sequence before deleting infrastructure:
terraform plan -destroy
terraform destroyThis 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.
instance has been terminated, now you can check in console
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.