Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/gravitational/teleport/llms.txt

Use this file to discover all available pages before exploring further.

The github.com/gravitational/teleport/api/client package provides an official Go client for the Teleport Auth Service gRPC API. You can use this client to build custom automation — provisioning users, managing roles, listing infrastructure, processing Access Requests, and more — using the same API that tctl, the Terraform provider, and the Kubernetes operator all use. The client automatically handles TLS certificate rotation, retries, and connection multiplexing, so you can focus on your business logic.

Installation

go get github.com/gravitational/teleport/api/client
Pin the client module to the major version of your Teleport cluster to ensure API compatibility. Check the Go module proxy for available versions:
# Find the pseudo-version for a specific Teleport tag
go list -f '{{.Version}}' -m "github.com/gravitational/teleport/api@$(git rev-parse v17.0.0)"

Connecting to a cluster

client.New

New opens a gRPC connection to a Teleport Auth or Proxy Service using the provided configuration and credentials. It tries all combinations of addresses and credentials and returns the first successful connection.
func New(ctx context.Context, cfg Config) (*Client, error)

client.Config fields

FieldTypeDescription
Addrs[]stringAddresses to try: Auth Service (host:3025), Proxy HTTPS (host:443), or Proxy SSH (host:3080).
Credentials[]CredentialsOne or more credential sources (see below).
DialerContextDialerOptional custom dialer for use with reverse tunnels or proxies.
DialInBackgroundboolDon’t block New on connection establishment.
ALPNSNIAuthDialClusterNamestringCluster name for TLS Routing through a Proxy Service.

Authentication / credential sources

The simplest approach for development. Reads credentials from the tsh profile on disk.
import "github.com/gravitational/teleport/api/client"

clt, err := client.New(ctx, client.Config{
    Addrs: []string{"example.teleport.sh:443"},
    Credentials: []client.Credentials{
        client.LoadProfile("", ""),  // uses default profile dir and profile
    },
})
tbot (Machine ID) can output identity files that contain a TLS certificate, private key, and CA chain. Use this for production automation.
clt, err := client.New(ctx, client.Config{
    Addrs: []string{"example.teleport.sh:443"},
    Credentials: []client.Credentials{
        client.LoadIdentityFile("/opt/teleport/identity"),
    },
})
Generate the identity file with tbot or for a one-off:
tctl auth sign --user=api-admin --format=file --out=/opt/teleport/identity --ttl=8760h
For advanced scenarios where you manage your own certificate rotation:
import (
    "crypto/tls"
    "github.com/gravitational/teleport/api/client"
)

tlsCfg := &tls.Config{
    Certificates: []tls.Certificate{cert},
    RootCAs:      certPool,
}

clt, err := client.New(ctx, client.Config{
    Addrs: []string{"example.teleport.sh:443"},
    Credentials: []client.Credentials{
        client.LoadTLS(tlsCfg),
    },
})

Key client methods

All methods accept a context.Context as their first argument. Pass a context with a timeout or cancellation signal to avoid blocking indefinitely.

Node management

GetNodes

Returns all SSH nodes registered in a namespace. Use defaults.Namespace ("default") for the standard namespace.
func (c *Client) GetNodes(ctx context.Context, namespace string) ([]types.Server, error)
import "github.com/gravitational/teleport/api/defaults"

nodes, err := clt.GetNodes(ctx, defaults.Namespace)
if err != nil {
    return err
}
for _, node := range nodes {
    fmt.Printf("Node: %s  Hostname: %s  Labels: %v\n",
        node.GetName(), node.GetHostname(), node.GetStaticLabels())
}

Role management

GetRoles

Returns all roles in the cluster.
func (c *Client) GetRoles(ctx context.Context) ([]types.Role, error)

CreateRole

Creates a new role. Returns an error if the role already exists.
func (c *Client) CreateRole(ctx context.Context, role types.Role) (types.Role, error)

UpsertRole

Creates a role or replaces an existing role with the same name.
func (c *Client) UpsertRole(ctx context.Context, role types.Role) (types.Role, error)

DeleteRole

Deletes a role by name.
func (c *Client) DeleteRole(ctx context.Context, name string) error
// Create a role programmatically
role, err := types.NewRole("api-developer", types.RoleSpecV6{
    Allow: types.RoleConditions{
        Logins:     []string{"ubuntu", "{{internal.logins}}"},
        NodeLabels: types.Labels{"env": {"staging"}},
    },
    Options: types.RoleOptions{
        MaxSessionTTL: types.Duration(8 * time.Hour),
    },
})
if err != nil {
    return err
}
created, err := clt.CreateRole(ctx, role)

User management

GetUsers

Returns all local users. Pass withSecrets = false for read-only access; true also returns password hashes (requires elevated permissions).
func (c *Client) GetUsers(ctx context.Context, withSecrets bool) ([]types.User, error)

CreateUser

Creates a new local user.
func (c *Client) CreateUser(ctx context.Context, user types.User) (types.User, error)

DeleteUser

