Showing posts with label Terraform. Show all posts
Showing posts with label Terraform. Show all posts

Tuesday, November 24, 2026

Okta as Code, Part 2

Storing Your Terraform Code in GitLab

In Part 1 I put an Okta org under Terraform on a Debian server. In this part I store that code in GitLab, so it is versioned, backed up and ready to share. Every command is followed by a short explanation, and every code box has a Copy button.

How this setup works: GitLab stores the code. Terraform still runs locally on the server: I edit the files, run terraform plan and terraform apply myself, and then commit and push the result to GitLab. The push does not change Okta. A pipeline that runs Terraform from GitLab is a later step.
Placeholders: replace it-systems-theo, Terraform-integrator-4574553 and integrator-4574553 with your own GitLab group, project and Okta org names. The project must be private, and no keys or credentials ever go into the repo.

Step 1: Create an SSH key

GitLab needs to know that pushes come from you. An SSH key pair does that without typing a password each time.

ssh-keygen -t ed25519 -C "theo@home-theo" -f ~/.ssh/id_ed25519_gitlab

This creates a key pair. -t ed25519 is a modern, short key type, -C is just a label, and -f sets the file name. It asks for a passphrase: choose one, because it protects the key if the file is ever copied.

Output of ssh-keygen

The fingerprint and the random square of characters that appear are safe to share. The private key file (id_ed25519_gitlab, without .pub) and your passphrase never are.

Print the public key and copy the whole line, which starts with ssh-ed25519:

cat ~/.ssh/id_ed25519_gitlab.pub

Step 2: Add the public key to GitLab

In GitLab, click your avatar (top left), then Edit profile.

GitLab avatar menu and Edit profile

Go to SSH Keys and click Add new key. Paste the public key, set the title to home-theo, and click Add key.

Adding a new SSH key in GitLab
The SSH key added in GitLab

Step 3: Tell SSH to use the key for GitLab

nano ~/.ssh/config

This opens (or creates) the file that controls how SSH connects to each server. Paste this, then save with Ctrl+O, Enter, and exit with Ctrl+X:

Host gitlab.com
  HostName gitlab.com
  User git
  IdentityFile ~/.ssh/id_ed25519_gitlab
  IdentitiesOnly yes

Whenever you connect to gitlab.com, SSH logs in as the user git and uses only this key.

Restrict the file so only you can read it:

chmod 600 ~/.ssh/config

Test the connection:

ssh -T git@gitlab.com

The first time, answer yes to the fingerprint question and enter your passphrase if you set one. Success looks like Welcome to GitLab, @yourusername!

Successful SSH test against GitLab

Step 4: Create the project in GitLab

Click New project, then Create blank project.

Creating a blank project in GitLab

Set Visibility Level to Private.

Untick “Initialize repository with a README”. Your local repository already has commits, and a README would make the first push fail.
Project settings with Private visibility and no README

After you click Create project, GitLab shows instructions for an empty project. Use the section Push an existing Git repository. Ignore the other two, because they would create a second repository.

GitLab instructions for an empty project

Step 5: Link your local repository and push

Go to the local repository and set the name and email recorded on your commits, for this repo only:

cd ~/okta-terraform
git config --local user.name "Your Name"
git config --local user.email "you@example.com"

Link the local repository to the GitLab project. Copy the address from Code > Clone with SSH in GitLab:

git remote add origin git@gitlab.com:it-systems-theo/Terraform-integrator-4574553.git

This tells Git that the GitLab project is called origin. Check it:

git remote -v

It lists two lines, one for fetch and one for push, with the same address.

Before you push anything, run git ls-files. It lists every tracked file, and you should see only .gitignore, your .tf files and .terraform.lock.hcl. If a .pem, .env or .tfstate file appears, stop and remove it from Git first.
git ls-files

Push your main branch:

git push --set-upstream origin main

This uploads your commits. --set-upstream remembers the link, so later a plain git push is enough. If your key has a passphrase, it asks for it now (nothing shows as you type).

Output of git push

