Terraform: Set Up OCI Terraform

In this tutorial, you set up Oracle Cloud Infrastructure Terraform provider scripts, documented in the Terraform Registry, to connect to your account. To confirm the setup, you fetch information from your tenancy.

Key tasks include how to:

  • Create RSA keys.
  • Set up Oracle Cloud Infrastructure Terraform provider scripts:
    • Authenticate your Terraform scripts.
    • Get information about the availability domains in your tenancy.
A diagram of a user connected from a local environment to an Oracle Cloud Infrastructure tenancy. The local environment is Linux and has Terraform installed. There is an arrow from Terraform in the local environment connected to Terraform Registry in the cloud. There is a second arrow from the local environment sending a message to the user's Oracle Cloud Infrastructure tenancy labeled Authenticate?. The third arrow is from the tenancy to the local environment labeled Fetch Data. These arrows suggest that the user has set up their Terraform scripts to be authenticated by their tenancy. The user can then fetch information from the tenancy, by using Terraform and Terraform Registry. The tenancy displays three availability domains and that is the information that the user is fetching.

For additional information, see:

Before You Begin

To successfully perform this tutorial, you must have the following:

MacOS or Linux

1. Prepare

Prepare your environment for authenticating and running your Terraform scripts. Also, gather the information your account needs to authenticate the scripts.

Install Terraform

Install the latest version of Terraform v13.0+:

  1. In your environment, check your Terraform version.
    terraform -v
    If you don't have Terraform v13.0+, then install Terraform using the following steps.
  2. From a browser, go to Download Latest Terraform Release.
  3. Find the link for your environment and then copy the link address. Example for Linux 64-bit:
    https://releases.hashicorp.com/terraform/0.13.1/terraform_0.13.1_linux_amd64.zip
  4. In your environment, create a temp directory and change to that directory:
    mkdir temp
    cd temp
  5. Download the Terraform zip file. Example:
    wget https://releases.hashicorp.com/terraform/0.13.1/terraform_0.13.1_linux_amd64.zip
  6. Unzip the file. Example:
    unzip terraform_0.13.1_linux_amd64.zip
  7. Move the folder to /usr/local/bin or its equivalent in Mac. Example:
    sudo mv terraform /usr/local/bin
  8. Go back to your home directory:
    cd
  9. Check the Terraform version:
    terraform -v

    Example: Terraform v0.13.1.

Create RSA Keys

If you created RSA keys for the Terraform Set Up Resource Discovery tutorial, then skip this step.

Create RSA keys for API signing into your Oracle Cloud Infrastructure account.

  1. Open a terminal window.
  2. Make an .oci directory.
    mkdir $HOME/.oci
    Note

    If you are using Windows Subsystem for Linux (WSL), create the directory in your Linux $HOME directory. If you create the directory in a /mnt folder (Windows file system), WSL configuration changes are required to chmod files.
  3. Generate a 2048-bit private key in a PEM format:
    openssl genrsa -out $HOME/.oci/<your-rsa-key-name>.pem 2048
  4. Change permissions, so only you can read and write to the private key file:
    chmod 600 $HOME/.oci/<your-rsa-key-name>.pem
  5. Generate the public key:
    openssl rsa -pubout -in $HOME/.oci/<your-rsa-key-name>.pem -out $HOME/.oci/<your-rsa-key-name>_public.pem
  6. Copy the public key.
    In the terminal, enter:
    cat $HOME/.oci/<your-rsa-key-name>_public.pem
  7. Add the public key to your user account.
    • From your user avatar, go to User Settings.
    • Click API Keys.
    • Click Add Public Key.
    • Select Paste Public Keys.
    • Paste value from previous step, including the lines with BEGIN PUBLIC KEY and END PUBLIC KEY
    • Click Add.

You have now set up the RSA keys to connect to your Oracle Cloud Infrastructure account.

Reference

Generating RSA Keys

Add List Policy

If your username is in the Administrators group, then skip this section. Otherwise, have your administrator add the following policy to your tenancy:

allow group <the-group-your-username-belongs> to read all-resources in tenancy

With this privilege, you can list all the resources in your tenancy.

