Use API Key credentials stored in a Kubernetes Secret by configuring a CredentialProvider

Updated at:

A CredentialProvider is a CustomResourceDefinition that lets the platform centrally manage the API Keys held in Kubernetes Secrets. The platform delivers credentials on demand to AI Agent workloads based on their Agent identities, so applications do not need to embed plaintext API Keys in code or images.

Feature introduction

In AI Agent scenarios, Agents often need API Keys to call third-party services, such as the OpenAI and Qwen large language model services. Storing actual API Keys directly in application code, images, or environment variables creates risks of credential exposure and makes rotation difficult.

CredentialProvider is a credential source CustomResourceDefinition (CRD) provided by the ack-agent-identity add-on. When its type is APIKey and its source is Kubernetes, it reads a single field from a Kubernetes Secret in the cluster as an API Key. It also provides the following capabilities:

  • Stores actual API Keys only in Kubernetes Secrets in the cluster, where the platform centrally manages and rotates them.

  • Controls, at the CredentialProvider level, which credentials each Agent identity can retrieve through the AgentRole and AgentRoleBinding authorization mechanism.

  • Supports template variables in secretRef.name, so one configuration dynamically references different Secrets according to context, such as the Agent identity, and retrieves different credentials for different identities.

CredentialProvider supports types such as RAM (Resource Access Management) in addition to APIKey, and sources such as Key Management Service (KMS) and RAM Roles for Service Accounts (RRSA). This topic covers only type: APIKey with a Kubernetes Secret source.

Resource objects

Configuring API Key credential delivery typically involves the following custom resources, which you create in sequence in the steps below:

Resource object

Description

AgentIdentity

Defines an Agent identity and serves as the subject for authorization and credential delivery.

CredentialProvider

Defines a credential source. In this topic, type is APIKey, which reads an API Key from a Kubernetes Secret.

AgentRole

Defines permission rules that declare which CredentialProvider credentials can be retrieved.

AgentRoleBinding

Binds an AgentRole to a specified AgentIdentity to complete authorization.

Applicability

  • The cluster Kubernetes version is 1.28 or later.

  • The ack-agent-identity add-on version is 0.2.0 or later, which you can confirm on the cluster Component Management page.

Configure an API Key credential

Perform the following operations by using kubectl. Before you begin, make sure that you have configured a kubeconfig that can access the target Container Compute Service (ACS) cluster. For more information, see Use ACS with kubectl.

Create the following resources in the same namespace: The Secret referenced by the CredentialProvider must be in the same namespace as the CredentialProvider. Cross-namespace references are not supported.

  1. Save the following content as llm-api-key-secret.yaml, and run kubectl apply -f llm-api-key-secret.yaml to create a Kubernetes Secret that stores the API Key.

    apiVersion: v1
    kind: Secret
    metadata:
      name: llm-api-key
      namespace: <YOUR_NAMESPACE>
    type: Opaque
    stringData:
      apiKey: "sk-xxxxxxxxxxxxxxxx"   # Replace with the actual API Key
  2. Save the following content as agent-identity.yaml, and run kubectl apply -f agent-identity.yaml to create an AgentIdentity that defines the Agent identity.

    apiVersion: agentidentity.alibabacloud.com/v1alpha1
    kind: AgentIdentity
    metadata:
      name: my-agent          # Agent identity name referenced in subsequent authorization
      namespace: <YOUR_NAMESPACE>
    spec:
      description: "Sample AI Agent identity"
  3. Save the following content as credential-provider-apikey.yaml, and run kubectl apply -f credential-provider-apikey.yaml to create a CredentialProvider that references the preceding Secret.

    apiVersion: agentidentity.alibabacloud.com/v1alpha1
    kind: CredentialProvider
    metadata:
      name: llm-api-key
      namespace: <YOUR_NAMESPACE>
    spec:
      type: APIKey
      apiKey:
        source:
          provider: Kubernetes
          kubernetes:
            secretRef:
              name: llm-api-key       # Secret name created in step 1
            keyName: apiKey           # Field in the Secret that contains the API Key
    secretRef.name supports template variables that dynamically reference different Secrets according to context using template variables.
  4. Save the following content as agent-role-apikey.yaml, and run kubectl apply -f agent-role-apikey.yaml to create an AgentRole and AgentRoleBinding that authorize the Agent identity to retrieve credentials from the CredentialProvider.

    apiVersion: agentidentity.alibabacloud.com/v1alpha1
    kind: AgentRole
    metadata:
      name: get-llm-key
      namespace: <YOUR_NAMESPACE>
    spec:
      rules:
      - effect: Allow
        action: "GetResourceCredential"
        resource: "CredentialProvider/llm-api-key"   # CredentialProvider name created in the preceding step
    ---
    apiVersion: agentidentity.alibabacloud.com/v1alpha1
    kind: AgentRoleBinding
    metadata:
      name: my-agent-get-llm-key
      namespace: <YOUR_NAMESPACE>
    spec:
      agentRoleRef:
        apiGroup: agentidentity.alibabacloud.com
        kind: AgentRole
        name: get-llm-key
      subjects:
      - authorizationType: "Agent"
        agentAuthorizationConfiguration:
          agentName: my-agent                        # Must match the AgentIdentity name
  5. Confirm that the CredentialProvider is ready (Available is True).

    kubectl get credentialprovider llm-api-key -n <YOUR_NAMESPACE>

    Expected output:

    NAME          AVAILABLE   AGE
    llm-api-key   True        30s

    If Available is not True, use kubectl describe to view the cause in Conditions. For troubleshooting, see Status and troubleshooting.

Consume credentials

