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.
Overview
So 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
Prerequisites:
- Terraform CLI version 1.5+
- Auth0 CLI version 1.1+
- jq
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
.auth0 login --scopes create:client_grants
If you don't already have an Auth0 tenant, you can sign up for a free Auth0 account and create a tenant.
Run the following commands to create a machine-to-machine application and extract the client ID and secret from the output.
# Create a machine-to-machine application on Auth0 export AUTH0_M2M_APP=$(auth0 apps create \ --name "Auth0 Terraform Provider" \ --description "Auth0 Terraform Provider M2M" \ --type m2m \ --reveal-secrets \ --json | jq -r '. | {client_id: .client_id, client_secret: .client_secret}') # Extract the client ID and client secret from the output. export AUTH0_CLIENT_ID=$(echo $AUTH0_M2M_APP | jq -r '.client_id') export AUTH0_CLIENT_SECRET=$(echo $AUTH0_M2M_APP | jq -r '.client_secret')
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:
# Get the ID and IDENTIFIER fields of the Auth0 Management API export AUTH0_MANAGEMENT_API_ID=$(auth0 apis list --json | jq -r 'map(select(.name == "Auth0 Management API"))[0].id') export AUTH0_MANAGEMENT_API_IDENTIFIER=$(auth0 apis list --json | jq -r 'map(select(.name == "Auth0 Management API"))[0].identifier') # Get the SCOPES to be authorized export AUTH0_MANAGEMENT_API_SCOPES=$(auth0 apis scopes list $AUTH0_MANAGEMENT_API_ID --json | jq -r '.[].value' | jq -ncR '[inputs]') # Authorize the Auth0 Terraform Provider application to use the Auth0 Management API auth0 api post "client-grants" --data='{"client_id": "'$AUTH0_CLIENT_ID'", "audience": "'$AUTH0_MANAGEMENT_API_IDENTIFIER'", "scope":'$AUTH0_MANAGEMENT_API_SCOPES'}'
If you don't want to authorize all scopes for the Terraform Provider, you can filter the required scopes from the output of
and pass it to theauth0 apis scopes list
command in place ofauth0 api post
. Make sure to pass a valid JSON array of strings.$AUTH0_MANAGEMENT_API_SCOPES
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:mkdir terraform cd terraform touch versions.tf
Add the following to the file:
terraform { required_version = ">= 1.7.0" required_providers { auth0 = { source = "auth0/auth0" version = "~> 1.1.2" # 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:touch config.tf
Add the following to the file:
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:
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:# 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
resource definition creates an Auth0 Web application client conforming to the OIDC standard.auth0_client
- The
resource definition configures the client to use theauth0_client_credentials
authentication method (confidential client using HTTP POST parameters). Other supported methods are:client_secret_post
: Public client without a client secretnone
: Confidential client using HTTP Basicclient_secret_basic
: Confidential client using a Private Key JWTprivate_key_jwt
Refer to the
schema andauth0_client
schema for all possible configurations.auth0_client_credentials
Next, you can also define some outputs to be captured. Create a
outputs.tf
file:touch outputs.tf
Add the following to the file:
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.
# 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:
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:
# Client ID terraform output --json | jq -r '.auth0_webapp_client_id.value' # Client Secret terraform output --json | jq -r '.auth0_webapp_client_secret.value'
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: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: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:# 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 = "jane@test.com" 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 = "john@test.com" 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
schema and auth0_role
schema for all possible configurations. auth0_user
and auth0_role_permission
resources can be used to manage permissions for roles.auth0_role_permissions
Run the following commands to plan and apply the changes:
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:# 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
schema for all possible configurations.auth0_action
Plan and apply the changes:
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:
export AUTH0_DOMAIN=<your-auth0-domain> auth0 tf generate --output-dir tmp-auth0-tf
This will create the below files in the
tmp-auth0-tf
folder:
: Terraform configurations to import the existing resources into the Terraform state.auth0_import.tf
: Terraform configurations for the Auth0 Terraform Provider. You may want to update theauth0_main.tf
to match the Terraform CLI version you are using.required_version
: Terraform configurations for the resources in the Auth0 tenant.auth0_generated.tf
: 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 updateterraform
inrequired_version
.auth0_main.tf
: Terraform state files..terraform*
Now, you can import the existing resources into the Terraform state. Run the following commands:
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
.# You can remove the import file as it's no longer needed. rm auth0_import.tf terraform plan
The output should be
No changes. Your infrastructure matches the configuration.
Note that the
command cannot import sensitive values like secrets and keys.auth0 tf generate
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:
terraform destroy
Learn More about Terraform, Auth0, and DevOps
If you want to learn more about Terraform, Auth0 Actions, and DevOps, check out these additional resources.
- Deploy Secure Spring Boot Microservices on Amazon EKS Using Terraform and Kubernetes
- Shhhh... Kubernetes Secrets Are Not Really Secret!
- Auth0 CLI Basics - Lab
- Assigning a Default Role to Users on Sign-Up with Auth0 Actions
- Ensure Users Log in from Trusted Networks with Auth0 Actions
You can also sign up for our newsletter to stay updated on everything related to Identity and Security.
If you liked this tutorial, chances are you'll enjoy the others we publish. Please follow @oktadev on Twitter and subscribe to our YouTube channel to get notified when we publish new developer tutorials.
About the author
Deepu K Sasidharan
Staff Developer Advocate