Skip links

Setting up OCI Terraform Provider

Over the last few months, I’ve been working to convert my skills from a core DBA/Replication specialist into a from dynamic DevOps persona.  Part of this is looking at all of the cloud providers out there and getting an understanding of what is going on and how to maximize interaction with each of these platforms.  I’ve taken at look at AWS, Azure, and Oracle Cloud Infrastructure (OCI).  Yes, I know GCP is out there as well, but I was just getting out of my comfort zone a bit, yet staying close to home with OCI.

Prior to leaving Oracle, I wrote a blog post on how to install HashiCorp Terraform on the MacOS (here).  This was the start of me using Terraform with OCI.  At the time, I was mostly using Terraform to work with OCI Marketplace implementation of of Oracle GoldenGate.  Yes, everything that is done with OCI Marketplace images are done with Terraform.  So it was a great introduction to Terraform.  

In this post, I want to tackle how to configure the OCI Provider for Terraform.  The first thing you have to understand is that “providers” are responsible for understanding API interactions and exposing the resources required.  These “providers” generally provide access to the IaaS (AWS, Azure, OCI, GCP), PaaS, or Sass services.

OCI Provider

For Terraform to work, it has to know what “provider” is going to be used.  This basically says what IaaS platform is going to be used, what APIs are exposed, and how to interact with the framework.  This is typically done in what is called a “provider block”.  In doing research, I’ve seen a few people put this code in a “provider.tf” file, but my preference it to put this “provider block” at the top of my main.tf file.  This provides a sense of quick access for knowing what provider is being used for the set of files being used.  There are reasons to use “provider.tf”, but for my purposes with OCI, I didn’t find it needed.

A provider block for OCI looks similar to this:

provider “oci” {
    tenancy_ocid = var.tenancy_ocid
    user_ocid = var.user_ocid
    fingerprint = var.fingerprint
    private_key_path = var.private_key_path
    regions = var.region
}

Now the above “provider block” is not formatted in proper HCL language, but it does work and shows what information is needed to make the OCI provider work.  Also notice that there are a lot of variables that are being used (var.*).  These variables need to be defined in a variables file that will be referenced within the same directory. If we were to replace these variables with actual values, the provider block would look something like this:

provider “oci” {
    tenancy_ocid = "ocid1.tenancy.oc1..aaaaaaaaojorxd……..lweivou6xeomto4gvjxuuyraxc……….”
    user_ocid = "ocid1.user.oc1..aaaaaaaavwqmadvq……..xlcszpsh4b54wsc7c23ciktpk……….”
    fingerprint = “..:16:cd:13:46:98:15:cb:18:cc:e8:44:52:cd:e8:..”
    private_key_path = "/Users/bocurtis/.ssh/<key_file>.pem”
    regions = "us-ashburn-1"
}

That is a bit messy!  Using variables are to the advantage when setting up a provider or anything within the Terraform structure.  I’ll write another post at a later date covering variables, but know that variables are easier and the preferred way of doing things with Terraform.

Gather the required info

Now that we understand what is needed to establish an OCI connection using the Terraform provider for OCI, where does all this information come from?  The obvious answer is from OCI, but where in OCI?  The easiest way to find this information is to use the OCI command line tool, but this has to be configured with the same information as the Terraform provider.  Not going to discuss how to install the OCI command line, but that can be found here.  Although the easiest way is from the command line,  to use either or all the information has to be gathered manually using the web UI.  Once this information pulled together than you can access OCI using the command line tool or by code using Terraform.

Tenancy Info

To find the tenancy information, login to your OCI cloud account and select the tenancy from under your profile. Once on the tenancy details page, there is a tab called “Tenancy Information”.  On this tab, copy the OCID.  This OCID needs to be placed in the Terraform variables file.

Oci tenancy info
Additional Details

Tenancy OCID from OCI Console:

1. Open the navigation menu, under Governance and Administration, go to Administration and click Tenancy Details.
2. The tenancy OCID is shown under Tenancy Information.  Click Copy

