IT Blog

Quick Tips Tutorials

Terraform to manage Oracle Cloud Infrastructure (OCI) Part-1

Overview

This tutorial shows how to set up Terraform to manage Oracle Cloud Infrastructure (OCI), configure the OCI CLI on macOS and Windows, and create an OCI compartment with Terraform. It includes sample commands, Terraform code snippets, configuration tips, and suggested places where you would add graphical snapshots in your documentation or blog. References to official OCI and Terraform guides are included for each major step docs.oracle.com docs.oracle.com docs.oracle.com Terraform Registry HashiCorp Developer.


Terraform is a powerful Infrastructure as Code (IaC) tool that allows you to define and provision cloud resources in a declarative way. This guide will walk you through setting up Terraform with Oracle Cloud Infrastructure (OCI), covering the OCI CLI configuration on both Mac and Windows, creating OCI compartments, and demonstrating some practical use cases.

Prerequisites

Before you begin, ensure you have the following:

  • An Oracle Cloud Infrastructure (OCI) account.
  • Basic understanding of command-line interfaces.
  • Basic understanding of cloud concepts.

Step 1: Install and Configure the OCI Command Line Interface (CLI)

The OCI CLI is essential for interacting with OCI resources from your local machine, and Terraform will use its configuration to authenticate.

1.1 Install OCI CLI on Mac

  1. Open Terminal: You can find Terminal in Applications > Utilities.
  2. Download and Run the Install Script: OCI provides a convenient install script. Run the following command:

Bash

bash -c "$(curl -L https://raw.githubusercontent.com/oracle/oci-cli/master/scripts/install/install.sh)"
  1. Follow the Prompts: The script will ask you for the installation location, Python executable, and whether to add the CLI to your PATH. It’s generally recommended to accept the default options unless you have specific requirements.
Article content
  1. Verify Installation: Once installed, open a new terminal session and run:

Bash

oci --version

This should display the installed OCI CLI version.

3.62.0

1.2 Install OCI CLI on Windows

  1. Download the Installer: Go to the official OCI CLI documentation page or directly download the Windows installer https://github.com/oracle/oci-cli/releases/tag/v3.68.0 Look for the “Installer for Windows (64-bit)” link.
Article content
  1. Run the Installer: Execute the downloaded .msi file. The installer will guide you through the process.
Article content
  1. Accept Defaults: You can typically accept the default installation paths. Ensure “Add OCI CLI to PATH” is checked.
  1. Verify Installation: Open a new Command Prompt or PowerShell window and run:

Bash

oci --version

You should see the installed OCI CLI version.

1.3 Configure OCI CLI

After installation, you need to configure the CLI with your OCI user credentials.

  1. Run oci setup config: In your terminal (Mac) or Command Prompt/PowerShell (Windows), run:

Bash

oci setup config
  1. Provide Information: The utility will prompt you for the following: User OCID: You can find this in the OCI Console under Identity & Security > Users. Click on your user and copy the OCID. Tenancy OCID: You can find this in the OCI Console under Tenancy Details (click on the hamburger menu at the top left, then Governance & Administration > Tenancy Details). Region: Your OCI home region (e.g., ap-melbourne-1 default, which will create a new key pair for you.
Article content
  1. Upload Public Key to OCI Console: The oci setup config command creates a private key (oci_api_key.pem) and a public key (oci_api_key_public.pem). You need to upload the content of oci_api_key_public.pem to your OCI user. Open oci_api_key_public.pem with a text editor and copy its entire content. In the OCI Console, navigate to Identity & Security > Users. Click on your user, then click “API Keys” on the left. Click “Add API Key,” choose “Paste Public Key,” and paste the content.
Article content
Article content

Step 2: Install Terraform

Now that your OCI CLI is configured, let’s install Terraform.

  1. Download Terraform: Go to the official Terraform downloads page: https://www.terraform.io/downloads.
  2. Choose Your Operating System: Download the appropriate package for Mac (amd64 or arm64) or Windows (amd64).
  3. Install Terraform: Mac: Unzip the downloaded package. Move the terraform executable to a directory in your PATH (e.g., /usr/local/bin). Windows: Unzip the downloaded package. Create a new folder (e.g., C:\terraform) and place the terraform.exe file there. Then, add this folder to your system’s PATH environment variable.
  4. Verify Installation: Open a new terminal or Command Prompt and run:

Bash

terraform --version

This should display the installed Terraform version

Reference: Quickstart and CLI config pages docs.oracle.com docs.oracle.com.


3. Prepare API keys and SSH keys for Terraform authentication

Generate an RSA key pair for API signing (example on macOS/Linux): 
mkdir -p ~/.oci openssl genrsa -out ~/.oci/oci_api_key.pem 2048 openssl rsa -pubout -in ~/.oci/oci_api_key.pem -out ~/.oci/oci_api_key_public.pem
  1. Upload the public key in the OCI Console under your user (User → API Keys → Add Public Key) or use the CLI to upload. Note the key fingerprint added to your user entry.
  2. Ensure the private key file has restrictive permissions:
Article content
chmod 600 ~/.oci/oci_api_key.pem

OCI Console user API Keys page showing uploaded public key and fingerprint]

Guidance: The API key links your CLI/Terraform sessions to your OCI user and is required for provider authentication docs.oracle.com.


4. Install Terraform and OCI Provider

  1. Install Terraform (macOS Homebrew or Windows Chocolatey): macOS: brew install terraform Windows (Chocolatey): choco install terraform
  2. Create a Terraform working directory, e.g., ~/tf-oci-compartment. Create a versions.tf to pin Terraform and provider versions:
