Note:

Introduction to Terraform with Oracle Linux

Introduction

This lab exercise introduces you to Terraform in Oracle Cloud Infrastructure, and shows you how to do a simple deployment of an Oracle Linux instance. By following instructions, copying commands and code you can work through this simple exercise as an introduction to Terraform in Oracle Cloud Infrastructure.

Objectives

In this tutorial, you will:

What you Need

  1. An Oracle Linux 7 instance, with Terraform packages, and Oracle Cloud Infrastructure CLI installed.

  2. Access to an Oracle Cloud Infrastructure compartment with permissions to create instances and access to an Oracle Cloud Infrastructure virtual cloud network (VCN).

Create the Terraform Variable Shell Script

This exercise requires you to collect and decide several values for Terraform to create the Oracle Linux instance. This exercise uses a Terraform variable shell script to set these values for processing. This approach allows you to re-use the Terraform code independently of the environment in which it runs. This approach also simplifies the process of organizing the code because you can paste necessary values right into the shell script as you collect them.

Note: Environment variables that have names starting with the token TF_VAR_ are interpreted for use by Terraform. The Terraform variable name is appended to the token TF_VAR_. For example the environment variable TF_VAR_user_ocid associates the value of that environment variable to the Terraform variable user_ocid.

  1. Make a directory named ~/tfLab for this exercise, and change to make that the working directory.

    mkdir ~/tfLab
    cd ~/tfLab
    
  2. In this and following steps throughout the exercise, environment variables are added to a file named tfVars.sh using the echo command. Keep this terminal clear for this purpose.

    Start the first value in the script file by inserting a portion of the environment variable assignment for user_ocid. Input the user OCID variable assignment with the echo command, then review with the cat command.

    echo -n "export TF_VAR_user_ocid=" >> tfVars.sh
    cat tfVars.sh
    

    Note: Use the -n option to prevent the echo command from writing a newline character. The following insertion will append directly to the assignment that was previously provided. Press enter to present a clean prompt.

    first tf var

Collect User and Tenancy OCID Values

To complete the CLI configuration, you will gather user and tenancy OCID values. These values are two of five configuration settings you make that allow the Oracle Cloud Infrastructure to authenticate calls to the API through Terraform, which runs on the instance. These values are also used within the Terraform code for the Oracle Cloud Infrastructure provider.

Note: You are given environment variable assignments to copy at the end of this step. If you use them, replace the OCID value placeholders with your OCID values.

  1. Find the user OCID by clicking on the Oracle Cloud Infrastructure console profile icon, then clicking the user name to display user details.

    get user profile

    From the user details page, click the Copy link next to the OCID value, which shows only the trailing few characters.

  2. Use the echo command to append the OCID value to the assignment. Use the cat command to review it.

    echo "ocid1.user.oc1..[your user OCID]" >> tfVars.sh
    cat tfVars.sh
    

    user env var

  3. Empty the display with the clear command.

  4. Get the tenancy OCID by clicking on the console profile icon, then clicking the tenancy name to display tenancy details.

    get tenancy profile

  5. From the tenancy details page, click the Copy link next to the OCID value, which shows only the trailing few characters.

  6. Input the tenancy OCID variable assignment with the echo command and include the tenancy OCID value. Use the cat command to review.

    echo "export TF_VAR_tenancy_ocid=ocid1.tenancy.oci1..[your tenancy ocid]" >> tfVars.sh
    cat tfVars.sh
    
  7. Paste the value into the tfVars.sh file as the assigned value for the variable TF_VAR_tenancy_ocid.

    user env var

  8. Leave this terminal display open and available so you can copy the user and tenancy OCID values for the next step in which configure the CLI.

Set Up the Oracle Cloud Infrastructure CLI Configuration

