Getting Started with the Auth0 Terraform Provider

Published on December 9, 2024
Learning GoalLearn how to get started with the Auth0 using the Auth0 Terraform Provider to automate your infrastructure configuration.

Here is what you will learn to do today:

  • Setup the Auth0 Terraform Provider with Auth0 CLI
  • Create a new Auth0 application for OpenID Connect (OIDC) authentication
  • Create roles and users for Auth0
  • Create an action to customize the authentication flow
  • Generate terraform configurations from your existing Auth0 tenant using Auth0 CLI

Why Use Terraform?

When managing infrastructure for any large enough organization, you will need to automate the provisioning and configuration of resources, services, and applications. Terraform has been the de facto standard for infrastructure as code (IaC) for a while now. Terraform's declarative syntax and cross-platform support make it a great choice for managing infrastructure. Terraform is cloud-agnostic and supports all major cloud providers and on-premise setups. It also supports a lot of other services and applications using providers.

If you use Terraform in your organization and want to configure and manage your Auth0 tenants with Terraform, you are in luck because Auth0 has a Terraform Provider. The Auth0 Terraform Provider allows you to automate the configuration of Auth0 resources like applications, connections, actions, and more. You can also use it to manage users and groups. With the Auth0 Terraform provider, you can automate almost everything you can do via the management UI.

Set up a Development Environment

  • Use your favorite text editor or IDE. We recommend using Visual Studio Code.
  • Install the Terraform CLI version 1.5+.
  • Install jq if you are using Linux or macOS.
  • Windows commands in this guide are written for PowerShell version 5+.

Create an Auth0 account

If you already have an Auth0 account, you can log in to your tenant and continue to the next step.

Otherwise, sign up for a free Auth0 account.

During the sign-up process, you create something called an Auth0 Tenant, where you configure your use of Auth0.

Once you sign in, Auth0 takes you to the Auth0 Dashboard, where you can configure and manage Auth0 assets, such as applications, APIs, connections, and user profiles.

Set up the Auth0 CLI

If you are not familiar with the Auth0 CLI, you can follow the "Auth0 CLI Basics" lab to learn how to build, manage, and test your Auth0 integrations from the command line.

There are different ways to install the Auth0 CLI, depending on your operating system.

LOADING...

Test the Auth0 CLI installation

Run the following command to show in the terminal the version of your Auth0 CLI installation:

COMMAND
auth0 --version

You should see the following output:

auth0 version <version-number> <hash>

Setup the Auth0 Terraform Provider

Before you can set up the Auth0 Terraform Provider, you need to create a machine-to-machine application in Auth0 so that Terraform can communicate with the Auth0 management API. This can be done using the Auth0 CLI. Install the Auth0 CLI and login to your tenant with the create:client_grants.

COMMAND
auth0 login --scopes create:client_grants

Run the following commands to create a machine-to-machine application and extract the client ID and secret from the output.

LOADING...

The environment variable names should be exactly as above as the Terraform provider expects these variables to be set.

The commands above will create the application and set environment variables for the client ID and secret.

This application needs to be authorized to use the Auth0 management API. This can be done using the commands below:

LOADING...

If you don't want to authorize all scopes for the Terraform Provider, you can filter the required scopes from the output of auth0 apis scopes list and pass it to the auth0 api post command in place of $AUTH0_MANAGEMENT_API_SCOPES. Make sure to pass a valid JSON array of strings.

Now, you can set up the Auth0 Terraform Provider. First, make sure you use a specific version of the providers, as different versions might use different attributes and features. Create a versions.tf file:

LOADING...

Add the following to the file:

versions.tf
terraform {
required_version = ">= 1.8.1"
required_providers {
auth0 = {
source = "auth0/auth0"
version = "~> 1.9.0" # Refer to docs for latest version
}
## Add other providers here
}
}

Next, you need to define variables and configure the provider. Create a config.tf file:

LOADING...

Add the following to the file:

config.tf
variable "auth0_domain" {
default = "https://<your_auth0_domain_uri>"
description = "Auth0 domain"
}
provider "auth0" {
domain = var.auth0_domain
debug = false
}

You can find your Auth0 domain in the Auth0 dashboard or by running the auth0 tenants list command.

