55 ‐ Terraform – Creating an OCI VCN with Internet Gateway - SanjeevOCI/Ocidocs GitHub Wiki
This lab demonstrates how to create a Virtual Cloud Network (VCN) in Oracle Cloud Infrastructure (OCI) using Terraform and attach an Internet Gateway for public access.
1. Get the VCN Creation Template
Go to Terraform Provider OCI Docs
and search for oci_core_vcn to get the VCN creation template.
2. Navigate to Code Editor
3. Write Terraform Code to Create a VCN
Create a new directory for your Terraform project and add the following files:
a. main.tf
provider "oci" {
region = "us-ashburn-1" // Replace with your desired region
}
resource "oci_core_vcn" "example_vcn" {
cidr_block = "10.0.0.0/16"
display_name = "example-vcn"
compartment_id = "ocid1.compartment.oc1..exampleuniqueID" // Replace with your compartment OCID
dns_label = "examplevcn"
}
b. variables.tf (Optional)
Define variables for reusability:
variable "compartment_id" {
description = "The OCID of the compartment where the VCN will be created"
type = string
}
variable "region" {
description = "The OCI region"
type = string
default = "us-ashburn-1"
}
variable "vcn_cidr" {
description = "The CIDR block for the VCN"
type = string
default = "10.0.0.0/16"
}
c. outputs.tf
Output the VCN details after creation:
output "vcn_id" {
value = oci_core_vcn.example_vcn.id
}
output "vcn_cidr_block" {
value = oci_core_vcn.example_vcn.cidr_block
}
4. Initialize Terraform
Run the following commands in your terminal from the project directory:
- Initialize Terraform:
terraform init
-
Validate the Configuration:
terraform validate -
Preview the Changes:
terraform plan -var="compartment_id=<your_compartment_ocid>" -
Apply the Configuration:
terraform apply -var="compartment_id=<your_compartment_ocid>"
5. Verify the VCN
After applying the configuration, you can:
- Check the output in the terminal for the VCN ID and CIDR block.
- Log in to the OCI Console and navigate to Networking > Virtual Cloud Networks to verify the VCN.
6. Clean Up (Optional)
To delete the VCN and associated resources:
terraform destroy -var="compartment_id=<your_compartment_ocid>"