Steps to Add the Policy
  1. In the top navigation bar, open the Profile menu.
  2. Click your username.
  3. In the left pane, click Groups.
  4. In a notepad, copy the Group Name that your username belongs.
  5. Open the navigation menu and click Identity & Security. Under Identity, click Policies.
  6. Click Create Policy.
  7. Fill in the following information:
    • Name: list-resources
    • Description: Allow the group <the-group-your-username-belongs> to list the resources in this tenancy.
    • Compartment: <your-tenancy>(root)
  8. For Policy Builder, click Customize (Advanced).
  9. Paste in the following policy:
    allow group <the-group-your-username-belongs> to read all-resources in tenancy
  10. Click Create.

Reference: Common Policies

Gather Required Information

Prepare the information you need to authenticate your Terraform scripts and copy them into your notepad.

  1. Collect the following credential information from the Oracle Cloud Infrastructure Console.
    • Tenancy OCID: <tenancy-ocid>
      • From your user avatar, go to Tenancy:<your-tenancy> and copy OCID.
    • User OCID: <user-ocid>
      • From your user avatar, go to User Settings and copy OCID.
    • Fingerprint: <fingerprint>
      • From your user avatar, go to User Settings and click API Keys.
      • Copy the fingerprint associated with the RSA public key you made in section 2. The format is: xx:xx:xx...xx.
    • Region: <region-identifier>
  2. Collect the following information from your environment.
    • Private Key Path: <rsa-private-key-path>
      • Path to the RSA private key you made in the Create RSA Keys section. Example: $HOME/.oci/<your-rsa-key-name>.pem.

2. Create Scripts

Create three scripts: one for authentication, one to fetch data from your account, and one to print outputs.

Add API Key-Based Authentication

First, set up a directory for your Terraform scripts. Then add a provider script so your Oracle Cloud Infrastructure account can authenticate the scripts running from this directory.
  1. In your $HOME directory, create a directory called tf-provider and change to that directory.
    mkdir tf-provider
    cd tf-provider
  2. Create a file called provider.tf.
  3. Add the following code to provider.tf:
    • Replace the fields with brackets, with the information you gathered in the Gather Required Information section.
    • Add quotations around string values.
    provider "oci" {
      tenancy_ocid = "<tenancy-ocid>"
      user_ocid = "<user-ocid>" 
      private_key_path = "<rsa-private-key-path>"
      fingerprint = "<fingerprint>"
      region = "<region-identifier>"
    }
  4. Save the provider.tf file.
Explanation

Go to Oracle Cloud Infrastructure Provider.

Go to Authentication and then API Key based authentication section of the page.

Use the following variables:

  • tenancy_ocid
  • user_ocid
  • private_key_path
  • fingerprint
  • region
Add a Data Source

In this section, you fetch a list of the availability domains in your tenancy.

By fetching data, you confirm that your OCI account authenticates your provider.tf script and you get information from your account.

  1. In the tf-provider directory, create a file called availability-domains.tf.
  2. Add the following code to availability-domains.tf.
    • Replace the field with brackets, with the information you gathered in the Gather Required Information section.
    # Source from https://registry.terraform.io/providers/hashicorp/oci/latest/docs/data-sources/identity_availability_domains
    
    # <tenancy-ocid> is the compartment OCID for the root compartment.
    # Use <tenancy-ocid> for the compartment OCID.
    
    data "oci_identity_availability_domains" "ads" {
      compartment_id = "<tenancy-ocid>"
    }
    Note

    The data source gets a list of availability domains in your entire tenancy. The tenancy OCID is the compartment OCID for the root compartment. Providing a specific "<compartment-ocid>" or your "<tenancy-ocid>" outputs the same list.
    Note

    Ensure provider.tf and availability-domains.tf are in the same directory. Terraform processes all the files in a directory in the correct order, based on their relationship. For a modular approach and future reuse, separate the provider and your other scripts.
Explanation

In Terraform, to fetch data, you use a data source. Fetching data from a data source is similar to the GET method in REST APIs.

  • Go to Oracle Cloud Infrastructure Provider.
  • In the left navigation Filter, enter availability domains.
  • Under Identity, go to Data Sources and click oci_identity_availability_domains.
  • Find the Resource Type from the title of the page:
    • Type: oci_identity_availability_domains
  • In the Argument Reference section, find all arguments (inputs) labeled as (Required)
    • compartment_id
  • Construct a data source block:
    • Declare a data source with the keyword: data.
    • Add a label for data source type: "oci_identity_availability_domains"
    • Add a label for a local name (your choice):
      • The label can contain letters, digits, underscores (_), and hyphens (-). The first character must not be a digit.
      • Example: "ads"
    • Inside the code block, provide values for all required arguments.
      • Example: compartment_id = "<some-compartment-ocid>"
    • For optional arguments, provide values to narrow down the fetch results. Only some data sources have optional arguments.
