Friday 15 March 2019

Use Terraform in the Oracle Cloud with Stacks

I already described how to use Terraform with the Oracle Cloud Infrastructure (OCI) from on-premise. But with the Resource Manager Stacks, Oracle offers a smart alternative to use Terraform with OCI.


The Resource Manager can be found in the Hamburger menu on the left side.


Click on 'Create Stack' to do so.


The Terraform files are needed in a single zip file, so we need to create some. Find my examples on GitHub.

network.tf
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
resource "oci_core_virtual_network" "VCN-Demo" {
  cidr_block     = "${var.VCN_SEDEMO_CIDR}"
  compartment_id = "${var.compartment_ocid}"
  display_name   = "VCN-Demo"
  dns_label      = "demovcn"
}

resource "oci_core_subnet" "SN_Bastion" {
  availability_domain = "${lookup(data.oci_identity_availability_domains.ADs.availability_domains[0],"name")}"
  cidr_block          = "${var.SN_BASTION_CIDR}"
  display_name        = "SN_Bastion"
  compartment_id      = "${var.compartment_ocid}"
  vcn_id              = "${oci_core_virtual_network.VCN-SE-Demo.id}"
  dns_label           = "snbastion"
}

I like to start with a Virtual Cloud Network (VCN) and a subnet, as these require minimal parameters.

data.tf
1
2
3
data "oci_identity_availability_domains" "ADs" {
  compartment_id = "${var.compartment_ocid}"
}

To avoid hard coding the ocid's of the Availbility Domains (ADs), I query the ADs from the compartment.

variables.tf
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
variable "compartment_ocid" {}
variable "region" {}

#########   CIDR  #################

variable "VCN_SEDEMO_CIDR" {
  default = "10.0.0.0/16"
}

variable "SN_BASTION_CIDR" {
  default = "10.0.1.0/24"
}

As with a standard Terraform script, I query the compartment_ocid and region from the environment and set two CIDR blocks for the VCN and the subnet.

provider.tf

1
2
3
provider "oci" {
  region = "${var.region}"
}

Now for the provider.tf, this one gets rather short. As we are already logged into oci, we do not need to handle the key file or user_ocid.


Pack those four files into a zip archive and upload them to the create Stack dialog.


We cannot source the variables via shell, but we can add these to the create dialog and we are done here.


To use the newly created Stack, click on its name or from the menu choose Edit.


Here you can do the usual Terraform plan, apply and destroy actions. Click on Plan and confirm the dialog.


In the Jobs list, you will see a new Terraform Job. Click on its name to see the details. It should succeed and on the bottom you will see the Terraform output.
After that, use Terraform Actions | Apply to create the resources, which should result in a


1
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

So this is a smart option to use Terraform with OCI without the need of a client software installation or a seperate vm to run the scripts, which could save time and money.