Step 6: Make a change: add a group and a rule

Now the real workflow. Edit the Terraform code, apply it locally, then store the change in GitLab.

Move to the Terraform folder. This is not the project root:

cd ~/okta-terraform/envs/okta-integrator-4574553

Open main.tf (or edit it in VS Code):

nano main.tf

Add this at the very bottom, below the existing blocks. Don't delete anything:

resource "okta_group" "it_support" {
  name        = "IT Support"
  description = "Managed by Terraform"
}

resource "okta_group_rule" "it_support" {
  name              = "IT Support by department"
  status            = "ACTIVE"
  group_assignments = [okta_group.it_support.id]
  expression_type   = "urn:okta:expression:1.0"
  expression_value  = "user.department==\"IT\""
}

The first block creates a group named IT Support. The second block automatically adds users whose department equals IT to that group. It refers to the group with okta_group.it_support.id, so Terraform creates the group first.

Step 7: Check, plan and apply locally

Load your Okta credentials, tidy the formatting and check the syntax:

source ~/.okta/okta-integrator-4574553.env
terraform fmt
terraform validate

source loads your credentials into this terminal. terraform fmt formats the files. terraform validate checks the syntax without contacting Okta, and you want Success! The configuration is valid.

Preview the changes:

terraform plan

This logs in to Okta and shows what would change, without changing anything. A good result ends with Plan: 2 to add, 0 to change, 0 to destroy.

Output of terraform plan

Apply the changes:

terraform apply

Type yes when asked. It should end with Apply complete! Resources: 2 added, 0 changed, 0 destroyed. Then check Directory > Groups in the Okta Admin Console.

Output of terraform apply

Step 8: Commit and push the change to GitLab

Only now does the change go to GitLab, as a record of what you applied. Go to the project root and check what changed:

cd ~/okta-terraform
git status

git status should list only main.tf as modified. Stage it by name, commit it and push it:

git add envs/okta-integrator-4574553/main.tf
git commit -m "Add IT Support group and rule"
git push
  • git add stages the file
  • git commit records it in local history with a message
  • git push uploads the commit to GitLab

Your daily routine from now on:

git status
git add FILENAME
git commit -m "What changed"
git push

What GitLab does and does not do here

  • GitLab: stores and versions the code, so you have history and a backup.
  • The server: runs Terraform, holds the credentials in ~/.okta and keeps the state file.
  • You: are the automation. A push to GitLab does not change Okta.

Next: a GitLab pipeline that runs terraform plan on merge requests and apply on main. That needs remote state, a runner and the Okta credentials stored as CI variables, so I'll cover it in the next part.

Okta as Code, Part 1

Setting Up Terraform on Debian

Managing Okta by clicking through the Admin Console works, until you need a second environment or want to know who changed what. In this post I put an Okta org under Terraform on a minimal Debian 13 server, step by step. Every command is followed by a short explanation, and every code box has a Copy button.

Placeholders: my Okta org is integrator-4574553, and I use that name in file names. Replace it with your own org name everywhere it appears.

What you need first

  • A Debian 13 machine (I used a minimal install over SSH) and an Okta org with admin access.
  • An OAuth service app with a private key, not an API token. A token has the full rights of the admin who created it and expires after 30 days unused. A service app only gets the scopes and role you give it.

Step 1: Install Terraform

Minimal Debian has no sudo. If you get sudo: command not found, run su -, then apt-get install -y sudo and usermod -aG sudo YOURUSER, then log out and back in.

First, install the tools needed to add HashiCorp's package repository:

sudo apt-get update && sudo apt-get install -y gnupg curl lsb-release

apt-get update refreshes the list of available packages. && runs the second command only if the first succeeds. The install adds three tools:

  • gnupg checks cryptographic signatures
  • curl downloads files
  • lsb-release reports your Debian codename (for example trixie)

Download HashiCorp's signing key:

wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg

This downloads the public key (wget -O- prints it instead of saving it), pipes it (|) into gpg --dearmor, which converts it to the binary format apt expects, and saves it in the keyrings folder. apt uses it to verify that packages really come from HashiCorp.

