📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how a .NET 10 API on AWS uses the AWS SDK for .NET without any access keys. How do IAM roles and the default credential chain work in ECS, Lambda and on a developer's laptop, how do you read secrets from Secrets Manager (and keep up with rotation), and how do your logs end up in CloudWatch?

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.

Mid-Level Coding Intermediate aws aws-sdk cloudwatch devops iam secrets-manager

🎯 Key points

  • AddDefaultAWSOptions plus AddAWSService<T>() register one thread-safe singleton client per service, reusing its HTTP connection pool instead of opening sockets per request
  • Default credential chain: env vars, shared profile / SSO, web identity, then container (ECS) or instance metadata credentials (enforce IMDSv2 on EC2)
  • ECS task role is what the app uses; the execution role only pulls the image, writes logs and injects task-definition secrets
  • Least-privilege policy: secretsmanager:GetSecretValue on one secret ARN, kms:Decrypt only if a customer-managed key is used
  • Local dev: aws sso login with an IAM Identity Center profile and AWS_PROFILE, never IAM user access keys
  • Secrets: cache with a TTL (SecretsManagerCache or a configuration provider with reload) so rotation is picked up without restarts
  • Logs: structured JSON to stdout with the awslogs driver (or Lambda's built-in log capture); no AWS calls in the request path
  • One role per workload gives CloudTrail an audit trail per service; never log secret values; alarm on AccessDenied

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The rule is the same as managed identity on Azure: no long-lived keys anywhere. In Program.cs I call AddDefaultAWSOptions with the region from configuration and register clients with AddAWSService<IAmazonSecretsManager>() from AWSSDK.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 after aws sso login, so I get short-lived credentials there too.

The task role's policy is narrow: secretsmanager:GetSecretValue on the one secret's ARN, s3:GetObject on one bucket prefix, and kms:Decrypt only 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 the awslogs log 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 credentials come from

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

Task role vs execution role (ECS)

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

Reading secrets: options

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains the default credential chain and where ECS, Lambda and local credentials come from
  • Separates the task role from the execution role
  • Knows env-var-injected secrets go stale after rotation and caches with a TTL
  • Logs JSON to stdout and never logs secret values

Red flags

  • Uses IAM user access keys anywhere, even locally
  • Grants secretsmanager:* or * on all resources
  • Calls Secrets Manager on every request

📚 Learn in depth

1. The default credential chain

AWS 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.

2. Registering clients

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.

3. IAM policy design

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.

4. Rotation and caching

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:

  1. Cache the secret for minutes, not hours.
  2. On an authentication failure, invalidate the cache once, re-read and retry.
  3. Not hold the password in a long-lived object that never re-reads it.

5. Logs to CloudWatch

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.

6. Australian context

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.

Try it yourself

  1. Run aws configure sso, then aws sts get-caller-identity --profile dev and run the API locally with AWS_PROFILE=dev.
  2. Deploy to ECS with a task role that lacks GetSecretValue and read the AccessDeniedException message and the CloudTrail event.
  3. Add the narrow policy above and confirm the call succeeds.
  4. Rotate the secret manually with aws secretsmanager rotate-secret and watch your cached client pick up the new version after the TTL.
  5. Query your JSON logs in CloudWatch Logs Insights by Level and TraceId.

💻 Code

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

⚠ Common mistakes

  • Mistake: Creating an IAM user and putting its access key in 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.
  • Mistake: Granting the policy to the execution role instead of the task role. Why it is wrong: The execution role is only used by the ECS agent, so the app still gets 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.
  • Mistake: Injecting a rotating database password as an environment variable and assuming rotation "just works". Why it is wrong: The value is read at task start; after rotation, running tasks hold the old password. Instead: Read through a cache with a TTL and refresh on login failure, or force a redeploy as part of rotation.
  • Mistake: Calling 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.
  • Mistake: Creating a new SDK client per request. Why it is wrong: Each client builds its own HTTP connection pool and resolves credentials again, which wastes sockets and adds latency. Instead: Register clients once with AddAWSService<T>().
  • Mistake: Leaving IMDSv1 enabled on EC2 instances. Why it is wrong: An SSRF bug in the app can then read the instance role's credentials from the metadata endpoint with a simple GET. Instead: Require IMDSv2 (session tokens) and set the hop limit to 1 unless containers on the host need it.
  • Mistake: A leftover 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.
  • Mistake: Logging the connection string or secret JSON while debugging. Why it is wrong: CloudWatch Logs then holds credentials readable by anyone with log access. Instead: Log only the secret id and version stage.
  • Mistake: Leaving log groups at the default "never expire" retention. Why it is wrong: Cost grows forever and you keep personal information longer than needed. Instead: Set retention per log group (for example 30–90 days) and archive to S3 if required.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares IAM roles with managed identity Why: Checks that they can do the same end to end on Azure with DefaultAzureCredential and RBAC.
    How to answer

    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:

    • Key Vault: grant Key Vault Secrets User and use AddAzureKeyVault.
    • Blob Storage: grant Storage Blob Data Contributor and create BlobServiceClient with the credential.
    • Azure SQL: 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.

  2. When: Candidate talks about what should and shouldn't be a secret Why: Checks their general secrets-management model and local development without secrets.
    How to answer

    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.

  3. When: Candidate mentions narrow IAM policies Why: Checks least privilege more broadly, including database permissions and just-in-time admin access.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Partial outage when RDS password rotation ran
Situation
An [orders] API on ECS Fargate in ap-southeast-2, [12] tasks, read its RDS for SQL Server password from a task-definition secret injected as an environment variable. Secrets Manager rotation was turned on with a [30-day] schedule to meet [an internal Essential Eight-aligned policy].
Signals
ALB 5xx rate jumped to [35%]; logs full of `SqlException` 18456 'Login failed for user'; only some tasks failed; the Secrets Manager rotation Lambda's log showed a successful rotation minutes earlier.
Investigation
Correlated the error start time with the rotation event in CloudTrail (`RotateSecret`, `PutSecretValue`). Compared task start times in the ECS console: tasks started after rotation were healthy, older ones failed. Checked the task definition and found the password delivered through `secrets` to an environment variable, read once at start. Confirmed the rotation strategy was single-user, so the old password stopped working immediately.
Resolution
Mitigated with `aws ecs update-service --force-new-deployment`, which replaced all tasks within minutes. Then changed the app to read the secret through `SecretsManagerCache` with a 5-minute TTL and a refresh-and-retry on login failure, and switched RDS rotation to the alternating-users strategy so the previous credentials stay valid during the cache window.
Prevention
Rotate secrets in staging on every release candidate; a CloudWatch alarm on SQL login failures in logs; a CloudTrail-based alert on `RotateSecret` that links to the dashboard; a checklist item that rotating secrets must not be delivered through env vars.

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.

More in AWS

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me