In this step, open a second ssh session on another terminal and keep the other session active, with the vi editor open. Run the oci setup config command in the new terminal to create the config file on your instance. During this process API keys are created for you. After the command completes you will copy essential values from the oci setup config screen output, and paste them into the tfVars.sh file. You will also upload the public key for the API to your Oracle Cloud Infrastructure user profile.

  1. Run the oci setup config command.
    oci setup config
    

    oci setup config

  2. The prompt asks for a location for the config file. The default location is home/opc/.oci/config. Press enter to accept the value.

    oci setup user ocid

  3. The prompt asks for the user OCID. Copy the value from the TF_VAR_user_ocid environment variable in the other terminal, which is displaying the tfVars.sh file, and paste it into the prompt. Press Enter if necessary.

    oci setup tenancy ocid

  4. The prompt asks for the tenancy OCID. Copy the value from the TF_VAR_tenancy_ocid environment variable in the other terminal, which is displaying the tfVars.sh file, and paste it into the prompt. Press Enter if necessary.

    oci setup region

  5. The prompt asks for the region, by index or name. Select your region from the list. The region where this exercise was developed is us-ashburn-1. Enter the region value or index, and press Enter.

    oci setup key

  6. The prompt asks you to generate a new API signing key pair. Respond with Y, and press Enter.

    oci setup key path

  7. The prompt asks you to enter a directory for the key pair. Accept the default location /home/opc/.oci by pressing Enter.

    oci setup key name

  8. The prompt asks you to enter a key name. Accept the default key name token oci_api_key by pressing Enter.

    oci setup key passphrase

  9. The prompt asks for a key passphrase. For this exercise, press Enter, which means there is no passphrase used.

    oci setup config done

  10. The oci setup config command has completed and has produced the API authentication key pair and also includes the region in which you are working. There are three more environment variables to assign with the results displayed in the terminal.

    Clear the screen in the terminal where you will set these environment variables with values copied from the completed oci setup config command output display.

    clear
    
  11. From the terminal screen displaying the oci setup config output, select and copy the region value. In the terminal screen displaying the file tfVars.sh enter the environment variable definition for the region.

    echo "export TF_VAR_region=us-ashburn-1" >> tfVars.sh
    
  12. From the terminal screen displaying the oci setup config output, select and copy the fingerprint value. In the terminal screen displaying the file tfVars.sh enter the environment variable definition for the fingerprint.

    echo "export TF_VAR_fingerprint=[your fingerprint]" >> tfVars.sh
    
  13. From the terminal screen displaying the oci setup config output, select and copy the key file value. In the terminal screen displaying the file tfVars.sh enter the environment variable definition for the key file. Then display the file with the cat command.

    echo "export TF_VAR_api_private_key=/home/opc/.oci/oci_api_key.pem" >> tfVars.sh
    cat tfVars.sh
    

    oci provider values

  14. Open the Oracle Cloud Infrastructure console and navigate to your user profile by clicking on the profile icon, then your user name scroll down and select the API Keys option under the Resources menu.

    add api key

  15. Click Add API Key.

  16. Select the Paste Public Key option.

    paste api key

  17. Return to the terminal where oci setup config was run, clear the screen and display the contents of the public key file in the .oci directory.

    clear
    cat .oci/oci_api_key_public.pem
    

    cat public key

  18. Select and copy the content of the public key from the terminal display and return to Add API Key input and paste the value.

    paste api key value

  19. Click Add.

  20. Examine the Configuration File Preview. It should reflect the same values that are in the ~/.oci/config file.

    config file preview

    Click Close.

  21. Review the API Key entry on the user details page.

    api key review

Gather and Organize Values in the Shell Script