Add the HashiCorp repository:

echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list

This writes one line into a new apt source file, telling Debian where HashiCorp's packages live and which key to trust. $(lsb_release -cs) fills in your Debian codename, and tee with sudo lets you write into a protected folder. If you get a 404 later, replace the codename with bookworm.

Install Terraform and check the version:

sudo apt-get update && sudo apt-get install -y terraform
terraform -version

The first line refreshes the package list (now including HashiCorp) and installs Terraform. The second prints the version, which proves it works. This guide needs 1.10 or higher.

terraform -version output

Step 2: Create the service app in Okta

In the Admin Console, go to Applications > Applications > Create App Integration. Choose API Services, name it Terraform, and keep the default Okta-generated client ID.

Creating the API Services app in Okta
Terraform app created in Okta

On the General tab, under Client Credentials, choose Public key / Private key.

Now add a public key: click Add > Generate new key and choose the key size (I used 4096-bit).

Adding a public key to the Okta app

The private key is shown only once. Select the PEM tab (not JSON) and click Copy to clipboard. Keep this dialog open while you save the key on your server (next step).

The generated key in PEM and JSON formats

Next, on the Okta API Scopes tab, grant the scopes you need, for example okta.groups.manage. A typical set:

okta.groups.manage
okta.apps.manage
okta.policies.manage
okta.authorizationServers.manage
okta.users.manage
okta.idps.manage
okta.trustedOrigins.manage
okta.schemas.manage
okta.networkZones.manage
okta.brands.manage
Granting API scopes

Scopes alone are not enough: the app also needs an admin role. On Admin roles, assign Super Administrator to start with, and narrow it to a custom role later.

Admin roles tab
Super Administrator assigned

Finally, copy the Client ID from the top of the General tab. It is not a secret.

Step 3: Store the credentials on the server

Back in the terminal. Create a private folder for secrets in your home directory:

mkdir -p ~/.okta && chmod 700 ~/.okta

-p means no error if it already exists. chmod 700 makes the folder accessible only to you.

Create the key file, paste the PEM you copied, press Ctrl+O then Enter to save, and Ctrl+X to exit:

nano ~/.okta/terraform-okta-integrator-4574553.pem

Make the key readable and writable by you only, then check the first line without showing the key:

chmod 600 ~/.okta/terraform-okta-integrator-4574553.pem
head -1 ~/.okta/terraform-okta-integrator-4574553.pem

The second command should print -----BEGIN PRIVATE KEY-----.

Create the credentials file:

nano ~/.okta/okta-integrator-4574553.env

Paste this, replacing the Client ID and KID with your real values from Okta (not the placeholders):

export OKTA_ORG_NAME="integrator-4574553"        # yourorg.okta.com -> "yourorg"
export OKTA_BASE_URL="okta.com"                  # or oktapreview.com / okta-emea.com
export OKTA_API_CLIENT_ID="YOUR_CLIENT_ID"
export OKTA_API_PRIVATE_KEY_ID="YOUR_KID"
export OKTA_API_PRIVATE_KEY="$(cat ~/.okta/terraform-okta-integrator-4574553.pem)"
export OKTA_API_SCOPES="okta.groups.manage,okta.apps.manage,okta.policies.manage,okta.authorizationServers.manage,okta.users.manage"
The credentials file

What each line does:

  • OKTA_ORG_NAME: the first part of your Okta URL
  • OKTA_BASE_URL: the domain, usually okta.com
  • OKTA_API_CLIENT_ID: which app is logging in
  • OKTA_API_PRIVATE_KEY_ID: the KID of the registered key
  • OKTA_API_PRIVATE_KEY: the contents of the PEM, read in by $(cat ...)
  • OKTA_API_SCOPES: the permissions requested

Restrict the file to you only:

chmod 600 ~/.okta/okta-integrator-4574553.env

Load the variables into your current terminal:

source ~/.okta/okta-integrator-4574553.env

Run this in every new terminal, and again after editing the file, because a terminal keeps the old values until you reload.

