Configure Cloud Credentials

Su Suriya Ravichandran Updated 10 Nov 2026
5 min read ·Lesson 164 of 200

Who Is Making the Request

Every request to Claude is made on behalf of an identity, and the identity decides what the request is allowed to do and whom the bill is sent to. On the direct API, that identity is an API key. On the cloud platforms, it is the cloud's own identity: an AWS credential, a Google Cloud identity, or a Microsoft Entra ID principal. Configuring credentials means giving the application the right identity, supplying it safely, and making sure that nothing sensitive ends up in code, logs, or version control.

This lesson explains where each platform looks for credentials, why identities attached to the running environment are preferable to stored secrets, how to report on credential configuration without revealing a value, and how to rotate a secret when one is unavoidable. The examples keep secret values out of output, which is the habit the rest of the lesson depends on.


Where Each Platform Looks

Each platform has a standard search order for credentials, and the SDK relies on it rather than inventing its own:

PlatformWhere the credentials come fromTypical use
Direct APIThe ANTHROPIC_API_KEY environment variable, or a value passed to the clientDevelopment, and services with a secret store
Amazon BedrockThe AWS credential chain: environment variables, a named profile, or the role attached to the machineApplications running on AWS
Google Cloud Vertex AIApplication Default Credentials: environment, a gcloud sign-in, or the identity attached to the machineApplications running on Google Cloud
Microsoft FoundryAn API key in ANTHROPIC_FOUNDRY_API_KEY, or a Microsoft Entra ID identityApplications running on Azure

The shared pattern is that the SDK reads the credential from the environment or from the platform's chain, and the application code never contains the value. That separation is the main defense against leaked secrets.


Prefer Identities Over Secrets

A secret is a value that grants access, such as an API key. It can be copied, pasted into a chat, committed to a repository, or left in a log. An identity is a granted permission that the platform attaches to a running machine or a workload, and it has no value the application holds. The identity can be given narrow permissions, and it can be revoked without changing any code.

For applications running on a cloud, the identity is the right choice whenever the platform offers it: an IAM role on AWS, a service account on Google Cloud, or a managed identity on Azure. A deployment that relies on an identity contains nothing to leak. A deployment that relies on a key contains a secret that must be stored, rotated, and protected for its entire life.


Reporting Without Revealing

Teams need to know whether credentials are configured correctly, but a report should never print the value. A safe report states whether each required source is present, and if a value is shown at all, it shows only a fragment that cannot be used to access anything:

"""credential_report.py: report which credentials are configured, without revealing any value."""

REQUIREMENTS = {
    "anthropic": ["ANTHROPIC_API_KEY"],
    "foundry": ["ANTHROPIC_FOUNDRY_API_KEY"],
    "bedrock": [],
    "vertex": [],
}


def redact(value: str) -> str:
    return f"...{value[-4:]}" if len(value) > 8 else "****"


def credential_report(env: dict) -> list[str]:
    lines = []
    for provider, names in REQUIREMENTS.items():
        if not names:
            lines.append(f"{provider}: checked by the cloud's own tools, not by this report")
            continue
        present = [name for name in names if env.get(name)]
        missing = [name for name in names if not env.get(name)]
        if missing and provider == "foundry":
            lines.append(f"{provider}: missing {', '.join(missing)}, or use Entra ID")
        elif missing:
            lines.append(f"{provider}: missing {', '.join(missing)}")
        else:
            value = env[present[0]]
            lines.append(f"{provider}: {present[0]} present (ends with {redact(value)[3:]})")
    return lines


if __name__ == "__main__":
    environment = {"ANTHROPIC_API_KEY": "sk-ant-demo-1234abcd"}
    for line in credential_report(environment):
        print(line)

Output:

anthropic: ANTHROPIC_API_KEY present (ends with abcd)
foundry: missing ANTHROPIC_FOUNDRY_API_KEY, or use Entra ID
bedrock: checked by the cloud's own tools, not by this report
vertex: checked by the cloud's own tools, not by this report

How It Works

  1. The requirements are a table. Each provider lists the variables it needs, and an empty list means the platform's own tools check the identity, which this report does not attempt to reproduce.
  2. redact() keeps only the last four characters, and only for values longer than eight characters. A four-character tail cannot authenticate anything, and it is enough to recognize which key is in use when two are in circulation.
  3. The report never prints the full value. The only part of the secret that appears is the fragment from redact(), which the code slices down to four characters.
  4. Missing variables are reported by name, which is what a person needs to fix the configuration, and the Foundry line names both options, since either is valid.

Keep Secrets Out of Files That Travel

When a secret is unavoidable, its location matters. The environment is the baseline, because the SDK reads it directly. For a local project, a .env file can hold development values, and Lesson 172 covers how to keep that file out of version control. For deployed services, a secret store managed by the platform is better than any file, because the store controls who can read the value and records when it is read.

Two habits protect secrets in every setting. The value should never be printed or logged, which the redaction above demonstrates. And it should be replaced on a schedule, so that a value copied somewhere unexpected stops working after a bounded time.


Rotating a Secret