In this step, you will collect the OCID and other Oracle Cloud Infrastructure values that are necessary to create and host an Oracle Linux server.

  1. Reach the compartment OCID by navigating through the console main menu to the Identity option, then click Compartments.

    identity compartments

  2. On the compartment list display that appears, bring up the record for your compartment. Hover the mouse over the OCID value and click the Copy link. The link changes to Copied when the value is ready.

    copy copmartment ocid

  3. Return to the terminal session in which you are building the environment variable shell file. Clear the screen if necessary. Create an environment variable assignment for the compartment_ocid value, and paste the OCID value from the console.

    echo "export TF_VAR_compartment_ocid=ocid1.compartment.oci1..[your compartment ocid]" >> tfVars.sh
    

    compartment ocid env var

  4. At the console, navigate through the console menu to the Instances list. On the Instances list, find the Availability domains displayed on the screen. Copy the name of the availability domain in which you want Terraform to create the instance.

    availability domain list

  5. Return to the terminal session. Create an environment variable assignment for the selected_AD value, and paste the name from the console.

    echo "export TF_VAR_selected_AD=DSdu:US-ASHBURN-AD-3" >> tfVars.sh
    

    selected AD env var

  6. The instance will require a subnet, so navigate to the subnet on which you want the new server’s primary VNIC to be connected. Copy the subnet OCID value by clicking the Copy link. The link changes to Copied when ready.

    subnet ocid

  7. Return to the terminal session. Create an environment variable assignment for the subnet_ocid value, and paste the OCID value from the console.

    echo "export TF_VAR_subnet_ocid=ocid1.subnet.oc1.[your subnet ocid]" >> tfVars.sh
    

    subnet ocid env var

  8. Oracle Cloud Infrastructure provides current and legacy versions of many different operating system images. Navigate to the page for All Oracle Linux 8.x Images. Click the name of the most recent Oracle Linux 8 image to display the list of OCID values for the image in each region. Select and copy the image OCID for the region in which the instance will be created.

    image ocid

  9. Return to the terminal session. Create an environment variable assignment for the iamge_ocid value, and paste the OCID value from the Image OCIDs list.

    echo "export TF_VAR_image_ocid=ocid1.image.[your image OCID]" >> tfVars.sh
    

    image ocid env var

  10. Select a compute shape name from the Oracle Cloud Infrastructure documentation page describing Compute Shapes. Click the Standard Shapes link on the page, then select and copy the name VM.Standard2.1.

    stardard shapes

  11. Return to the terminal session. Create an environment variable assignment for the instance_shape value, and paste the name from the Standard Shapes list.

    echo "export TF_VAR_instance_shape=VM.Standard2.1" >> tfVars.sh
    cat tfVars.sh
    clear
    

    instance shape env var

  12. You will need a public key to access the instance you create with Terraform from this instance where the Terraform code is hosted. Create a key pair in the instance .ssh directory. Use the ssh-keygen command, and press enter twice to leave the passphrase empty.

    ssh-keygen -f ~/.ssh/id_rsa
    

    ssh-keygen

  13. Select and copy the location of the public key. Create an environment variable assignment for the ssh_public_key value, and paste the public key location. Then clear the screen.

    echo "export TF_VAR_ssh_public_key=/home/opc/.ssh/id_rsa.pub" >> tfVars.sh
    clear
    

    ssh-keygen_env_var

  14. Create three environment variables for instance, host, and VNIC names. Press enter, if necessary to invoke the vnic_name environment variable. Display the tfVars.sh file with the cat command to review. Then, clear the screen.

    echo "export TF_VAR_instance_name=tfInstance" >> tfVars.sh
    echo "export TF_VAR_hostname_label=tfHostname" >> tfVars.sh
    echo "export TF_VAR_vnic_name=tfVNIC" >> tfVars.sh
    clear
    

    name env vars

Create and Review Terraform Code

