Using Terraform to Deploy an OCI Compartment (Easy)
Tags: oracle, cloud, devops, terraform
Published: 2023-06-19 17:28:21

Terraform is a devops tool that programmatically deploys cloud resources in a predictable, declarative way. It is a part of the Infrastructure as Code (IaC) environment that aims to safely create, change, and improve infrastructure using APIs without resorting to using the online console.

This is a guide to show an example usage of Terraform with regards to the Oracle Cloud Infrastructure (OCI). Substantially, how to deploy an OCI Compartment.

## How to Deploy an OCI Compartment

### 1. Install Terraform

Follow the official [installation page](https://developer.hashicorp.com/terraform/install) to install Terraform on your machine.

### 2. Configure the OCI Provider profile

To deploy OCI resources, you need access to manage the resources from your machine. This can be achieved using an API Key. To complete this step, see [Setting up the OCI Configuration File using API Keys](https://dev.to/farisdurrani/setting-up-the-oci-configuration-file-using-api-keys-96c).

### 3. Create a new directory, e.g., `terraform-test/`

### 4. Declaring the OCI resources

Your final file tree should look like this once this step is completed:
```txt
📦terraform-test
 ┣ 📜compartment-vars.tf
 ┣ 📜compartment.tf
 ┣ 📜provider.tf
 ┣ 📜terraform.tf
 ┗ 📜terraform.tfvars
```

In the file `terraform.tf`, we shall declare the provider, namely OCI:

```tf
# terraform.tf
terraform {
  required_providers {
    oci = {
      source  = "oracle/oci"
      version = ">= 5.0.0"
    }
  }
}
```

In the file `provider.tf`, we declare the profile to be used. This is required if you have multiple OCI profiles configured in `~/.oci/config` and the profile in question is not DEFAULT.

```tf
# provider.tf
provider "oci" {
  config_file_profile = "DEFAULT"
}
```

In `compartment.tf`, we declare the actual resources we want to deploy. 

In this example, we want to deploy an empty compartment inside another existing compartment (which may be the tenancy itself) with the name in the format `COMP-MyCompartmentName-HHmmss`.

```tf
# compartment.tf
locals {
  name_prefix = "COMP"
}

resource "oci_identity_compartment" "my_new_compartment" {
  #Required
  compartment_id = var.compartment_id
  description    = var.description
  name           = format("%s-%s", local.name_prefix, var.name)
  #Optional
  # defined_tags  = var.defined_tags
  enable_delete = true
  # freeform_tags = var.freeform_tags
}
```

Notice we have a few Terraform variables to fill.

In `compartment-vars.tf`, we declare the variables:

```tf
# compartment-vars.tf
#Required
variable "compartment_id" {
  description = "Compartment OCID"
  type        = string
}
variable "description" {
  description = "Compartment Description"
  type        = string
}
variable "name" {
  description = "Compartment Name"
  type        = string
}
```

And finally in `terraform.tfvars`, we initialize the variables:
```tf
# terraform.tfvars
compartment_id = "ocid1.compartment.oc1..aaaaaaaakbr7t5yqjirrmwm3ycg5jj4hytyaaparentcompartmentrewkhflkhwiuedh"
description    = "Test Compartment Description"
name           = "MyCompartment1"
```
where:
- `compartment_id` is the OCID of the compartment that will contain this new compartment. If the new compartment is a root compartment, put the tenancy OCID found in **Profile Picture** > **Tenancy**

Note: using the tfvars file is after all optional if you choose to hardcode the values in `compartment.tf`

### 5. Deploy

First, we initialize and validate the files:
```sh
terraform init
terraform fmt
terraform validate
```

Then, we write the plan:
```sh
terraform plan --out="plan.out"
```

And apply it:
```sh
terraform apply "plan.out"
```

If all goes well, we should see a success message:

![Terminal showing Terraform successful deployment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jobyx3qhziawlhan8hj8.png)


And of course, the deployed resource on OCI:

![OCI console showing successful deployment of compartment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/epic24xvo15zonnchukq.png)




## Destroying a Terraform deployment
To destroy everything deployed in the current plan, simply
```sh
terraform destroy
```

---

***Safe harbor statement***
The information provided on this channel/article/story is solely intended for informational purposes and cannot be used as a part of any contractual agreement. The content does not guarantee the delivery of any material, code, or functionality, and should not be the sole basis for making purchasing decisions. The postings on this site are my own and do not necessarily reflect the views or work of Oracle or Mythics, LLC.

*This work is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/).*