terraform {
  required_version = ">= 1.5.0"
  required_providers {
    oci = {
      source  = "oracle/oci"
      version = ">= 7.0.0"
    }
  }
} 
  1. Initialize Terraform in the directory:
terraform init 
  • terraform init output showing OCI provider download and initialization

Reference: HashiCorp Terraform OCI tutorials and Oracle provider docs HashiCorp Developer Terraform Registry.


5. Configure Terraform to use OCI credentials

Option A — Use environment variables (suitable for CI/CD and temporary sessions):

export OCI_TENANCY=<tenancy_ocid>
export OCI_USER=<user_ocid>
export OCI_FINGERPRINT=<api_key_fingerprint>
export OCI_KEY_FILE=~/.oci/oci_api_key.pem
export OCI_REGION=us-ashburn-1 

Option B — Use a provider block referencing the CLI config profile (recommended when ~/.oci/config exists):

provider "oci" {
  tenancy_ocid     = var.tenancy_ocid
  user_ocid        = var.user_ocid
  fingerprint      = var.fingerprint
  private_key_path = var.private_key_path
  region           = var.region
} 

Define variables in variables.tf and sensitive values in terraform.tfvars or environment variables for security. Confirm provider setup by running:

terraform plan 

terraform plan output showing provider configuration OK


6. Terraform example: Create an OCI Compartment

Create compartment.tf:

resource "oci_identity_compartment" "example_compartment" {
  name        = "demo-compartment"
  description = "Terraform-managed compartment for demos"
  compartment_id = var.tenancy_ocid
  enable_delete  = true
  freeform_tags = {
    created_by = "terraform"
    project    = "demo"
  }
} 

Create outputs.tf:

output "compartment_ocid" {
  value = oci_identity_compartment.example_compartment.id
} 

Workflow:

  1. terraform init (if not done).
  2. terraform fmt to format files.
  3. terraform validate.
  4. terraform plan -out=tfplan.
  5. terraform apply “tfplan”.

Notes:

  • By default, Terraform will not delete compartments unless enable_delete = true is set and the compartment is empty Terraform Registry.
  • If a compartment with the same name exists and is unmanaged, provider behaviour may import or update it depending on configuration; exercise caution when multiple configs manage shared compartments Terraform Registry.
  • terraform apply confirming creation and output showing compartment_ocid]

Reference: Create a Compartment tutorial and provider resource docs docs.oracle.com Terraform Registry.


7. Use cases and examples

  1. Single-tenant dev environment:
  2. Automated environment provisioning:
  3. Policy-driven multi-account models:
  4. Reusable module example (module skeleton):
# modules/compartment/main.tf
resource "oci_identity_compartment" "this" {
  name           = var.name
  description    = var.description
  compartment_id = var.parent_compartment_id
  enable_delete  = var.enable_delete
  freeform_tags  = var.tags
}

# modules/compartment/variables.tf
variable "name" {}
variable "description" { default = "" }
variable "parent_compartment_id" {}
variable "enable_delete" { default = false }
variable "tags" { default = {} } 

Instantiate module:

module "project_compartment" {
  source = "./modules/compartment"
  name = "project-x"
  parent_compartment_id = var.tenancy_ocid
  enable_delete = true
  tags = { owner = "team-x" }
} 

Recommendation: Keep compartments small and lifecycle simple; use modules for repeatability and guardrails.

References: Simple infrastructure tutorial and Terraform Registry examples docs.oracle.com Terraform Registry.


8. Troubleshooting and best practices

  • IAM permission errors: ensure the user’s policy grants identity and compartment creation privileges. Test with the OCI Console or CLI before running Terraform.
  • Shared compartments: avoid multiple Terraform states managing the same compartment name; prefer explicit OCIDs when several teams interact. The provider can import existing compartments but this can create drift or conflicts Terraform Registry.
  • State management: use a remote state backend (e.g., Terraform Cloud, OCI Object Storage with locking) for team collaboration.
  • Secrets handling: never store private keys or secrets in plain text in VCS; use secret managers or CI/CD secret stores.

Reference: Provider and tutorial guidance on behavior and best practices Terraform Registry docs.oracle.com.


9. Suggested graphical snapshots to include in your article

  • OCI Console: User → API Keys page showing uploaded public key and fingerprint (for API auth).
  • macOS terminal: oci setup config interactive prompts and ~/.oci/config content.
  • Windows PowerShell: oci setup config and %USERPROFILE%.oci\config.
  • Terraform directory: file tree showing versions.tf, provider.tf, compartment.tf.
  • terraform plan and terraform apply outputs with created resource OCID.
  • OCI Console: Compartments list showing the newly created compartment and tags.

Quick reference commands

  • Install OCI CLI (macOS): brew install oci-cli docs.oracle.com.
  • Setup OCI CLI: oci setup config docs.oracle.com.
  • Terraform init: terraform init HashiCorp Developer.
  • Create plan: terraform plan -out=tfplan.
  • Apply plan: terraform apply “tfplan”.

Final notes

This article is based followed official OCI and Terraform guidance: OCI CLI quickstart and configuration, Set Up OCI Terraform, and Create a Compartment tutorials, and provider documentation for the oci_identity_compartment resource docs.oracle.com docs.oracle.com docs.oracle.com Terraform Registry HashiCorp Developer. Use modules and remote state early, and keep IAM and key management secure when automating OCI with Terraform.

If you like my work, please provide feedback, support and reach out if you need further support

Author: Zak Khan

Email: zak@cosmicro.com.au

Leave a Reply

Your email address will not be published. Required fields are marked *