Now, you can initialize the Terraform workspace and test the provider by running the following commands:

COMMAND
terraform init

Create an Auth0 Application

Let's get into business. Create a Terraform script that creates an Auth0 web application and required customizations. Create a file named auth0.tf in the terraform folder and add the following content:

auth0.tf
# Create a new Auth0 application for OIDC authentication
resource "auth0_client" "oidc_client" {
name = "MyCoolApp"
description = "My Cool App Client Created Through Terraform"
app_type = "regular_web"
callbacks = ["http://localhost:8080/callback"]
allowed_logout_urls = ["http://localhost:8080"]
oidc_conformant = true
jwt_configuration {
alg = "RS256"
}
}
# Configuring client_secret_post as an authentication method.
resource "auth0_client_credentials" "oidc_client_creds" {
client_id = auth0_client.oidc_client.id
authentication_method = "client_secret_post"
}

The script above does the following:

  • The auth0_client resource definition creates an Auth0 Web application client conforming to the OIDC standard.
  • The auth0_client_credentials resource definition configures the client to use the client_secret_post authentication method (confidential client using HTTP POST parameters). Other supported methods are:
    • none: Public client without a client secret
    • client_secret_basic: Confidential client using HTTP Basic
    • private_key_jwt: Confidential client using a Private Key JWT

Refer to the auth0_client schema and auth0_client_credentials schema for all possible configurations.

Next, you can also define some outputs to be captured. Create a outputs.tf file:

LOADING...

Add the following to the file:

outputs.tf
output "auth0_webapp_client_id" {
description = "Auth0 JavaMicroservices Client ID"
value = auth0_client.oidc_client.client_id
}
output "auth0_webapp_client_secret" {
description = "Auth0 JavaMicroservices Client Secret"
value = auth0_client_credentials.oidc_client_creds.client_secret
sensitive = true
}

Now you can run the Terraform script to create the Auth0 application. Run the following commands to plan and apply it.

COMMAND
# see a preview of what will be done
terraform plan

Review the plan and make sure everything is correct.

Now you can apply the changes:

COMMAND
terraform apply

You will see the configurations being applied and the output variables printed to the console.

Go to Auth0 dashboard and check Applications > Applications. You should see the application created. You can also find the application using the Auth0 CLI with the auth0 apps list command.

If you want to get the client ID and secret from the output, you can run the following command:

COMMAND
# Client ID
terraform output auth0_webapp_client_id
# Client Secret
terraform output auth0_webapp_client_secret

You can update the allowed callback URLs and allowed logout URLs in the Auth0 web application. You can do this by adding the values to the callbacks and allowed_logout_urls array in the oidc_client resource in the auth0.tf file like below:

auth0.tf
resource "auth0_client" "oidc_client" {
name = "MyCoolApp"
description = "My Cool App Client Created Through Terraform"
app_type = "regular_web"
callbacks = ["http://localhost:8080/callback", "http://another-domain/callback"]
allowed_logout_urls = ["http://localhost:8080", "http://another-domain"]
oidc_conformant = true
jwt_configuration {
alg = "RS256"
}
}

Run terraform apply -target="auth0_client.oidc_client" to update the configuration in your Auth0 tenant.

Create Roles and Users

You can create roles and users using the Auth0 Terraform provider. Let's create some roles and users and then let's assign the roles to the users.

Add the following content to the config.tf file to get a default password while applying the Terraform script:

config.tf
variable "default_password" {
# Should be a strong password. Example: lkjhasdf$12$12
description = "Default password for all users"
sensitive = true
}

Add the following content to the auth0.tf file:

auth0.tf
# Create a role for admin users
resource "auth0_role" "admin" {
name = "ROLE_ADMIN"
description = "Administrator"
}
# Create a role for regular users
resource "auth0_role" "user" {
name = "ROLE_USER"
description = "User"
}
# Create an admin user
resource "auth0_user" "admin_user" {
connection_name = "Username-Password-Authentication"
name = "Jane Doe"
email_verified = true
password = var.default_password
}
# Assign roles to the admin user
resource "auth0_user_roles" "admin_user_roles" {
user_id = auth0_user.admin_user.id
roles = [auth0_role.admin.id, auth0_role.user.id]
}
# Create a regular user
resource "auth0_user" "regular_user" {
connection_name = "Username-Password-Authentication"
name = "John Doe"
email_verified = false
password = var.default_password
}
# Assign roles to the regular user
resource "auth0_user_roles" "regular_user_roles" {
user_id = auth0_user.regular_user.id
roles = [auth0_role.user.id]
}