User Info

To ensure user access, grap the OCID for your user.  This is often found by accessing the Profile section and then clicking User Settings.  This OCID will need to be added to the Terraform variables files as well.

oci_user_details.png
Additional Details

These same details can be accessed in the following way:

1. Under Governance and Administration, go to Identity and click Users
2. The user OCID is shown under User Information

Finger Print Info

The fingerprint info that is needed can be found on the User details page as well.  It is generated after you have uploaded a public key to OCI.  This fingerprint is used for you to validate login while using and accessing APIs.  After uploading a public_key, the fingerprint is provided.  This string of characters and numbers need to be copied to the Terraform variables file.

oci_user_details_fp.png

Private Key Info

After gathering up the information that I just pointed out, the next item that has to be added to the Terraform variables file is the location of the private key.  This location is typically located somewhere on your local hard drive, especially if you are using Terraform OSS to build out the infrastructure.  In my case this location is ~/.ssh/<private_key>.pem.

Region Info

The last piece of information needed is the region which to build workloads in.  In most cases this is your default region; however, you can subscribe to other regions and build workloads in those as well.  For the purpose of demoing and testing, I keep all of my items in the Ashburn data centers (us-ashburn-1).

Working

With all the required information gathered and the OCI provider built inside of a main.tf, additional code has to be written to confirm that the connection is successful.  In order to do this, I wrote a main.tf file that looks similar to the below structure.  Now I’m using a “module” concept here, but that is only to  break up my code and that can be discussed later.

Code (main.tf)

provider "oci" {
version = ">= 3.76.0"
region = var.region
tenancy_ocid = var.tenancy_ocid
user_ocid = var.user_ocid
fingerprint = var.fingerprint
private_key_path = var.private_key_path
}

module "identity" {
source = "./modules/identity/info"
}

output "user_api_info" {
value = module.identity.user_api_info
}

With everything written, I just have to initialize the environment (terraform init), then perform a plan (terraform plan), and lastly apply (terraform apply).  If everything is sucessful, I should get output that is related to the user I’m connecting to OCI with.

Output

Bobbys-MacBook-Pro:OCI bocurtis$ terraform apply
module.identity.data.oci_identity_api_keys.test_api_keys: Refreshing state...

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

output:

user_api_info = [
{
"fingerprint" = “..:16:cd:13:46:98:15:cb:18:cc:e8:44:52:cd:..:.."
"id" = "ocid1.tenancy.oc1..aaaaaaaaojorxdfprzt2sx75lweivou6xeomto4gvjxuuyraxcdakff4dujq/ocid1.user.oc1..aaaaaaaavwqmadvq4geqqzog3xlcszpsh4b54wsc*************
"inactive_status" = ""
"key_value" = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwcXkeqP+XDlMnTWY4B3j\npgztL3Ed22zl5HomRVEmnM+ZhdStmhFj9uvZT+wU22GCJ+hfZyYCjdxGkaAgKf/R\nV1hMJ4kUx+XepTvdUx6Inu5hL5KevM7uGMFyxxgTgma4lgsYgF+*********************************************************************+UI5q6VS68HM\nioch9pNiwiC5frNkudmqpGBVOvGaCoayM8e1maivz3o4UgOYGcOwEIR14uMq/nrs\nRm1b/bbn+hRTQ1K8K5uWxiu8GV8B4IJCIf/xpLTvHiZ1ws+GITnOZBrPM8/J+ayc\nPwIDAQAB\n-----END PUBLIC KEY-----"
"state" = "ACTIVE"
"time_created" = "2020-06-07 01:14:24.08 +0000 UTC"
"user_id" = "ocid1.user.oc1..aaaaaaaavwqmadvq4geqqzog3xlcszpsh4b54wsc#######################"
},
]

Summary

In this blog post, I wanted to show how to configure the Terraform Provider for OCI.  As was discussed it really is not that hard once you know where to find the correct information needed.  Additionally, the same information is used to make the connection for the OCI command line tools as well.  Meaning that if you have the OCI command line tool already installed and configured, you have all the information you need.  