Created and authorized API Key credentials are typically consumed through egress traffic credential injection in Agent Sandbox. Reference this CredentialProvider in the tokenTransformation rule of a SecurityProfile. The Sandbox application sends requests with a placeholder token. The egress gateway replaces the placeholder with the actual API Key when it forwards the request. For the complete end-to-end configuration, including SecurityProfile, SandboxSet, SandboxClaim, and verification, see Configure credential injection for Agent Sandbox egress traffic.

Template variables in secretRef.name

In addition to a fixed Secret name, secretRef.name can include ${ack:agent-identity/...} template variables. When retrieving credentials, the system renders the actual Secret name according to the identity context of the current request, so it can provide different credentials for different identities. For example, llm-api-key-${ack:agent-identity/agent-name} resolves to llm-api-key-my-agent according to the Agent name.

The following template variables are supported:

Template variable

Description

${ack:agent-identity/agent-name}

The name of the AgentIdentity associated with the current Agent identity.

${ack:agent-identity/metadata/<key>}

The value of the specified key in custom metadata written when the identity token is issued. Replace <key> with the actual key name.

If a template variable cannot be resolved in the current request context, the credential retrieval request fails with an explicit error message instead of silently returning an empty value. For example, resolution fails when the referenced metadata key does not exist.

The following example shows how to dynamically reference different Secrets by tenant. API Keys for different tenants are stored in Secrets named llm-api-key-<tenant identifier>. When retrieving credentials, the CredentialProvider resolves the corresponding Secret name through ${ack:agent-identity/metadata/tenant-id}.

The metadata value comes from custom metadata written when the identity token is issued. Annotation values can be passed in Agent Sandbox scenarios through the SandboxClaim annotation security.agents.kruise.io/<key>. The part after the prefix is the metadata key:

apiVersion: agents.kruise.io/v1alpha1
kind: SandboxClaim
metadata:
  name: my-claim
  namespace: <YOUR_NAMESPACE>
spec:
  templateName: my-sandbox-set
  replicas: 1
  annotations:
    # After removing the prefix, the following value can be referenced in the template through ${ack:agent-identity/metadata/tenant-id}
    security.agents.kruise.io/tenant-id: acme
    security.agents.kruise.io/agent-name: my-agent

The corresponding CredentialProvider is as follows:

apiVersion: agentidentity.alibabacloud.com/v1alpha1
kind: CredentialProvider
metadata:
  name: llm-api-key
  namespace: <YOUR_NAMESPACE>
spec:
  type: APIKey
  apiKey:
    source:
      provider: Kubernetes
      kubernetes:
        secretRef:
          name: 'llm-api-key-${ack:agent-identity/metadata/tenant-id}'   # Resolves to llm-api-key-acme
        keyName: apiKey

With this configuration, when tenant-id in the request identity metadata is acme, secretRef.name resolves to llm-api-key-acme and reads the Secret dedicated to that tenant.

Field descriptions

The spec structure for type: APIKey with a Kubernetes source is as follows:

spec:
  type: APIKey                     # Required credential type. Cannot be changed after creation
  apiKey:
    source:
      provider: Kubernetes         # Required credential source
      kubernetes:
        secretRef:
          name: <secret-name>      # Required Secret name in the same namespace. Supports template variables
        keyName: <key>             # Required field name in Secret data

Key fields are described as follows:

Field

Required

Description

spec.type

Yes

Credential type. In this topic, use APIKey. This value cannot be changed after creation; validation rejects changes.

spec.apiKey.source.provider

Yes

Credential source. In this topic, use Kubernetes. If KMS is enabled in the cluster, you can also use KMS, which this topic does not cover.

spec.apiKey.source.kubernetes.secretRef.name

Yes

Name of the referenced Kubernetes Secret. It must be in the same namespace as the CredentialProvider. Supports template variables.

spec.apiKey.source.kubernetes.keyName

Yes

Specifies which field in Secret data to read as the API Key. Required for the APIKey type.

Status and troubleshooting

The running status of a CredentialProvider is recorded in status.conditions. Run kubectl describe credentialprovider <name> -n <YOUR_NAMESPACE> to view it. Common Conditions and Reasons are as follows:

Condition / Reason

Description

Available=True

Configuration validation passes and the credential source can be resolved.

Degraded, Reason=SecretNotFound

The Secret referenced by secretRef.name does not exist. Check that the Secret name and namespace are correct.

Degraded, Reason=SecretKeyMissing

The Secret exists but does not contain the field specified by keyName.

When secretRef.name uses template variables, the actual Secret name can be determined only when credentials are retrieved. Therefore, the reconciliation phase skips the Secret existence check and directly marks the CredentialProvider as Available. Errors in this configuration, such as a rendered Secret that does not exist, appear only when credentials are retrieved. They do not appear in the CredentialProvider status.

Limits

Limit

Description

Secret and CredentialProvider in the same namespace

secretRef supports only Secrets in the same namespace and does not support cross-namespace references.

Single-field reading

The APIKey type reads only the single field specified by keyName. keyName is required.

FAQ

Why is a CredentialProvider's Available status not True?

Troubleshoot the issue as follows:

  1. Run kubectl describe credentialprovider <name> -n <YOUR_NAMESPACE> and view the Reason in Conditions.

  2. If the Reason is SecretNotFound, confirm that secretRef.name matches the actual Secret name and that the Secret and CredentialProvider are in the same namespace.

  3. If the Reason is SecretKeyMissing, confirm that keyName matches the field name in Secret data. Run kubectl get secret <name> -n <YOUR_NAMESPACE> -o jsonpath='{.data}' to view the fields.

Why is the Agent denied (no permission) when retrieving credentials?

Confirm that you have created an AgentRole with action: GetResourceCredential and resource: CredentialProvider/<name>, as well as an AgentRoleBinding. Also confirm that the AgentRoleBinding agentName matches the target AgentIdentity name and that all three resources are in the same namespace.

Related documentation