Refer to the auth0_role schema and auth0_user schema for all possible configurations. auth0_role_permission and auth0_role_permissions resources can be used to manage permissions for roles.

Run the following commands to plan and apply the changes:

COMMAND
terraform plan
# Verify the plan
terraform apply

Provide a default password when prompted. You can find the user IDs in the output.

Create an Action to Customize the Authentication Flow

One of the most powerful features of Auth0 is the ability to customize the authentication flow using Actions. Actions are custom code that runs during the authentication flow. Actions can be used to add custom claims to the ID and access tokens, custom logic to the authentication flow, and more. You can use the Auth0 Terraform provider to create and manage actions.

Let's create an action that adds the roles to the ID and access tokens. Add the following content to the auth0.tf file:

auth0.tf
# Create an action to add the roles to the ID/access token claims.
resource "auth0_action" "roles_action" {
name = "add_roles_claim"
runtime = "node18"
deploy = true
code = <<-EOT
/**
* Handler that will be called during the execution of a PostLogin flow.
*
* @param {Event} event - Details about the user and the context in which they are logging in.
* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
*/
exports.onExecutePostLogin = async (event, api) => {
const namespace = 'https://www.cooldomain.com';
if (event.authorization) {
api.idToken.setCustomClaim(namespace + '/roles', event.authorization.roles);
api.accessToken.setCustomClaim(namespace + '/roles', event.authorization.roles);
}
};
EOT
supported_triggers {
id = "post-login"
version = "v3"
}
}
# Attach the action to the login flow
resource "auth0_trigger_actions" "login_flow" {
trigger = "post-login"
actions {
id = auth0_action.roles_action.id
display_name = auth0_action.roles_action.name
}
}

Refer to the auth0_action schema for all possible configurations.

Plan and apply the changes:

COMMAND
terraform plan
# Verify the plan
terraform apply

Generate Terraform Configurations from Your Existing Auth0 Tenant Using Auth0 CLI

You may already have an existing Auth0 tenant with applications, connections, users, and more. You can use the Auth0 CLI to generate Terraform configurations from your existing Auth0 tenant. Run the following command to generate the Terraform configurations from the above setup:

LOADING...

This will create the below files in the tmp-auth0-tf folder:

  • auth0_import.tf: Terraform configurations to import the existing resources into the Terraform state.
  • auth0_main.tf: Terraform configurations for the Auth0 Terraform Provider. You may want to update the required_version to match the Terraform CLI version you are using.
  • auth0_generated.tf: Terraform configurations for the resources in the Auth0 tenant.
  • terraform: A specific version of the Terraform binary used for the import. You can use this binary to run terraform commands if you don't want to update required_version in auth0_main.tf.
  • .terraform*: Terraform state files.

Now, you can import the existing resources into the Terraform state. Run the following commands:

COMMAND
cd tmp-auth0-tf
terraform apply # You can use your local Terraform CLI if you have updated `required_version` in `auth0_main.tf` else run `./terraform apply`

You can verify the generated configurations by running terraform plan.

LOADING...

The output should be No changes. Your infrastructure matches the configuration.

Note that the auth0 tf generate command cannot import sensitive values like secrets and keys.

Note that this feature is available only from version 1.1+ of the Auth0 CLI and Terraform import is supported only from Terraform version 1.5+.

Tear Down the Cluster with Terraform

Once you are done with the tutorial, you can delete all the resources created using Terraform by running the following command:

COMMAND
terraform destroy

Recap

In this guide, you learned how to configure your Auth0 infrastructure using Terraform, the Auth0 Terraform Provider and Auth0 CLI. Isn't it cool how you can create and test an Auth0 infrastructure with Terraform so quickly?

Check out our other guide, "Auth0 CLI Basics", to learn more.