Hopefully, this post will be useful to others who are trying to interact with OCI via the Terraform Provider.

Enjoy!!

Leave a comment

  1. Good day! Do you know if they make any plugins to help with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains.
    If you know of any please share. Thanks! I saw similar
    article here: Bij nl

  2. There are a number of tradeoffs: Wet saws aren’t cheap, they are often sluggish, and you can’t put adhesive on the tile till it has dried.

  3. A motivating discussion is definitely worth comment. I believe that you need to publish more about this topic, it might not be a taboo matter but typically people don’t discuss such topics. To the next! Cheers!

  4. Pretty! This was an incredibly wonderful article. Thanks for supplying these details.

  5. Should you even so undecided: download all the earphones, person all the down to some sort of Biggest score as well as get regarding stopper these people in to a Zune following that a music player and see the one that comments easier to a person, in addition to which experts claim vent making you smirk whole lot. You’ll are familiar with explaining perfect for you.

  6. Окраска бампера транспортного средства требует тщательной подготовительной работы и правильного подбора составов. В первую очередь необходимо определить, сколько краски нужно на бампер, учитывая его габариты и качество поверхности. [url=https://emmanuelbibletraining.info/ ]Сколько надо краски на задний бампер на emmanuelbibletraining.info [/url] считается подходящим выбором для достижения отличного результата. Важно помнить, что перед применением нового покрытия следует тщательно подготовить поверхность, удалив старую краску и очистив пластик. Текстурная краска дает не только эстетичный внешний вид, но и дополнительную защиту от механических повреждений.
    Для тех, кто столкнулся с необходимостью удаления следов краски после ДТП, существуют различные способы решения проблемы. Чтобы удалить краску с бампера от другой машины, специалисты рекомендуют использовать специальные смывки для краски с пластика бампера, которые эффективно справляются с задачей без повреждения основного покрытия. При работе с черной структурной краской важно принимать во внимание время высыхания каждого слоя и следовать технологию нанесения, что позволит добиться однородного покрытия и надежного результата.

    Источник: [url=https://emmanuelbibletraining.info/ ]https://emmanuelbibletraining.info/ [/url]

    по вопросам Как убрать краску с бампера от забора – стучите в Телеграм bke08

  7. Настройка GPON-роутера — это важный процесс для абонентов, которые планируют улучшить качество интернета и надежность соединения. Главный шаг заключается в грамотной настройке роутера, чтобы гарантировать стабильную работу сети. Если вы не понимаете, как настроить GPON-роутер, вам может содействовать блог, где объясняется о всех этапах подключения и настройке GPON-терминала. Подробнее о том [url=https://netgate-kiev.blogspot.com/ ]Как подключить вай фай роутер gpon на netgate-kiev.blogspot.com [/url] можно ознакомиться на сайте по ссылке.

    Когда появляется вопрос, как настроить роутер к GPON или как интегрировать свой роутер к GPON-модему, важно рассматривать несколько моментов. Например, при эксплуатации услуг МТС для подключения GPON-роутера требуется внимательно следить за совместимостью устройств. Если вы хотите масштабировать сеть, не игнорируйте, что подключение второго роутера через GPON позволит усилить сигнал и обеспечить надежную работу интернета. Настройка таких устройств нуждается внимательности и корректного выбора параметров.

    Источник: [url=https://netgate-kiev.blogspot.com/ ]https://netgate-kiev.blogspot.com/ [/url]

    по вопросам Как подключить свой роутер к роутеру мгтс gpon – пишите в Telegram iah00

  8. You can convert 1 BABYDOGE to 1.230e-9 USD. Live BABYDOGE to USD calculator is based on live data from multiple crypto exchanges. Last price update for BABYDOGE to USD converter was today at 13:39 UTC. InvestorPlace – Stock Market News, Stock Advice & Trading Tips The table above shows the price and ROI of Baby Doge Coin today and previous years on the same date (Aug 9). A meme coin which was created because of a joke tweet by Elon Musk, Baby Doge has seen early growth. This is similar to the story of the Shiba token which also gained early popularity. Although there may be an investment opportunity with Baby Doge, it’s important to do your research because it will definitely be volatile.  There was Dogecoin in the beginning (DOGE). This is the digital currency that was intended to be a mockery of cryptocurrencies but ended up attracting attention and investors, becoming one of the most significant ones today.
    https://pumpyoursound.com/u/user/1452133
    Kimberly Gedeon, holding a Master’s degree in International Journalism, launched her career as a journalist for MadameNoire’s business beat in 2013. She loved translating stuffy stories about the economy, personal finance and investing into digestible, easy-to-understand, entertaining stories for young women of color. During her time on the business beat, she discovered her passion for tech as she dove into articles about tech entrepreneurship, the Consumer Electronics Show (CES) and the latest tablets. After eight years of freelancing, dabbling in a myriad of beats, she’s finally found a home at Laptop Mag that accepts her as the crypto-addicted, virtual reality-loving, investing-focused, tech-fascinated nerd she is. Woot! Bitcoin and other cryptocurrency investments are not protected by insurance from the Securities Investor Protection Corp. (SIPC). At regular brokerages, the agency protects against the loss of securities and cash in brokerage accounts containing up to $500,000, with a $250,000 cash limit. Cryptocurrency exchanges such as Coinbase have crime insurance to protect their infrastructure against hacks. But that insurance doesn’t protect individual customers from password theft. 

  9. Bond funds may comprise long-maturing Treasury and municipal issues (revenue funds) or shorter-lived Treasury bills and notes (cash market funds).

  10. Yuen Wo-Ping directed the film “Wing Chun” talked about above, and was additionally the action director for “The Matrix”, “Crouching Tiger, Hidden Dragon”, and “The Matrix Reloaded”.

  11. В текущем пространстве портативных технологий power bank является незаменимым аксессуаром для обладателей смартфонов и других портативных устройств. Это компактное зарядное устройство выступает как автономный аккумулятор с встроенным аккумулятором, позволяющий заряжать различные устройства где угодно. На рынке представлено множество моделей, включая инновационные решения, такие как [url=https://powerbanki.top/ ]Характеристики повербанка на powerbanki.top [/url], которые дают возможность заряжать устройства даже в экстремальных условиях. Важными характеристиками при выборе выступают емкость аккумулятора, количество разъемов, скорость зарядки и поддержка различных протоколов быстрой зарядки.

    Особое внимание стоит уделить выбору повербанка для iPhone, учитывая специфику зарядки устройств Apple. Новейшие беспроводные power bank совместимы с технологию MagSafe, предоставляя максимально комфортное использование с iPhone 12 и более современными моделями. При выборе необходимо обратить внимание на сертификацию MFi (Made for iPhone), которая обеспечивает безопасность использования устройства с устройствами Apple. Емкие модели с емкостью 50000 mAh способны обеспечить до 10-12 полных зарядов iPhone, а также работают для зарядки MacBook и других ноутбуков благодаря поддержке USB Power Delivery.

    Источник: [url=https://powerbanki.top/ ]https://powerbanki.top/ [/url]

    по вопросам можно ли заряжать айфон повербанком – обращайтесь в Телеграм vrp42

  12. On the next page, we will look at astrology’s impact on the modern world.

  13. In its annual review on 14 May, the Bank of Canada concluded that its three interest rate cuts in March and first ever bond buying program had succeeded in stabilizing Canadian markets.

  14. They’re comparatively simple to transport and handle, and they aren’t too picky about the place their nectar comes from, to allow them to adapt to pollinating many plants.

  15. Ease of transacting: Whether it is the creation of the accounts or the actual transactions, every activity happens via the automated systems and you only to need to make the decision on buying and selling of specified currency at specific rates and on specific dates.

  16. Some innovations are so ubiquitous that it’s difficult to imagine they began as an thought scribbled on paper and then a patent software submitted to, say, the U.S.

  17. If in case you have debt, work out how you’re going to afford your payments, and in the event you assume you could run into bother, seek the advice of a shopper credit score counseling agency.

  18. The one-volume publication includes over 150 authors each providing a two- to five-page article on a subject relevant to one of eight core topics: Economic and Income Security; Employment, Work, and Retirement; Family and Intergenerational Issues; Financial Advice, Investments, and Consumer Services; Health Care and Health Insurance; Housing and Housing Finance; Legal Issues and Services; Quality of Life and Well-Being.

  19. Santa Claus might visit American children, but in Syria, kids receive Christmas gifts from the smallest camel of one of many Three Clever Males.

  20. Instance: The Hotel Grand Chancellor in Australia makes use of SiteMinder to maximise its on-line publicity and streamline booking processes.

  21. Bell, David A. (2023), Mikaberidze, Alexander; Colson, Bruno (eds.), “The primary Complete Battle? The Place of the Napoleonic Wars within the History of Warfare”, The Cambridge Historical past of the Napoleonic Wars, vol.

  22. Carrying this Firoza stone might assist somebody who has bother expressing their emotions.

  23. ATG is ISO 9001:2015 certified, and the only World Journey Management Company in the USA to realize that certification.

  24. It looks at a broader notion of income, and captures some parts of income the federal poverty line doesn’t: expenses on childcare and commuting to work, for example.

  25. The most important of the wolf species, a grey wolf has a coat that may truly display quite a lot of colors, including gray, brown, black and white.

  26. Thus, in order to bestow your self with so many advantages, one ought to at all times buy a natural gemstone.

  27. Small business financing is more difficult for all countries as a result, and if the economy worsens, it will be harder to maintain this disproportionality.

  28. Additionally they enable each driver and passenger to fine tune the air conditioning to their own wants, and may protect your clothes from embarrassing sweat stains.

  29. Yet, even they had been seemingly shocked by the success of Taurus, the entrance-drive 1986 substitute for the junior LTD in the all-necessary midsize market.

  30. Contact-Tone Controls — All Conferencing Inc., and other host firms provide handset audio controls based on easy contact-tone combos.

  31. She had celebrated her 89th birthday on Could 6. At the age of fifty five Mrs Johnson received her Licensed Practical Nurse license and retired from this career on the age of 75.

  32. After these adjustments are made, stocks that meet the necessary qualifications are then selected to become part of the SET50 Index or the SET100 Index.

  33. The good news is getting your contemporary-baked cookies by means of the mail in order that they arrive to their recipient as deliciously because the day you baked them isn’t rocket science, however there positively is a science to it.

  34. 17.5 billion price of them for the six months ending in Might 2022, in contrast with $364 million for your complete year of 2020, the Washington Publish reported.

  35. It is a wonderful and fantastic choice for the busy government who has no time to buy.

  36. Each subsidiary has its own tax ID number and it pays all its own taxes according to the business type.

  37. Nepomniachtchi was praised by commentators for his opening preparation, with many noting that he spent very little time making his moves till move 23, a time benefit which only grew as the game progressed.

  38. Put provision – Simply as callability permits the seller to name the bond again earlier than it matures, some (however not too many) bonds have a put provision that provides the one that bought the bond a chance to sell it again at face value before it matures.

  39. All these three are implemented in order to keep systems and strategies running and focused toward desired results (n.d.).

  40. Each individual lesson is planned by your licensed driving instructor to ensure your are confident in what
    they are learning and understand your outcomes.

  41. Find driving instructors who are approved by the Driver
    and Vehicle Standards Agency (DVSA) and check their grade (if they declare it).

  42. The system is fantastic and easy to use, it makes day to day
    planning easy and always accessible.

  43. So the sooner you learn the law and safety regulations, the better driver you’ll be
    for yourself and those driving around you.

  44. Look for an instructor who is fully qualified and registered with a recognized driving school or governing body.