Deletes a user by username.
func (c *Client) DeleteUser(ctx context.Context, user string) error
// Create a user with roles and traits
user, err := types.NewUser("alice@example.com")
if err != nil {
    return err
}
user.SetRoles([]string{"developer", "access"})
user.SetTraits(wrappers.Traits{
    "logins": {"alice", "ubuntu"},
    "kubernetes_users": {"alice"},
})

created, err := clt.CreateUser(ctx, user)

Token management

CreateToken

Creates a new provisioning (join) token.
func (c *Client) CreateToken(ctx context.Context, token types.ProvisionToken) error

GetTokens

Returns all provisioning tokens.
func (c *Client) GetTokens(ctx context.Context) ([]types.ProvisionToken, error)
token, err := types.NewProvisionTokenFromSpec("my-join-token", time.Now().Add(24*time.Hour), types.ProvisionTokenSpecV2{
    Roles: []types.SystemRole{types.RoleNode, types.RoleApp},
})
if err != nil {
    return err
}
err = clt.CreateToken(ctx, token)

Database, Kubernetes, and Application servers

GetDatabaseServers

Returns all database server instances (not the database resources themselves).
func (c *Client) GetDatabaseServers(ctx context.Context, namespace string) ([]types.DatabaseServer, error)

GetKubernetesServers

Returns all Kubernetes Service instances.
func (c *Client) GetKubernetesServers(ctx context.Context) ([]types.KubeServer, error)

GetApplicationServers

Returns all Application Service instances.
func (c *Client) GetApplicationServers(ctx context.Context, namespace string) ([]types.AppServer, error)

GetApps

Returns all Application resources (the registered apps, not the service instances).
func (c *Client) GetApps(ctx context.Context) ([]types.Application, error)

Access Requests

SubmitAccessReview

Approves or denies an Access Request, optionally adding a review note.
func (c *Client) SubmitAccessReview(ctx context.Context, params types.AccessReviewSubmission) (types.AccessRequest, error)
reviewed, err := clt.SubmitAccessReview(ctx, types.AccessReviewSubmission{
    RequestID: "66b827b2-1b0b-512b-965d-6c789388d3c9",
    Review: types.AccessReview{
        ProposedState: types.RequestState_APPROVED,
        Reason:        "Approved for production incident response",
        Author:        "on-call@example.com",
    },
})

Complete example: connect and list nodes

The following program connects to a Teleport cluster using the current tsh profile, lists all SSH nodes, and prints their names and labels.
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/gravitational/teleport/api/client"
	"github.com/gravitational/teleport/api/defaults"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// Connect using the current tsh login profile.
	// For production, replace with client.LoadIdentityFile("/path/to/identity").
	clt, err := client.New(ctx, client.Config{
		Addrs: []string{
			// Teleport Cloud customers use <tenant>.teleport.sh:443
			"example.teleport.sh:443",
			"example.teleport.sh:3025", // direct Auth Service (self-hosted)
		},
		Credentials: []client.Credentials{
			client.LoadProfile("", ""),
		},
	})
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	defer clt.Close()

	// Verify connectivity
	ping, err := clt.Ping(ctx)
	if err != nil {
		log.Fatalf("failed to ping: %v", err)
	}
	fmt.Printf("Connected to cluster %q (server version %s)\n",
		ping.ClusterName, ping.ServerVersion)

	// List all SSH nodes in the default namespace
	nodes, err := clt.GetNodes(ctx, defaults.Namespace)
	if err != nil {
		log.Fatalf("failed to list nodes: %v", err)
	}

	fmt.Printf("\nFound %d node(s):\n", len(nodes))
	for _, node := range nodes {
		fmt.Printf("  %-40s  hostname=%-30s  labels=%v\n",
			node.GetName(),
			node.GetHostname(),
			node.GetStaticLabels(),
		)
	}

	// List all roles
	roles, err := clt.GetRoles(ctx)
	if err != nil {
		log.Fatalf("failed to list roles: %v", err)
	}
	fmt.Printf("\nFound %d role(s):\n", len(roles))
	for _, role := range roles {
		fmt.Printf("  %s\n", role.GetName())
	}
}
Run it:
# Log in first so a tsh profile exists
tsh login --proxy=example.teleport.sh --user=api-admin

# Run the program
go run main.go

Authentication patterns

tsh Profile (development)

Call client.LoadProfile("", "") after tsh login. The profile is read from ~/.tsh/ automatically. TTL is capped by the cluster’s max_session_ttl setting.

Identity File (production)

Use tbot to continuously renew an identity file and load it with client.LoadIdentityFile("/path"). Certificates can be as short as 1 minute for zero-standing-privilege automation.

TLS Config (advanced)

Build a crypto/tls.Config manually and pass it to client.LoadTLS(tlsCfg). Useful when certificates are managed by an external PKI or rotated by a sidecar.

Environment Variables

TELEPORT_IDENTITY_FILE, TELEPORT_IDENTITY_FILE_NO_CREDENTIALS, and TELEPORT_AUTH_SERVER are read automatically by client.LoadProfile when set. Useful for containerised workloads.
Never hardcode certificates or private keys in source code or commit them to VCS. Use tbot with short-lived credentials and a secure secrets manager or environment variable injection for any automated workflow.

Further reading

Build docs developers (and LLMs) love