Optional: load the credentials automatically

To avoid typing source each time, add it to your shell startup file:

nano ~/.bashrc

Add this line at the very bottom, save, then load it in the current terminal:

source ~/.okta/okta-integrator-4574553.env
source ~/.bashrc
Trade-off: your private key is then present in every terminal session. That is fine on a personal home server, but on a shared machine, or once you manage more than one Okta org, load the right file by hand instead.

Step 4: Set up Git and the project folders

Install Git, which tracks changes to your files:

sudo apt-get install -y git

Tell Git who you are (used in commit history) and name the default branch main:

git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main

Create the project folder, with one subfolder per Okta org. That keeps each org's code and state separate:

mkdir -p ~/okta-terraform/envs/okta-integrator-4574553

Move into the project root and turn it into a Git repository:

cd ~/okta-terraform
git init

Create the file that tells Git what never to track:

nano .gitignore
.terraform/
*.tfstate
*.tfstate.*
*.tfvars
*.pem
*.env
key.json
crash.log
Why this matters: Terraform state files can contain secrets, and keys must never reach GitHub. Keep your .pem and .env files in ~/.okta, outside the repo, and make any GitHub repo private. Do not ignore .terraform.lock.hcl; that one should be committed.

Save the ignore file as the first commit:

git add .gitignore
git commit -m "Add .gitignore"

git add stages the file and git commit records it in history with a message.

Step 5: Write the Terraform files

Move into the folder where Terraform runs. All terraform commands go here:

cd ~/okta-terraform/envs/okta-integrator-4574553

versions.tf pins the versions. It needs Terraform 1.10 or newer and the Okta provider from the 5.x series. With no backend block, state stays in a local file.

nano versions.tf
terraform {
  required_version = ">= 1.10"

  required_providers {
    okta = {
      source  = "okta/okta"
      version = "~> 5.0"
    }
  }
}

provider.tf sets rate-limit and retry behaviour. It uses at most 50% of Okta's API rate limit and waits and retries when limited. There are no credentials here, because they come from the OKTA_* variables.

nano provider.tf
provider "okta" {
  max_api_capacity = 50
  backoff          = true
  min_wait_seconds = 5
  max_wait_seconds = 60
  max_retries      = 5
}

main.tf holds the actual resources, a small first test:

nano main.tf
data "okta_group" "everyone" {
  name = "Everyone"
}

resource "okta_group" "engineering" {
  name        = "Engineering"
  description = "Managed by Terraform"
}

resource "okta_group_rule" "engineering" {
  name              = "Engineering by department"
  status            = "ACTIVE"
  group_assignments = [okta_group.engineering.id]
  expression_type   = "urn:okta:expression:1.0"
  expression_value  = "user.department==\"Engineering\""
}
  • data "okta_group" only reads the built-in Everyone group and changes nothing. Built-in objects cannot be created or deleted, so you reference them with a data source.
  • resource "okta_group" creates a group named Engineering.
  • resource "okta_group_rule" automatically adds users whose department equals Engineering.

Step 6: Run Terraform

Download the Okta provider plugin and create .terraform.lock.hcl, which records the exact versions. This step needs no credentials:

terraform init

Check the files for syntax errors without contacting Okta:

terraform validate

Show what would be created, changed or deleted, without changing anything. This is the first step that logs in to Okta, so credential problems appear here:

source ~/.okta/okta-integrator-4574553.env
terraform plan

A good result ends with Plan: 2 to add, 0 to change, 0 to destroy. Then apply it:

terraform apply

Terraform shows the plan again and, after you type yes, creates the group and rule. Check them in the Admin Console under Directory > Groups.

Commit your work

Go to the project root and check what Git sees. No .pem, .env or .tfstate file should appear in the list:

cd ~/okta-terraform
git status

Add the files by name (safer than git add .) and commit:

git add envs/okta-integrator-4574553/*.tf envs/okta-integrator-4574553/.terraform.lock.hcl
git commit -m "Add Okta Terraform config"