Note:
- This tutorial requires access to Oracle Cloud. To sign up for a free account, see Oracle Cloud Free Tier.
- It uses example values for Oracle Cloud Infrastructure credentials, tenancy, and compartments. When completing your lab, substitute these values with ones specific to your cloud environment.
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:
- Configure an Oracle Linux 7 instance to run Terraform and communicate over the Oracle Cloud Infrastructure API
- Organize your Terraform files to take advantage of working in different environments
- Collect required configuration data such as OCID values
- Create a cloud-init user data configuration script
- Create, then destroy the instance using Terraform
What you Need
-
An Oracle Linux 7 instance, with Terraform packages, and Oracle Cloud Infrastructure CLI installed.
-
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
.
-
Make a directory named
~/tfLab
for this exercise, and change to make that the working directory.mkdir ~/tfLab cd ~/tfLab
-
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 theecho
command, then review with thecat
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.
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.
-
Find the user OCID by clicking on the Oracle Cloud Infrastructure console profile icon, then clicking the user name to display user details.
From the user details page, click the Copy link next to the OCID value, which shows only the trailing few characters.
-
Use the
echo
command to append the OCID value to the assignment. Use thecat
command to review it.echo "ocid1.user.oc1..[your user OCID]" >> tfVars.sh cat tfVars.sh
-
Empty the display with the
clear
command. -
Get the tenancy OCID by clicking on the console profile icon, then clicking the tenancy name to display tenancy details.
-
From the tenancy details page, click the Copy link next to the OCID value, which shows only the trailing few characters.
-
Input the tenancy OCID variable assignment with the
echo
command and include the tenancy OCID value. Use thecat
command to review.echo "export TF_VAR_tenancy_ocid=ocid1.tenancy.oci1..[your tenancy ocid]" >> tfVars.sh cat tfVars.sh
-
Paste the value into the
tfVars.sh
file as the assigned value for the variableTF_VAR_tenancy_ocid
. -
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.
- Run the
oci setup config
command.oci setup config
-
The prompt asks for a location for the
config
file. The default location ishome/opc/.oci/config
. Press enter to accept the value. -
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 thetfVars.sh
file, and paste it into the prompt. Press Enter if necessary. -
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 thetfVars.sh
file, and paste it into the prompt. Press Enter if necessary. -
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. -
The prompt asks you to generate a new API signing key pair. Respond with
Y
, and press Enter. -
The prompt asks you to enter a directory for the key pair. Accept the default location
/home/opc/.oci
by pressing Enter. -
The prompt asks you to enter a key name. Accept the default key name token
oci_api_key
by pressing Enter. -
The prompt asks for a key passphrase. For this exercise, press Enter, which means there is no passphrase used.
-
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
-
From the terminal screen displaying the
oci setup config
output, select and copy the region value. In the terminal screen displaying the filetfVars.sh
enter the environment variable definition for the region.echo "export TF_VAR_region=us-ashburn-1" >> tfVars.sh
-
From the terminal screen displaying the
oci setup config
output, select and copy the fingerprint value. In the terminal screen displaying the filetfVars.sh
enter the environment variable definition for the fingerprint.echo "export TF_VAR_fingerprint=[your fingerprint]" >> tfVars.sh
-
From the terminal screen displaying the
oci setup config
output, select and copy the key file value. In the terminal screen displaying the filetfVars.sh
enter the environment variable definition for the key file. Then display the file with thecat
command.echo "export TF_VAR_api_private_key=/home/opc/.oci/oci_api_key.pem" >> tfVars.sh cat tfVars.sh
-
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.
-
Click Add API Key.
-
Select the Paste Public Key option.
-
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
-
Select and copy the content of the public key from the terminal display and return to Add API Key input and paste the value.
-
Click Add.
-
Examine the Configuration File Preview. It should reflect the same values that are in the
~/.oci/config
file.Click Close.
-
Review the API Key entry on the user details page.
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.
-
Reach the compartment OCID by navigating through the console main menu to the Identity option, then click Compartments.
-
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.
-
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
-
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.
-
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
-
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.
-
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
-
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.
-
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
-
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.
-
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
-
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
-
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
-
Create three environment variables for instance, host, and VNIC names. Press enter, if necessary to invoke the
vnic_name
environment variable. Display thetfVars.sh
file with thecat
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
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.
-
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
-
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 addsHTTPS
andHTTP
services to the instance firewall and enables and starts theocid.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
-
Show the
user-data
variable. Then, clear the screen.cat tfVars.tf clear
-
Create the main Terraform code file named
main.tf
. This code includes the Terraformprovider
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
-
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
-
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 theuser_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
-
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
-
The
source_details
identify the image to be used for the instance and the type of source, which isimage
. The closing brace for theoci_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
- Display
main.tf
. Use thef
andb
keys to scroll the display.less main.tf
-
List the files in the
~/tfLab
directory. The shell script permissions must be set so that it can be invoked with thesource
command. Change permissions on thetfVars.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
-
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
Run Terraform
This step shows you how to run Terraform commands to create the instance.
-
In the terminal, check the Terraform version, then clear the screen.
terraform --version clear
-
Initialize Terraform on the instance. After reviewing the output, clear the screen.
terraform init clear
-
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
-
Use the
apply
command to execute the plan and create the instance. When prompted to perform the actions, respond withyes
. After a short time, the process finishes. Clear the screen.terraform apply yes clear
-
Display the contents of the directory. Explore the
terraform.tfstate
file with theless
command, then useq
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
Examine the Instance
-
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. -
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
-
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 thehttps
andhttp
services are supported. Then clear the screen.sudo firewall-cmd --info-zone=public clear
-
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
-
Exit the session.
exit
Destroy the Instance
In this step, you destroy the instance with Terraform.
Note: Destroying the instance in your tenancy is optional.
-
Use the
destroy
command to terminate the instance. Enteryes
when prompted.terraform destroy yes
-
The instance has been destroyed.
-
Check the Oracle Cloud Infrastructure console to verify the instance has been terminated.
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.
Introduction to Terraform with Oracle Linux
F40571-03
March 2021
Copyright © 2021, Oracle and/or its affiliates.
This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.
If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, then the following notice is applicable:
U.S. GOVERNMENT END USERS: Oracle programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, delivered to U.S. Government end users are "commercial computer software" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of the programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, shall be subject to license terms and license restrictions applicable to the programs. No other rights are granted to the U.S. Government.
This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group.
This software or hardware and documentation may provide access to or information about content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services unless otherwise set forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services, except as set forth in an applicable agreement between you and Oracle.