# Deploying Login Rules via Terraform

This guide will explain how to:

- Use Teleport's Terraform Provider to deploy Login Rules to your Teleport cluster
- Edit deployed Login Rules via Terraform

## How it works

Login Rules are registered with the Teleport Auth Service as resources stored on the Auth Service backend. The Teleport Auth Service exposes a gRPC API that enables clients to create, delete, or modify backend resources, including Login Rules. The Teleport Terraform Provider can manage Login Rules by authenticating to the Teleport Auth Service and interacting with its gRPC API.

## Prerequisites

- A running Teleport Enterprise cluster. If you want to get started with Teleport, [sign up](https://goteleport.com/signup) for a free trial or [set up a demo environment](https://goteleport.com/docs/get-started/deploy-community.md).

- The `tctl` and `tsh` clients.

  Installing `tctl` and `tsh` clients

  1. Determine the version of your Teleport cluster. The `tctl` and `tsh` clients must be at most one major version behind your Teleport cluster version. Send a GET request to the Proxy Service at `/v1/webapi/find` and use a JSON query tool to obtain your cluster version. Replace teleport.example.com:443 with the web address of your Teleport Proxy Service:

     ```
     $ TELEPORT_DOMAIN=teleport.example.com:443
     $ TELEPORT_VERSION="$(curl -s https://$TELEPORT_DOMAIN/v1/webapi/find | jq -r '.server_version')"
     ```

  2. Follow the instructions for your platform to install `tctl` and `tsh` clients:

     **Mac**

     Download the signed macOS .pkg installer for Teleport, which includes the `tctl` and `tsh` clients:

     ```
     $ curl -O https://cdn.teleport.dev/teleport-${TELEPORT_VERSION?}.pkg
     ```

     In Finder double-click the `pkg` file to begin installation.

     ---

     DANGER

     Using Homebrew to install Teleport is not supported. The Teleport package in Homebrew is not maintained by Teleport and we can't guarantee its reliability or security.

     ---

     **Windows - Powershell**

     ```
     $ curl.exe -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-windows-amd64-bin.zip
     Unzip the archive and move the `tctl` and `tsh` clients to your %PATH%
     NOTE: Do not place the `tctl` and `tsh` clients in the System32 directory, as this can cause issues when using WinSCP.
     Use %SystemRoot% (C:\Windows) or %USERPROFILE% (C:\Users\<username>) instead.
     ```

     **Linux**

     All of the Teleport binaries in Linux installations include the `tctl` and `tsh` clients. For more options (including RPM/DEB packages and downloads for i386/ARM/ARM64) see our [installation page](https://goteleport.com/docs/installation.md).

     ```
     $ curl -O https://cdn.teleport.dev/teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gz
     $ tar -xzf teleport-v${TELEPORT_VERSION?}-linux-amd64-bin.tar.gz
     $ cd teleport
     $ sudo ./install
     Teleport binaries have been copied to /usr/local/bin
     ```

* To check that you can connect to your Teleport cluster, sign in with `tsh login`, then verify that you can run `tctl` commands using your current credentials.

  For example, run the following command, assigning teleport.example.com to the domain name of the Teleport Proxy Service in your cluster and email\@example.com to your Teleport username:

  ```
  $ tsh login --proxy=teleport.example.com --user=email@example.com
  $ tctl status
  Cluster  teleport.example.com
  Version  18.7.3
  CA pin   sha256:abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678abdc1245efgh5678
  ```

  If you can connect to the cluster and run the `tctl status` command, you can use your current credentials to run subsequent `tctl` commands from your workstation. If you host your own Teleport cluster, you can also run `tctl` commands on the computer that hosts the Teleport Auth Service for full permissions.

* [Terraform >= 1.0.0+](https://learn.hashicorp.com/tutorials/terraform/install-cli)

  ```
  $ terraform version
  Terraform v1.0.0
  ```

## Step 1/4. Set up Teleport credentials for Terraform

For simplicity, this guide will configure the Terraform provider to use your current logged-in user's Teleport credentials obtained from `tsh login`.

---

NOTE

The [Terraform provider guide](https://goteleport.com/docs/zero-trust-access/infrastructure-as-code/terraform-provider.md) includes instructions for configuring a dedicated `terraform` user and role, which is a better option when running Terraform in a non-interactive environment.

If you are already using Terraform to manage other resources in your Teleport cluster then you have probably already set up a `terraform` user and role and configured the associated credentials. Make sure to use the `terraform` role from the latest version of the guide, which has `list`, `read`, `create`, `update`, and `delete` verbs for `login_rule` resources.

---

First, ensure you are logged into Teleport as a user that has permissions to read and modify `login_rule` resources. The preset `editor` role has access to this already, but in case you are using a more customized configuration, create a role called `loginrule-manager.yaml` with the following contents:

```
kind: role
metadata:
  name: loginrule-manager
spec:
  allow:
    rules:
      - resources: [login_rule]
        verbs: [list, read, create, update, delete]
version: v7

```

Create the role with `tctl`:

```
$ tctl create loginrule-manager.yaml
role 'loginrule-manager' has been created
```

Assign the `loginrule-manager` role to your Teleport user by running the appropriate commands for your authentication provider:

**Local User**

1. Retrieve your local user's roles as a comma-separated list:

   ```
   $ ROLES=$(tsh status -f json | jq -r '.active.roles | join(",")')
   ```

2. Edit your local user to add the new role:

   ```
   $ tctl users update $(tsh status -f json | jq -r '.active.username') \
     --set-roles "${ROLES?},loginrule-manager"
   ```

3. Sign out of the Teleport cluster and sign in again to assume the new role.

**GitHub**

1. Open your `github` authentication connector in a text editor:

   ```
   $ tctl edit github/github
   ```

2. Edit the `github` connector, adding `loginrule-manager` to the `teams_to_roles` section.

   The team you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the team must include your user account and should be the smallest team possible within your organization.

   Here is an example:

   ```
     teams_to_roles:
       - organization: octocats
         team: admins
         roles:
           - access
   +       - loginrule-manager

   ```

3. Apply your changes by saving and closing the file in your editor.

4. Sign out of the Teleport cluster and sign in again to assume the new role.

**SAML**

1. Retrieve your `saml` configuration resource:

   ```
   $ tctl get --with-secrets saml/mysaml > saml.yaml
   ```

   Note that the `--with-secrets` flag adds the value of `spec.signing_key_pair.private_key` to the `saml.yaml` file. Because this key contains a sensitive value, you should remove the saml.yaml file immediately after updating the resource.

2. Edit `saml.yaml`, adding `loginrule-manager` to the `attributes_to_roles` section.

   The attribute you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the group must include your user account and should be the smallest group possible within your organization.

   Here is an example:

   ```
     attributes_to_roles:
       - name: "groups"
         value: "my-group"
         roles:
           - access
   +       - loginrule-manager

   ```

3. Apply your changes:

   ```
   $ tctl create -f saml.yaml
   ```

4. Sign out of the Teleport cluster and sign in again to assume the new role.

**OIDC**

1. Retrieve your `oidc` configuration resource:

   ```
   $ tctl get oidc/myoidc --with-secrets > oidc.yaml
   ```

   Note that the `--with-secrets` flag adds the value of `spec.signing_key_pair.private_key` to the `oidc.yaml` file. Because this key contains a sensitive value, you should remove the oidc.yaml file immediately after updating the resource.

2. Edit `oidc.yaml`, adding `loginrule-manager` to the `claims_to_roles` section.

   The claim you should map to this role depends on how you have designed your organization's role-based access controls (RBAC). However, the group must include your user account and should be the smallest group possible within your organization.

   Here is an example:

   ```
     claims_to_roles:
       - name: "groups"
         value: "my-group"
         roles:
           - access
   +       - loginrule-manager

   ```

3. Apply your changes:

   ```
   $ tctl create -f oidc.yaml
   ```

4. Sign out of the Teleport cluster and sign in again to assume the new role.

## Step 2/4. Create a Terraform configuration

Paste the following into a file called `main.tf` to configure the Terraform provider and create two example Login Rules. Make sure to update the `addr = "teleport.example.com:443"` field with the public address of your Teleport Proxy.

```
terraform {
  required_providers {
    teleport = {
      source  = "terraform.releases.teleport.dev/gravitational/teleport"
      version = "~> 18.0"
    }
  }
}

provider "teleport" {
  # Update addr to point to your Teleport proxy
  addr = "teleport.example.com:443"

  # Setting profile_dir and profile_name to empty strings will cause the
  # Terraform provider to authenticate using the current logged-in tsh profile
  profile_dir  = ""
  profile_name = ""
}

resource "teleport_login_rule" "terraform-test-map-rule" {
  metadata = {
    name        = "terraform-test-map-rule"
    description = "Terraform test rule using traits_map"
    labels = {
      example = "yes"
    }
  }
  version = "v1"

  # The rule with the lowest priority will be evaluated first.
  priority = 0

  # traits_map holds a map of all desired trait keys to list of expressions to
  # determine the trait values.
  traits_map = {

    # The "logins" traits will be set to the external "username" trait converted
    # to lowercase, as well as any external "logins" trait.
    "logins" = {

      # The traits_map value must be an object holding the expressions list in a
      # "values" field
      values = [
        "strings.lower(external.username)",
        "external.logins",
      ]
    }

    # The external "groups" trait will be passed through unchanged, all other
    # traits will be filtered out.
    "groups" = {
      values = [
        "external.groups",
      ]
    }
  }
}

resource "teleport_login_rule" "terraform-test-expression-rule" {
  metadata = {
    name        = "terraform-test-expression-rule"
    description = "Terraform test rule using traits_expression"
    labels = {
      example = "yes"
    }
  }
  version = "v1"

  # This rule has a higher priority value, so it will be evaluated after the
  # "terraform-test-map-rule".
  priority = 1

  # traits_expression is an alternative to traits_map, which returns all desired
  # traits in a single expression. The EOT syntax is a way of writing a
  # multiline string in Terraform, it is not part of the expression.
  traits_expression = <<-EOT
    external.put("groups",
      choose(
        option(external.groups.contains("admins"), external.groups.add("app-admins", "db-admins")),
        option(external.groups.contains("ops"), external.groups.add("k8s-admins")),
        option(true, external.groups)))
    EOT
}


```

## Step 3/4. Apply the configuration

Init Terraform and apply the configuration:

```
$ terraform init
$ terraform apply
```

## Step 4/4. Make sure everything worked

Double-check that the new Login Rules are now available in your cluster:

```
$ tctl get login_rules
kind: login_rule
metadata:
  description: Terraform test rule using traits_expression
  id: 1680190764978381000
  labels:
    example: "yes"
  name: terraform-test-expression-rule
spec:
  priority: 1
  traits_expression: |
    external.put("groups",
      choose(
        option(external.groups.contains("admins"),
external.groups.add("app-admins", "db-admins")),
        option(external.groups.contains("ops"),
external.groups.add("k8s-admins")),
        option(true, external.groups)))
version: v1
---
kind: login_rule
metadata:
  description: Terraform test rule using traits_map
  id: 1680193055097268000
  labels:
    example: "yes"
  name: terraform-test-map-rule
spec:
  priority: 0
  traits_map:
    groups:
    - external.groups
    logins:
    - strings.lower(external.username)
    - external.logins
version: v1
```

Test the Login Rules you just installed with the `tctl login_rule test` command. The `--load-from-cluster` flag tells the command to load all Login Rules currently installed in the cluster. You can send example traits to the standard input of the command, and it will print the final traits after transformation by the Login Rules.

```
$ echo '{"groups": ["admins", "ops"], "username": ["Alice"], "logins": ["user", "root"]}' | \
  tctl login_rule test --load-from-cluster
groups:
- admins
- ops
- app-admins
- db-admins
logins:
- alice
- user
- root
```

## Next Steps

- Read the [Terraform Guide](https://goteleport.com/docs/zero-trust-access/infrastructure-as-code/terraform-provider.md) to learn more about configuring the Terraform provider.
- Read the [Login Rules reference](https://goteleport.com/docs/reference/access-controls/login-rules.md) to learn more about the Login Rule expression syntax.
