Coding question on keyless AWS access from .NET 10: AWSSDK.Extensions.NETCore.Setup and the default credential chain, ECS task roles versus execution roles, local development with IAM Identity Center profiles, Secrets Manager with caching and rotation, and structured logs to CloudWatch Logs.
The app never holds keys. I register clients with AddDefaultAWSOptions and AddAWSService<IAmazonSecretsManager>(), and the SDK's default credential chain finds credentials: on ECS from the task role through the container credentials endpoint, on Lambda from the execution role, and on a laptop from an IAM Identity Center profile after aws sso login.
The task role gets a least-privilege policy, such as secretsmanager:GetSecretValue on one secret ARN.
For Secrets Manager I read the secret through a cache with a TTL, so rotation is picked up without a restart. Values injected into environment variables at task start go stale after rotation.
For logs, I write structured JSON to stdout and let the awslogs driver (or Lambda) ship it to CloudWatch Logs.
The trade-off: a cache adds staleness, but per-request secret calls add latency, cost and throttling.
"The rule is the same as managed identity on Azure: no long-lived keys anywhere. In
Program.csI callAddDefaultAWSOptionswith the region from configuration and register clients withAddAWSService<IAmazonSecretsManager>()fromAWSSDK.Extensions.NETCore.Setup. Those clients are thread-safe singletons. I never pass credentials in. The SDK walks its default credential chain: environment variables, then the shared config file and SSO profiles, then the ECS container credentials endpoint or the EC2 instance metadata service. In ECS that means the task role. In Lambda it's the execution role, exposed as environment variables. On my laptop it's my IAM Identity Center profile afteraws sso login, so I get short-lived credentials there too.The task role's policy is narrow:
secretsmanager:GetSecretValueon the one secret's ARN,s3:GetObjecton one bucket prefix, andkms:Decryptonly if the secret uses a customer-managed key. I keep that separate from the execution role, which ECS uses to pull from ECR, write logs and inject secrets declared in the task definition.For the database password I use Secrets Manager with automatic rotation. You can inject a secret into an environment variable through the task definition, but that value is read once when the task starts, so after rotation the app has an old password until the tasks are replaced. So I read it through a cache with a TTL, for example
SecretsManagerCache, and refresh on a login failure. For logs, I don't call CloudWatch from the request path. I write structured JSON to stdout with the console formatter, and theawslogslog driver ships it to a log group, so I can query it with Logs Insights. The mistake I see is someone creating an IAM user to 'get it working locally', and that key ending up in a repo. Identity comes from the platform, never from configuration."
| Where the code runs | Credential source | Configured by |
|---|---|---|
| ECS on Fargate or EC2 | Task role via the container credentials endpoint (AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) |
taskRoleArn in the task definition |
| Lambda | Execution role, injected as temporary env vars | Function's role |
| EC2 | Instance profile via IMDSv2 | Instance profile |
| EKS | EKS Pod Identity or IRSA (web identity token) | Pod Identity association or service account annotation |
| Developer laptop | IAM Identity Center (SSO) profile | aws configure sso, AWS_PROFILE |
| GitHub Actions | OIDC federation to a role | aws-actions/configure-aws-credentials |
| Role | Used by | Typical permissions |
|---|---|---|
| Task role | Your .NET code through the SDK | Secrets Manager, S3, SQS, DynamoDB on specific ARNs |
| Execution role | The ECS agent | ecr:GetAuthorizationToken, pull image, logs:CreateLogStream and logs:PutLogEvents, read task-definition secrets |
| Approach | Rotation-aware | Notes |
|---|---|---|
Task-definition secrets to env var |
No, until task restart | Simple; fine for secrets that rarely rotate |
SecretsManagerCache (AWSSDK.SecretsManager.Caching) |
Yes, after TTL | Good for connection strings |
| Configuration provider with reload (Systems Manager / Secrets Manager provider) | Yes, on reload interval | Integrates with IOptionsMonitor |
Call GetSecretValue per request |
Yes | Latency, cost, throttling; avoid |
An API on ECS read the RDS password from an injected env var. When 30-day rotation ran, [12] tasks kept the old password and failed logins until a forced redeploy, a [9-minute] partial outage. Switching to a 5-minute cached secret with a refresh on SQL login error 18456 made the next rotation invisible to users.
Checks whether the candidate can wire AWS access in .NET with no stored keys, least-privilege roles, rotation that works, and sensible logging.
Green flags
Red flags
secretsmanager:* or * on all resourcesAWS SDK for .NET client created without explicit credentials
└─ FallbackCredentialsFactory tries, in order:
1. Environment variables (AWS_ACCESS_KEY_ID / SECRET / SESSION_TOKEN) ← Lambda sets these
2. Shared config and credentials files (profile, SSO, assume-role) ← laptops
3. Web identity token (EKS IRSA, other OIDC) ← EKS
4. ECS container credentials endpoint ← ECS / Pod Identity
5. EC2 instance metadata (IMDSv2) ← EC2
Whichever source wins, the SDK receives temporary credentials from STS and refreshes them before expiry. This is the AWS counterpart of DefaultAzureCredential. Because step 1 wins first, a stray AWS_ACCESS_KEY_ID in a container's environment silently overrides the task role, which is a common cause of "wrong account" errors.
AddDefaultAWSOptions(builder.Configuration.GetAWSOptions()) reads the AWS section (region, profile for local use). AddAWSService<T>() registers each client as a singleton. SDK clients are thread-safe and hold an HTTP connection pool, so one per service per process is correct; creating them per request wastes sockets and time.
Grant actions on specific ARNs, and use conditions where useful:
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:ap-southeast-2:111122223333:secret:orders/db-*" },
{ "Effect": "Allow", "Action": "s3:GetObject",
"Resource": "arn:aws:s3:::orders-documents/invoices/*" }
]
}
The -* suffix matters because Secrets Manager appends six random characters to secret ARNs. If the secret is encrypted with a customer-managed KMS key, the role also needs kms:Decrypt on that key; with the AWS-managed key it does not.
Rotation in Secrets Manager runs a Lambda that creates a new version (AWSPENDING), sets it in the database, tests it and moves the AWSCURRENT label. For RDS, managed rotation with the alternating-users strategy keeps the old credentials valid for a while, which gives caches time to refresh. Your app should:
In ECS the awslogs driver (or FireLens with Fluent Bit) reads the container's stdout and writes to a log group. In Lambda, stdout and ILambdaContext.Logger go to the function's log group automatically. Writing JSON lines lets CloudWatch Logs Insights query fields:
fields @timestamp, Level, Message, TraceId
| filter Level = "Error"
| sort @timestamp desc
In-process providers such as AWS.Logger.AspNetCore also work and are useful on EC2 without an agent, but they add network calls and buffering inside your process. For traces and metrics, the AWS Distro for OpenTelemetry collector runs as a sidecar.
Keep secrets and log groups in ap-southeast-2 or ap-southeast-4, set log retention (logs default to never expire), and don't log personal information. Under the Privacy Act's APP 11 you must protect personal information you hold, which includes logs. Set retention to what you actually need and restrict who can read the log groups.
aws configure sso, then aws sts get-caller-identity --profile dev and run the API locally with AWS_PROFILE=dev.GetSecretValue and read the AccessDeniedException message and the CloudTrail event.aws secretsmanager rotate-secret and watch your cached client pick up the new version after the TTL.Level and TraceId.A .NET 10 API that uses only platform credentials, a cached Secrets Manager read with refresh on failure, and JSON console logs for CloudWatch.
// Program.cs
using Amazon.SecretsManager;
using Amazon.SecretsManager.Extensions.Caching;
using Orders;
var builder = WebApplication.CreateBuilder(args);
// JSON to stdout; the awslogs driver (ECS) or Lambda ships it to CloudWatch Logs.
builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole(o => o.IncludeScopes = true);
// Region from the "AWS" config section. No credentials: the default chain uses the task role.
builder.Services.AddDefaultAWSOptions(builder.Configuration.GetAWSOptions());
builder.Services.AddAWSService<IAmazonSecretsManager>();
builder.Services.AddSingleton(sp => new SecretsManagerCache(
sp.GetRequiredService<IAmazonSecretsManager>(),
new SecretCacheConfiguration { CacheItemTTL = 300_000 })); // 5 minutes, so rotation is picked up
builder.Services.AddSingleton<DbConnectionFactory>();
var app = builder.Build();
app.MapGet("/orders/{id:int}/total", async (int id, DbConnectionFactory db, CancellationToken ct) =>
Results.Ok(await db.QueryTotalAsync(id, ct)));
app.Run();
// DbConnectionFactory.cs: reads the rotated RDS secret through the cache and retries once on login failure.
using System.Text.Json;
using Amazon.SecretsManager.Extensions.Caching;
using Microsoft.Data.SqlClient;
namespace Orders;
public sealed record DbSecret(string Username, string Password, string Host, int Port, string DbName);
public sealed class DbConnectionFactory(SecretsManagerCache cache, IConfiguration config, ILogger<DbConnectionFactory> log)
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private readonly string _secretId = config["Database:SecretId"]!; // name or ARN, not the value
public async Task<decimal> QueryTotalAsync(int orderId, CancellationToken ct)
{
try
{
return await RunAsync(orderId, ct);
}
catch (SqlException ex) when (ex.Number == 18456) // login failed: password probably rotated
{
log.LogWarning("SQL login failed; refreshing secret {SecretId}", _secretId); // never log the value
await cache.RefreshNowAsync(_secretId);
return await RunAsync(orderId, ct);
}
}
private async Task<decimal> RunAsync(int orderId, CancellationToken ct)
{
var secret = JsonSerializer.Deserialize<DbSecret>(await cache.GetSecretString(_secretId), Json)!;
var csb = new SqlConnectionStringBuilder
{
DataSource = $"{secret.Host},{secret.Port}",
InitialCatalog = secret.DbName,
UserID = secret.Username,
Password = secret.Password,
Encrypt = true
};
await using var conn = new SqlConnection(csb.ConnectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("SELECT Total FROM dbo.Orders WHERE Id = @id", conn);
cmd.Parameters.AddWithValue("@id", orderId);
return (decimal)(await cmd.ExecuteScalarAsync(ct) ?? 0m);
}
}
// ECS task definition (excerpt): two roles, logs to CloudWatch, no keys.
{
"family": "orders-api",
"taskRoleArn": "arn:aws:iam::111122223333:role/orders-api-task",
"executionRoleArn": "arn:aws:iam::111122223333:role/orders-api-execution",
"containerDefinitions": [{
"name": "api",
"image": "111122223333.dkr.ecr.ap-southeast-2.amazonaws.com/orders-api:1.4.2",
"environment": [
{ "name": "AWS__Region", "value": "ap-southeast-2" },
{ "name": "Database__SecretId", "value": "orders/db" }
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/orders-api",
"awslogs-region": "ap-southeast-2",
"awslogs-stream-prefix": "api"
}
}
}]
}
# Local development: short-lived SSO credentials, same code path.
aws configure sso --profile orders-dev
aws sso login --profile orders-dev
AWS_PROFILE=orders-dev dotnet run --project src/Orders.Api
appsettings.Development.json or a CI variable. Why it is wrong: The keys never expire, and they leak through more than source control: container images, docker inspect, exception messages, debug logs, CI logs and screenshots. A leaked key works from anywhere until someone revokes it. Instead: Use IAM Identity Center profiles locally, task or execution roles in AWS, and OIDC federation in CI.AccessDenied (or, the other way round, the agent can't pull the image). Instead: Put app permissions on taskRoleArn and pull, log and injected-secret permissions on executionRoleArn.GetSecretValue on every request. Why it is wrong: It adds latency, costs per call and can hit API throttling under load. Instead: Cache it for a few minutes.AddAWSService<T>().AWS_ACCESS_KEY_ID in the container environment. Why it is wrong: Environment credentials come first in the chain and silently override the task role. Instead: Remove them and check with sts:GetCallerIdentity at start-up in non-production.The senior point is that keyless access is a property of the platform setup, not of the code. The code is just AddAWSService<T>() with no credentials. The real work is the role design (task vs execution role, narrow ARNs, KMS only when needed), local development through Identity Center rather than IAM users, and rotation that the running app survives. On Azure I'd say the same about managed identity and DefaultAzureCredential, which makes the skill portable.
Role design is also a governance decision. One role per workload means every CloudTrail event names the service that made the call, which is what auditors and incident responders need, and it limits the blast radius if one service is compromised. In a larger organisation, roles and policies are defined in infrastructure as code and reviewed in pull requests, permission boundaries and Service Control Policies cap what any team can grant, and IAM Access Analyzer flags unused permissions to remove. That maps directly to the Essential Eight's 'restrict administrative privileges' and to APRA CPS 234 or IRAP evidence.
To measure it, I'd alarm on CloudTrail AccessDenied events for the role, watch Secrets Manager API call volume (a spike means the cache isn't working), and run a rotation in staging as part of the release checklist.
| Secret delivery | When it fits | Cost | When not to |
|---|---|---|---|
| Task-definition secret to env var | Rarely rotated values, simple apps | Free, read once | Automatic rotation on short cycles |
| SDK cache with TTL | Rotated DB credentials | A few API calls per TTL per task | Ultra-low-latency cold paths (pre-warm it) |
| Config provider with reload | Many settings, IOptionsMonitor consumers |
Reload interval calls | When you need refresh on failure |
| Parameter Store SecureString | Plain config with few secrets | Cheaper than Secrets Manager | You need managed rotation |
| Role design | When it fits | Cost | When not to |
|---|---|---|---|
| One role per workload | Default | More roles to manage (use IaC) | Never skip it for production |
| Shared role for a team's services | Throwaway sandboxes | Blurred audit trail, large blast radius | Anything holding personal information |
Managed identity gives the app an Entra ID identity that Azure manages, so there is no secret to store or rotate. In code, Azure.Identity gets tokens: DefaultAzureCredential tries managed identity in Azure and the developer's az login or Visual Studio sign-in locally. Then:
AddAzureKeyVault.BlobServiceClient with the credential.CREATE USER [app-name] FROM EXTERNAL PROVIDER, add it to database roles, and use Authentication=Active Directory Default in the connection string.Use a user-assigned identity when several apps share access or it must survive redeploys. The trade-off is setup effort in RBAC and SQL users in exchange for no secrets at all.
A secret is anything that grants access or proves identity: database passwords, API keys and tokens, client secrets, JWT signing keys, SAS tokens. The best secret is no secret at all: in Azure I use managed identity so the app authenticates to Azure SQL, Storage and Service Bus with Entra tokens, not stored credentials. What must remain a secret, typically a third-party API key that doesn't support Entra, goes in Azure Key Vault, read through the AddAzureKeyVault configuration provider using the app's managed identity, with Key Vault RBAC per app and a vault per environment. Locally, developers use dotnet user-secrets or their own Entra sign-in against a dev vault. Nothing goes in appsettings.json or the repo, and secret scanning blocks pushes. The trade-off: Entra and Key Vault become runtime dependencies with network hops and throttling limits, so you load at start-up, cache and reload on an interval, and automate rotation rather than doing it by hand.
Least privilege means every identity gets only the permissions it needs, at the smallest scope, for the shortest time. For a .NET service in Azure I give each workload its own managed identity and assign data-plane roles at resource scope: Storage Blob Data Reader on one container, Key Vault Secrets User on one vault, never Contributor on the subscription. In Azure SQL the app is a contained user with read/write or object-level grants, not db_owner; migrations run under a separate identity in the pipeline. Humans have no standing admin rights: they elevate through Entra PIM, time-bound and audited. That maps to the Essential Eight's restrict administrative privileges strategy. The trade-off is operational friction: narrow scopes mean more role assignments and more "access denied" during development, so you codify them in Bicep or Terraform rather than clicking in the portal.
How to tell it (STAR)
**S:** Our orders API on ECS had a partial outage the first time automatic password rotation ran on the RDS database, [about 35%] of requests failing. **T:** I was on call and had to restore service, then make rotation safe. **A:** I matched the error start to the rotation in CloudTrail and saw only tasks started before rotation were failing, because the password was injected as an env var at start-up. I forced a new deployment to recover, then changed the app to read the secret through a five-minute cache that refreshes on a login failure, and moved rotation to alternating users so old credentials overlap with the cache window. We also added a rotation test to staging releases. **R:** Recovery took [9] minutes, and the next [n] rotations went through with zero errors.
Last updated 23 Nov 2026.