This step shows you how to organize the Terraform code in files that will allow you to easily deploy an instance from different environments. The first file contains Terraform variable declarations, the next file contains the Terraform code that describes the provider and the instance resource that will be created.

  1. Create the Terraform variable declarations file named tfVars.tf. Then, clear the screen.

    echo "// Copyright (c) 2021 Oracle and/or its affiliates. All rights reserved.
    // Licensed under the Mozilla Public License v2.0
    variable \"user_ocid\" {}
    variable \"tenancy_ocid\" {}
    variable \"region\" {}
    variable \"fingerprint\" {}
    variable \"api_private_key\"{}
    variable \"selected_AD\" {}
    variable \"compartment_ocid\" {}
    variable \"instance_shape\" {}
    variable \"image_ocid\" {}
    variable \"ssh_public_key\" {}
    variable \"subnet_ocid\" {}
    variable \"instance_name\" {}
    variable \"hostname_label\" {}
    variable \"vnic_name\" {}" >> tfVars.tf
    clear
    
  2. Provide a short bash script in the user_data variable value, that will be used as cloud-init user data. This script shows that you can configure various features in the instance before you access it. This script adds HTTPS and HTTP services to the instance firewall and enables and starts the ocid.service. Then, clear the screen.

    echo "variable \"user_data\" {" >> tfVars.tf
    echo "  default = <<EOF" >> tfVars.tf
    echo '#!'"/bin/bash" >> tfVars.tf
    echo "sudo systemctl stop firewalld" >> tfVars.tf
    echo "sudo firewall-offline-cmd --add-service=https" >> tfVars.tf
    echo "sudo firewall-offline-cmd --add-service=http" >> tfVars.tf
    echo "sudo systemctl start firewalld" >> tfVars.tf
    echo "sudo systemctl enable ocid.service" >> tfVars.tf
    echo "sudo systemctl start ocid.service" >> tfVars.tf
    echo "EOF" >> tfVars.tf
    echo "}" >> tfVars.tf
    clear
    
  3. Show the user-data variable. Then, clear the screen.

    cat tfVars.tf
    clear
    

    cat user data var

  4. Create the main Terraform code file named main.tf. This code includes the Terraform provider block which is applicable only to Oracle Cloud Infrastructure. Values in the provider block are the same as those in the ~/.oci/config file.

    After invoking the echo commands, clear the screen.

    echo "// Copyright (c) 2021 Oracle and/or its affiliates. All rights reserved." >> main.tf
    echo "// Licensed under the Mozilla Public License v2.0" >> main.tf
    echo "" >> main.tf
    echo "provider \"oci\" {" >> main.tf
    echo "  user_ocid    = var.user_ocid" >> main.tf
    echo "  tenancy_ocid = var.tenancy_ocid" >> main.tf
    echo "  region       = var.region" >> main.tf
    echo "  fingerprint  = var.fingerprint" >> main.tf
    echo "  private_key  = var.api_private_key" >> main.tf
    echo "}" >> main.tf
    echo "" >> main.tf
    clear
    
  5. Start the Terraform oci_core_instance code block, and include the instance availability domain, compartment OCID, display name and shape. Press the enter key, if necessary to invoke the last command, then clear the screen.

    echo "resource \"oci_core_instance\" \"test_instance\" {" >> main.tf
    echo "  availability_domain = var.selected_AD" >> main.tf
    echo "  compartment_id      = var.compartment_ocid" >> main.tf
    echo "  display_name        = var.instance_name" >> main.tf
    echo "  shape               = var.instance_shape" >> main.tf
    echo "" >> main.tf
    clear
    
  6. The metadata code snippet includes the variable for the public key to be installed in the ~/.ssh/authorized_keys file of the new instance, and the invocation of the user_data variable. Clear the screen.

    echo "  metadata = {" >> main.tf
    echo "    ssh_authorized_keys = file (var.ssh_public_key)" >> main.tf
    echo "    user_data = base64encode(var.user_data)" >> main.tf
    echo "  }" >> main.tf
    echo "" >> main.tf
    clear
    
  7. The network configuration is defined in the create_vnic_details block. The variables define the subnet for the instance primary VNIC, the display (for example, for the console) name, host name and public IP assignment. Clear the screen.

    echo "  create_vnic_details {" >> main.tf
    echo "    subnet_id = var.subnet_ocid" >> main.tf
    echo "    display_name = var.vnic_name" >> main.tf
    echo "    hostname_label = var.hostname_label" >> main.tf
    echo "    assign_public_ip = false" >> main.tf
    echo "  }" >> main.tf
    echo "" >> main.tf
    clear
    
  8. The source_details identify the image to be used for the instance and the type of source, which is image. The closing brace for the oci_core_instance is also contained in this snippet. Clear the screen after invoking the commands.

    echo "  source_details {" >> main.tf
    echo "    source_id = var.image_ocid" >> main.tf
    echo "    source_type = \"image\"" >> main.tf
    echo "  }" >> main.tf
    echo "}" >> main.tf
    
  9. Display main.tf. Use the f and b keys to scroll the display.
    less main.tf
    

    main.tf

  10. List the files in the ~/tfLab directory. The shell script permissions must be set so that it can be invoked with the source command. Change permissions on the tfVars.sh file so that it can be invoked. List the files again.

    After confirming the correct permissions for tfVars.sh, clear the screen.

    ls -al
    chmod 764 tfVars.sh
    ls -al
    clear
    

    shell permissions

  11. Invoke the tfVars.sh shell script and display the Terraform environment variables that were set. Clear the screen after reviewing the variables.

    source tfVars.sh
    env | grep TF_VAR
    clear
    

    env vars

