Terraform Import OCI Resources

Terraform allows you to re-create a state file (terraform.tfstate) with the import command.

For the import, you need to specify a resource type, name, and OCID. So you have to create a .tf file first. In this example we’ll import a compartment:


variable "tenancy_ocid" {}
variable "compartment_description" {}
variable "compartment_name" {}
resource "oci_identity_compartment" "test_compartment" {
    compartment_id = "${var.tenancy_ocid}"
    description = "${var.compartment_description}"
    name = "${var.compartment_name}"

We now have to find the OCID of the compartment we want to import. You can do this via the online console or via the command line client.

$ oci iam compartment list --all --output table --query "data[*].{name:name,ocid:\"compartment-id\"}"

Initialize Terraform:

$ terraform init

Now execute the import command and specify the resource type, name, and OCID:

$ terraform import oci_identity_compartment.test_compartment ocid1.compartment.xxxxx
Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

That’s it. You should now see a terraform.tfstate file with the compartment details in it.