Rotation replaces a secret with a new one while the application keeps running. The safe procedure creates the new value, deploys it alongside the old one, switches the application to the new value, confirms that requests succeed, and then revokes the old value. Revoking first causes an outage, and never revoking leaves a permanent exposure. The steps are simple, and they are only reliable when the application can read its configuration without a code change, which is another reason the environment is the right place for the value.


Summary

Each platform has its own credential chain, and the SDK reads from it. Identities attached to the running environment are preferable to stored secrets, because they contain nothing to leak and can be revoked without changing code. Where a secret is unavoidable, it belongs in the environment or a secret store, never in code, and reports about it should show presence and a short redacted tail, never the value. Rotation replaces a secret without downtime, and the next lesson turns to the question of which platform to choose in the first place.

0 Comments

Reviewed before they appear

No comments yet.

Anthropic SDK Using Python
Anthropic SDK Intro Claude API Intro SDK Requirements Install Anthropic SDK Upgrade the SDK Create an API Key Set API Keys Use Environment Variables Import Anthropic Create a Client Send Your First Message Choose a Claude Model Set Max Tokens Read a Response Print Response Text Understand Message Blocks Use System Prompts Send User Messages Set Temperature Handle Stop Reasons Messages API Intro Create Messages Use Message Roles Send Conversation History Continue a Conversation Build a Chat Loop Reset Chat History Use Multiple Turns Inspect Message IDs Read Usage Data Write Clear Prompts Set a System Prompt Add Context to Prompts Use Prompt Templates Add Examples to Prompts Request JSON Output Use XML Tags Control Response Length Improve Prompt Quality Avoid Prompt Injection Read Text Blocks Read Content Blocks Check Stop Reasons Count Input Tokens Count Output Tokens Count Tokens Before Sending Limit Output Tokens Use Stop Sequences Read Request IDs Parse API Responses Streaming Intro Stream Text Output Use Stream Events Use Stream Helpers Get Final Messages Stream Async Responses Handle Stream Errors Build a Live Chat Stream Long Responses Close Streams Safely Build a Chatbot Keep Chat History Manage Chat Sessions Add Chat Memory Build a CLI Chatbot Build a Web Chatbot Use Flask with Claude Use FastAPI with Claude Return JSON from an API Add Chat Error Messages Async SDK Intro Create an Async Client Send Async Messages Use asyncio Run Parallel Requests Stream Async Text Handle Async Errors Set Async Timeouts Close Async Clients Choose Sync or Async Tool Use Intro Define a Tool Create Tool Schemas Send Tools to Claude Read Tool Calls Run Python Tools Return Tool Results Continue After Tool Use Control Tool Choice Handle Tool Errors Use the beta_tool Decorator Create a Tool Runner Add Tool Docstrings Validate Tool Inputs Use Multiple Tools Limit Tool Calls Log Tool Activity Build a Weather Tool Build a Search Tool Build a Calculator Tool Structured Output Intro Request JSON Data Validate JSON Output Use Pydantic Models Handle Invalid JSON Extract Fields from Text Generate Typed Data Use Image URLs Send Base64 Images Read PDFs with Claude Use Output Schemas Build Data Extraction Test Structured Responses Send Image Inputs Upload Files Use File IDs Process Text Files Summarize Documents Extract Table Data Handle File Errors Read Cache Usage Reduce Repeated Input Costs Debug Cache Misses Prompt Caching Intro Enable Prompt Caching Cache System Prompts Cache Long Context Test Cache Performance Use Cache Breakpoints Cache Best Practices Message Batches Intro Create a Message Batch Set Batch IDs Check Batch Status List Message Batches Get Batch Results Process Batch Outputs Handle Failed Batch Items Use Batches for Bulk Tasks Compare Batches and Requests Handle API Errors Handle Rate Limits Retry Failed Requests Set Request Timeouts Handle Network Errors Use Exponential Backoff Build Reliable API Calls Use Extended Thinking Log API Errors Track Request IDs Paginate API Results Set Thinking Budgets Read Thinking Blocks Use Tool Search Use Web Search Tools Use Computer Tools Use Citations Use Token Counting Read Raw Responses Set Custom Headers Use Claude on AWS Bedrock Use Claude on Vertex AI Use Claude on Microsoft Foundry Configure Cloud Credentials Choose a Cloud Provider Compare API Integrations Configure Provider Clients Handle Cloud Errors Use Cloud SDK Extras Deploy Cloud Apps Protect API Keys Use a .env File Ignore Secrets in Git Validate User Input Reduce Prompt Injection Limit Tool Permissions Avoid Unsafe Tool Calls Sanitize Tool Results Set Usage Limits Review Security Logs Test SDK Functions Mock API Responses Test Error Handling Test Streaming Code Measure Token Usage Track API Costs Configure Logging Deploy with Docker Deploy a FastAPI App Monitor Production Apps Build a Claude Chatbot Build a Text Summarizer Build a Code Explainer Build a JSON Extractor Build a PDF Assistant Build a Streaming Chat App Build a Tool-Calling Agent Build a Batch Processor Build a Research Assistant Build a Claude API Dashboard
Ask about this post
AI Ask about this post

Ask questions about Configure Cloud Credentials and get answers drawn from it.

Signed-in readers only.