Run Terraform

This step shows you how to run Terraform commands to create the instance.

  1. In the terminal, check the Terraform version, then clear the screen.

    terraform --version
    clear
    

    terraform version

  2. Initialize Terraform on the instance. After reviewing the output, clear the screen.

    terraform init
    clear
    

    terraform version

  3. Use the plan command to produce the deployment plan that will be used by the Oracle Cloud Infrastructure Terraform provider. Scroll the terminal screen to see the plan to deploy the instance. Clear the screen when ready to continue.

    terraform plan
    clear
    

    terraform plan

  4. Use the apply command to execute the plan and create the instance. When prompted to perform the actions, respond with yes. After a short time, the process finishes. Clear the screen.

    terraform apply
    yes
    clear
    

    terraform apply

  5. Display the contents of the directory. Explore the terraform.tfstate file with the less command, then use q to exit. This file will be used by terraform to destroy the instance at the end of this lab. Clear the screen when you are satisfied with your review.

    ls -alt
    less terraform.tfstate
    q
    clear
    

    review tfstate

Examine the Instance

  1. Login to the Oracle Cloud Infrastructure console, and find the instance named tfInstance on the list for your compartment. Click the name to display the instance details page. Select and copy the IP address.

    copy ip address

  2. Return to the terminal, change directory to /home/opc, clear the screen, then use the ip address from the console to connect to the Oracle Linux 8 instance that was just created.

    cd /home/opc
    clear
    ssh -i ./.ssh/id_rsa 198.51.100.7
    clear
    

    ssh to ip

  3. The small cloud-init script that was provided as user_data was run after the instance was created. Check the status of the firewall settings to see that the https and http services are supported. Then clear the screen.

    sudo firewall-cmd --info-zone=public
    clear
    

    firewall-cmd

  4. Check the status of the ocid.service, which is disabled by default on a new instance. The script enabled and started this service. Clear the screen.

    sudo systemctl status ocid.service
    clear
    

    status ocid service

  5. Exit the session.

    exit
    

    exit

Destroy the Instance

In this step, you destroy the instance with Terraform.

Note: Destroying the instance in your tenancy is optional.

  1. Use the destroy command to terminate the instance. Enter yes when prompted.

    terraform destroy
    yes
    

    terraform destroy

  2. The instance has been destroyed.

    instance destroyed

  3. Check the Oracle Cloud Infrastructure console to verify the instance has been terminated.

    instance gone

In this exercise, you gathered essential information that enabled you to create an Oracle Linux 8 instance in Oracle Cloud Infrastructure using Terraform. The Terraform code is generic to Oracle Cloud Infrastructure, and your inputs were provided from your environment.

More Learning Resources

Explore other labs on docs.oracle.com/learn or access more free learning content on the Oracle Learning YouTube channel. Additionally, visit education.oracle.com/learning-explorer to become an Oracle Learning Explorer.

For product documentation, visit Oracle Help Center.