SkillSprout
Chapter 1 · Lesson 2
Intermediate
6 min read

Credentials and IAM Roles for Applications

Overview

An application needs an identity to call AWS. The worst way to give it one is to paste long-lived access keys into source code or config files. The right way is to attach an IAM role to the compute that runs the code, and let the SDK fetch temporary credentials automatically.

Think of a hotel keycard. A permanent master key can be copied and lost; a keycard that expires every few hours and only opens your floor limits the damage if it is stolen. Roles hand your code that expiring keycard and rotate it for you.

The SDK finds credentials by walking a fixed credential provider chain. Knowing the order and which mechanism each compute service uses is a core exam skill.

Key Concepts

  • The default credential provider chain checks, in order: code parameters, environment variables, shared credentials/config (including SSO and assume-role profiles), container credentials, then EC2 instance profile (IMDS).
  • EC2 uses an instance profile (role) served by the Instance Metadata Service; use IMDSv2 (session tokens).
  • ECS tasks use a task role; the task execution role is separate and only pulls images and writes logs.
  • Lambda uses its execution role and injects temporary credentials as environment variables.
  • EKS uses IAM Roles for Service Accounts (IRSA) or EKS Pod Identity.
  • Humans should use IAM Identity Center (SSO) and short-lived sessions, not IAM user access keys.
  • Roles are assumed through STS AssumeRole; credentials include an access key, secret and session token.
  • Never commit keys; leaked keys are found by scanners within minutes.

Detailed Notes

Credential provider chain

PrioritySourceTypical use
1Explicit parameters in codeAvoid
2Environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKENCI jobs, Lambda
3Shared credentials/config file, SSO, role_arn profilesLaptops
4Container credential endpoint (AWS_CONTAINER_CREDENTIALS_RELATIVE_URI)ECS/Fargate
5EC2 instance metadata (IMDS)EC2

Because environment variables beat instance profiles, a stale AWS_ACCESS_KEY_ID on a server can silently override the role and cause confusing AccessDenied errors.

Which role for which service?

ComputeRole mechanism
EC2Instance profile wrapping an IAM role
LambdaFunction execution role
ECS / FargateTask role (app) and task execution role (agent)
EKSIRSA or Pod Identity
CodeBuild / CodePipelineService role

Role trust policy and permissions

A role has two policies: the trust policy (who can assume it) and permission policies (what it can do).

json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "ec2.amazonaws.com" },
    "Action": "sts:AssumeRole"
  }]
}

Local development with SSO

bash
aws configure sso --profile dev
aws sso login --profile dev
export AWS_PROFILE=dev
python app.py   # SDK picks up the SSO session automatically

Assuming a role in code

python
import boto3

sts = boto3.client("sts")
resp = sts.assume_role(
    RoleArn="arn:aws:iam::111122223333:role/ReadOnlyAudit",
    RoleSessionName="audit-job",
    DurationSeconds=3600,
)
c = resp["Credentials"]
s3 = boto3.client(
    "s3",
    aws_access_key_id=c["AccessKeyId"],
    aws_secret_access_key=c["SecretAccessKey"],
    aws_session_token=c["SessionToken"],
)

Prefer an ~/.aws/config profile with role_arn and source_profile so the SDK refreshes automatically.

IMDSv2

IMDSv2 requires a session token obtained with a PUT request, which blocks SSRF-style credential theft. Enforce it with HttpTokens=required in launch settings.

bash
TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/

Troubleshooting

Run aws sts get-caller-identity to see which identity is actually being used. If the ARN is not the role you expect, look for environment variables or profiles overriding it.

Programmatic access options compared

OptionLifetimeWhen to use
IAM user access keysLong-lived until rotatedAvoid; legacy integrations only
IAM Identity Center (SSO)HoursDevelopers on laptops
Role on compute (EC2, ECS, Lambda)Auto-rotatedAnything running in AWS
OIDC federation (AssumeRoleWithWebIdentity)Minutes to hoursGitHub Actions, GitLab CI, EKS service accounts
IAM Roles AnywhereHoursOn-premises servers with X.509 certificates

Federated CI without stored keys

A GitHub Actions workflow can exchange its OIDC token for AWS credentials. The role trusts the GitHub identity provider and pins the repository in a condition, so nothing secret is stored in the repository.

json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
      "StringLike": { "token.actions.githubusercontent.com:sub": "repo:my-org/my-app:ref:refs/heads/main" }
    }
  }]
}
yaml
permissions:
  id-token: write
steps:
  - uses: aws-actions/configure-aws-credentials@v4
    with:
      role-to-assume: arn:aws:iam::111122223333:role/GitHubDeploy
      aws-region: eu-west-1

Authenticated calls between services

In a microservice system, one service often calls another's API. Use IAM authorisation (SigV4) on API Gateway or Lambda function URLs so the caller's role is the identity, or pass a JWT that the receiving service validates. Never share one broad key between services. Sign a request manually only when the SDK does not support the target, for example calling an execute-api URL.

python
import boto3, requests
from requests_aws4auth import AWS4Auth

c = boto3.Session().get_credentials().get_frozen_credentials()
auth = AWS4Auth(c.access_key, c.secret_key, "eu-west-1", "execute-api", session_token=c.token)
print(requests.get("https://abc123.execute-api.eu-west-1.amazonaws.com/prod/orders", auth=auth).status_code)

Real World Example

A startup stored an IAM user's access keys in a Docker image to let a service write to S3. A public repository leaked the image and the keys were abused within hours. The fix: the service moved to ECS Fargate with a task role scoped to a single bucket prefix. No secrets live in the image, credentials expire in hours, and CloudTrail shows the role session name for every call.

Architecture Diagram

Temporary credentials for a workload
Architecture
AWS Cloud
IAM roletrust + permissions
STStemporary creds
App on EC2/ECS/LambdaSDK
S3 bucket

The compute service obtains role credentials from STS and exposes them to the SDK.

  1. 1An IAM role with a trust policy for the compute service is attached to the workload.
  2. 2The platform calls STS and delivers temporary credentials to the runtime.
  3. 3The SDK discovers them through the provider chain and signs requests.
  4. 4Credentials refresh automatically before they expire.

Best Practices

  • ✓Use roles, not IAM user keys, for any workload on AWS.
  • ✓Use IAM Identity Center and short sessions for human CLI access.
  • ✓Require IMDSv2 on all EC2 instances.
  • ✓Scope each role to one application and the minimum actions and resources.
  • ✓Scan repositories for secrets and rotate any exposed key immediately.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • If a question says an app runs on EC2/ECS/Lambda and needs access, the answer is an IAM role, not access keys.
  • Execution role vs task role: know which one the question describes.
  • Hard-coded or committed keys are always the wrong answer.
  • get-caller-identity is the first debugging step for permission puzzles.

Finished this lesson?

0 of 46 lessons done · 0% of the course