Add Outputs

The data source oci_identity_availability_domains, fetches a list of availability domains. In this section, you declare an output block to print the fetched information.

  1. In the tf-provider directory, create a file called outputs.tf.
  2. Add the following code to outputs.tf.
    # Output the "list" of all availability domains.
    output "all-availability-domains-in-your-tenancy" {
      value = data.oci_identity_availability_domains.ads.availability_domains
    }
  3. Save the outputs.tf file.
    Note

    Ensure outputs.tf, provider.tf, and availability-domains.tf are in the same directory.
Explanation

  • On the Data Source: oci_identity_availability_domains page, go to Attribute Reference.
    Note

    Attributes are the outputs you can return for the oci_identity_availability_domains data source.
  • Find the attributes:
    • Attribute: availability_domains:
      • The list of availability domains
      • If you output availability_domains, you get three attributes for each availability domain in the list:
        • compartment_id
        • id
        • name
  • Construct a data source output block:
    • Declare an output block with the keyword: output
    • Add a label to be printed with the output results:
      • The label can contain letters, digits, underscores (_), and hyphens (-). The first character must not be a digit.
      • Example: "all-availability-domains-in-your-tenancy"
    • Inside the code block, enter a value for the data source output with the expression:
      • value = data.<type>.<local-name-for-data-source>.<attribute>
      • Example: value = data.oci_identity_availability_domains.ads.availability_domains

3. Run Scripts

Run your Terraform scripts. After your account authenticates the scripts, Terraform fetches your tenancy's availability domains.

Initialize

  1. Initialize a working directory in the tf-provider directory.
    terraform init

    Example output:

    Initializing the backend...
    
    Initializing provider plugins...
    - Finding latest version of hashicorp/oci...
    - Installing hashicorp/oci v3.96.0...
    - Installed hashicorp/oci v3.96.0 (signed by HashiCorp)
    
    The following providers do not have any version constraints in configuration,
    so the latest version was installed.
    ...
    * hashicorp/oci: version = "~> 3.96.0"
    
    Terraform has been successfully initialized!
  2. Check the contents of the tf-provider directory.
    ls -a

    You now have a folder called .terraform that includes the plugins for the oci provider.

    Note

    Troubleshooting:
    • After running terraform init
    • error message: Failed to query available provider packages:
      • If you are on a VPN, check your proxy settings.
Plan

  1. Create an execution plan to check whether the changes shown in the execution plan match your expectations, without changing the real resources.
    terraform plan
  2. Confirm that you have Plan: 0 to add, 0 to change, 0 to destroy.

    Example output:

    An execution plan has been generated and is shown below.
    Resource actions are indicated with the following symbols:
    
    Terraform will perform the following actions:
    
    Plan: 0 to add, 0 to change, 0 to destroy.
    Note

    You are fetching data, so the plan shows that you are not adding, changing, or destroying any resources.
Apply

  1. Run your Terraform scripts and get your outputs:
    terraform apply
  2. When prompted for confirmation, enter yes, for your resource to be created.

    After you run the apply command, the output is displayed in the terminal.

    Example output:
    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
    
    Outputs:
    
    all-availability-domains-in-your-tenancy = [
      {
        "compartment_id" = "ocid1.compartment.xxx"
        "id" = "ocid1.availabilitydomain.xxx"
        "name" = "QnsC:US-ASHBURN-AD-1"
      },
      {
        "compartment_id" = "ocid1.compartment.xxx"
        "id" = "ocid1.availabilitydomain.xxx"
        "name" = "QnsC:US-ASHBURN-AD-2"
      },
      {
        "compartment_id" = "ocid1.compartment.xxx"
        "id" = "ocid1.availabilitydomain.xxx"
        "name" = "QnsC:US-ASHBURN-AD-3"
      },
    ]

Congratulations! Your Oracle Cloud Infrastructure account can now authenticate your Oracle Cloud Infrastructure Terraform provider scripts.

References:

Troubleshooting

  • 401 errors - (Service error:NotAuthenticated):
    • You have an incorrect value for one of the following:
      • tenancy OCID
      • user OCID
      • fingerprint
      • RSA private key (the path or the key)
  • no such host:
    • You have an incorrect value for the following:
      • region identifier