Terraform can import existing infrastructure resources. This functionality lets you bring existing resources under Terraform management. Terraform is not able to auto- generate configurations for those imported modules, for now, and requires you to first write the resource definition in Terraform and then import this resource. Import will find the existing resource from ID and import it into your Terraform state at the given ADDRESS.
Additional Tips:
- The terraform import command establishes a link between the existing OCI resourceand your Terraform configuration, but you need to define and manage its attributes within Terraform.
- Be cautious about importing resources, ensuring that each remote object is associated with only one Terraform resource. Importing the same object multiple times may lead to unexpected behavior.
- You may need to run additional terraform import commands for other resources.
Lets consider an example
Steps to Import an Existing OCI Resource into Terraform
- Define the Resource in Your Terraform Configuration
- First, you need to define the resource you want to import in a
.tf
file. For example, if you are importing an OCI compartment, you would write the resource definition like this:
- First, you need to define the resource you want to import in a
2. Run the Import Command
- Once the resource is defined, you can run the
terraform import
command. This command connects the existing resource in OCI to Terraform’s state, allowing it to be managed by Terraform. - For example, to import a compartment, use the following command:
Here replace the example with “test” and YOUR_COMPARTMENT_ID with “ id of the compartment which you want to import.
3. Verify the Resource Import
- After the import, use the
terraform plan
command to see if everything matches. Terraform will show any differences between the existing resource and the defined configuration.
terraform plan
4. Apply the Configuration
- Once everything looks good, use the
terraform apply
command to apply any changes or updates to the imported resource. This will make sure that the resource is correctly managed under Terraform.
terraform apply
“How the Terraform Import Command Helps Manage Existing Resources”