Trace Identity Center, STS and Federation to the API Caller
Terraform does not hold a key to your AWS account. It holds a borrowed keycard: a temporary credential, scoped to one role, valid for a bounded time, and logged at every door it opens. A provider block is not an identity; it is a set of instructions for finding an identity, and every plan begins with the question of which identity those instructions found.
Start with four words AWS documentation uses loosely. A principal is the thing making the request. An IAM role is a permission container with two policies: a trust policy saying who may enter, and identity policies saying what the entrant may do. A role session is one activation of that role by one principal, with its own name, tags and expiry. A federation exchanges an identity assertion from elsewhere, such as a corporate identity provider or a CI system, for AWS credentials. AWS Security Token Service (STS) performs that exchange and returns an access key ID, a secret access key and a session token. Only the first is safe to show anyone.
The human path. An engineer signs in to IAM Identity Center with multi-factor authentication. The corporate identity provider returns a SAML assertion or OIDC token, Identity Center maps the assigned permission set to a role in the target account, and STS issues a session. Identity Center permission-set roles are special: Identity Center owns and secures them, only Identity Center users can assume them, and their trust policies cannot be edited to admit outsiders (AWS documentation). A permission-set session lasts from one to twelve hours, with one hour as the default. The AWS CLI caches and refreshes it, so a plan started in the morning may run under a different session by afternoon.
The machine path uses a token, not a stored key. A CI job presents a short-lived OIDC token to STS, and the role's trust policy restricts which repository, branch and workflow may present it. The provider accepts that token either as a block or as environment variables the SDK resolves.
Both forms are documented in the provider authentication reference.
The provider resolves credentials in a fixed order, and the first match wins. It mirrors the AWS CLI, which is why an exported shell variable can override a carefully written block.
| Order | Source | Read from |
|---|---|---|
| 1 | Provider arguments | the provider block itself |
| 2 | Environment variables | the shell that launched Terraform |
| 3 | Shared credentials | the AWS credentials file |
| 4 | Shared configuration | the AWS config file |
| 5 | Container credentials | the container credential endpoint |
| 6 | EC2 metadata | the instance profile |
The shell outranks the provider block
A developer exports a profile for one task and forgets it. The next plan quietly runs as the wrong role, and a perfect provider block is overruled by the shell it inherits. AWS_PROFILE is the usual culprit; unsetting it is the fix, not another guard in code.
Once the session exists, ask AWS who you are rather than assuming. The caller-identity data source returns the account, ARN and user ID for the exact alias it is attached to, and the region data source returns the configured region.
For an assumed role the ARN ends in the role and session name, as in arn:aws:sts::111122223333:assumed-role/tf-deployer/ci-4821; the user ID repeats the session name after a colon. Figure 1 shows the full exchange for both a human and a workload.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
autonumber
actor Caller as Engineer or CI workload
participant IdP as Identity provider / OIDC issuer
participant IdC as IAM Identity Center
participant STS as AWS STS
participant TF as Terraform CLI
participant API as AWS service API
Caller->>IdP: sign in with MFA, or present short-lived OIDC token
IdP-->>IdC: SAML assertion or OIDC token
IdC->>STS: AssumeRole for the permission-set role
alt Trust policy allows and session is live
STS-->>TF: Temporary key, secret and session token
TF->>API: Signed plan-time reads and writes
API-->>TF: Response recorded in CloudTrail
else Trust denies or session expires
STS-->>TF: AccessDenied or ExpiredToken
TF-->>Caller: Plan stops before resource creation
end
Note over TF,API: Record account, ARN, session name,
region and expiry — never record
the secret or token
The session name is the audit handle
Set the session name in the provider's assume-role block, with the pipeline or person in it, and set source_identity to the identity behind the run. CloudTrail records both on the AssumeRole call and on every later service call (CloudTrail reference), and a trust policy can require them with a source-identity condition — closing the gap between “a pipeline ran” and “this person's change ran”.
What you record and what you publish differ. Figure 2 is the recording sheet this series uses: account, role ARN, session name, region, partition, expiry and source identity belong in the evidence file; the secret key, session token, plan file, state JSON and trace logs never do.
Separate Backend Roles from Resource-Provisioning Roles
The analogy that keeps teams out of trouble is a building with three keys. The backend key opens the ledger room where the record of the building is kept. The deployment key opens the construction site. The workload key opens one occupied apartment. Losing the ledger key is not the same incident as losing the construction key, and neither is the same as losing a tenant's key, so they should never be the same piece of metal.
Terraform demonstrates the split, often unnoticed. The S3 backend resolves its own credentials, separately from the provider. Its documentation says plainly that backend operations are performed with the administrator's credentials, while resource operations go through the provider's assume_role (S3 backend reference). That means a single terraform apply can use two entirely different identities, and reviewing only the provider block reviews half the run.
The backend role reads and writes one state object and its lock. Its policy grants list on the bucket under a prefix condition, get and put on the exact key, and delete on the lock object only when locking is enabled. It should hold nothing else.
State is a secret store in disguise. Plaintext attributes mean read access to state is often read access to the infrastructure's secrets. Turn on bucket versioning and SSE-KMS, and give the role decrypt and data-key permission on one key — never a wildcard.
The deployment role lives in each target account and is trusted by a principal, not by an account root. It is the only role allowed to create and change resources. A trust policy naming the account root admits anyone in that account who can call AssumeRole, which is usually broader than intended. Name the calling role's ARN instead, add the principal-ARN and organisation-ID conditions as outer boundaries, and require an external ID for any third party.
Service principals need their own two conditions. Source-account and source-ARN stop a service being tricked into acting for another account. Cross-account access always needs both sides: the caller's identity policy must allow the assume action on the target ARN, and the target's trust policy must admit the caller. Either alone gives a clean AccessDenied before any resource call.
The workload role belongs to the application, not the pipeline. It is trusted by the ECS tasks, Lambda and EKS OIDC service principals, and it must never be assumable by the CI role. If it is, a pipeline compromise becomes a runtime compromise, and the blast radius of a bad pull request extends from "changed infrastructure" to "read the production database."
Least privilege is structural before it is textual
Three boundaries intersect; the smallest one wins. A permissions boundary caps the deployment role, a service control policy caps the whole account, and the identity policy grants the subset this configuration needs. That is why adding a permission sometimes changes nothing.
iam:PassRoleonly with a passed-to-service condition, so a role can reach EC2 but not Lambda- no
iam:CreateUseroriam:CreateAccessKeyunless a reviewed exception exists - no organisation-wide actions in a deployment policy
Figure 3 traces the three trusts and the three places they can fail.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A[CI workload identity] --> B{Backend role trust
PrincipalArn and OrgID}
B -- deny --> X1[AccessDenied
state unreadable, plan stops]
B -- allow --> C[Backend session
state prefix plus tflock only]
A --> D{Deployment role trust
ExternalId and PrincipalArn}
D -- deny --> X2[AccessDenied
no credentials for target account]
D -- allow --> E[Deployment session
SCP and permissions boundary]
E --> F{Identity policy allows
this specific action}
F -- deny --> X3[UnauthorizedOperation
nothing created]
F -- allow --> G[Resource changed in target account]
H[Workload role] -.->|trusted by service principal only| G
E -.->|must not assume| H
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,C,E,G primary;
class B,D,H secondary;
class F ok;
class X1,X2,X3 danger;
Role chaining caps the session at one hour
A session that assumes another role cannot outlive that chain. When a role session assumes a second role, the resulting session is capped at one hour, and a larger requested duration fails (AWS knowledge center). A chain of CI role, backend role and deployment role is already two hops. Prefer a direct OIDC trust into each role, and keep max_session_duration consistent with the requested duration.
Map Regional and Global Services to Provider Aliases
An alias is not a cosmetic label. It is a named provider instance with its own credential resolution, account guard, region and default_tags. When you pass aws.prod_us_east_1 into a module, all of that travels as one object. Naming aliases by account and region, rather than by team or purpose, keeps the blast radius visible at the call site.
Version 6 of the provider weakened the old rule that every region needs its own provider block: most resources now accept a top-level region argument, which is optional and computed, defaults to the provider's region, and forces replacement when changed. Removing the argument does not force replacement; the prior value from state is used (enhanced region support). That suits a one-off cross-region resource but is a poor substitute for aliases at module boundaries, because aliases also carry the role and account guard that region does not.
| Scope | Representative resources in aws 6.72.0 | Alias that owns it | Guard to enforce |
|---|---|---|---|
| Regional workload | aws_vpc, aws_subnet, aws_db_instance, aws_eks_cluster | aws.prod_us_east_1 | allowed_account_ids plus a region precondition |
| Regional but consumer-fixed | aws_acm_certificate, aws_wafv2_web_acl with scope = "CLOUDFRONT" | aws.global_us_east_1 | region must equal us-east-1 |
| Global service | aws_iam_role, aws_route53_zone, aws_cloudfront_distribution, aws_organizations_account | aws.global_use1 | account must be the security or management account |
| Global object in a regional service | aws_s3_account_public_access_block, aws_backup_global_settings, aws_ram_sharing_with_organization | aws.global_use1 | account guard only; no region semantics |
| Identity probe | aws_caller_identity, aws_region, aws_partition, aws_arn | the alias under test | read through the same alias the resources use |
The middle rows are where real incidents live. An ACM certificate for CloudFront must be requested or imported in us-east-1, regardless of where the distribution's origin sits (ACM FAQ). An IAM role is a global object even though its API call is signed for a region, which is why IAM resources are explicitly listed as non-region-aware in the provider's guide. And an S3 bucket's name is globally unique while its location is fixed at creation from the provider's region, so the same module applied through two aliases creates two buckets in two places unless you assert the region.
The account guard runs while the provider configures itself, before any read or create. allowed_account_ids is the supported control, with the mutually exclusive forbidden_account_ids as its mirror. On an instance profile the provider reads the account from instance metadata; otherwise it tries GetUser, GetCallerIdentity, then ListRoles, so the caller must be able to do one of those (provider configuration).
There is no provider-level region allowlist, so build one. Read the current region and partition from their data sources, compare them with variables, and fail a precondition; variable validation catches a typo before the API call. The partition check matters when a configuration might meet the China or GovCloud partitions.
Modules receive aliases; they never construct their own. A child declares its required aliases in configuration_aliases and receives them through the providers map. Two rules follow: a module must never hardcode a region in its own provider block, because that defeats every guard at the boundary, and a module that touches a global service should receive the global alias explicitly.
The plan that looks ordinary
A developer still has a shared-services profile exported. The stack's resources omit the provider meta-argument, so they land on an implicit default instance with a region but no account guard. The plan is valid, the diff looks ordinary, and apply creates a VPC in the shared-services account. The fix is structural: guard every instance, name the alias in every resource, and make the sanitized identity record a required plan output.
Inspect the Pinned AWS Schema and Dependency Lock
A provider upgrade is a code upgrade inside a binary that speaks to hundreds of APIs. The diff you care about is in the schema and the lock file, not only the changelog.
Pin the CLI, the provider and the lock, and record when you verified them. This article was checked on 5 November 2026 against Terraform CLI 1.17.1 (the supported release, published 28 October 2026) and hashicorp/aws 6.72.0, the release the Registry returned. A range such as ~> 6.0 is not a pin; it accepts whatever the Registry serves next.
The lock file is the contract. Commit it, and let CI fail when it changes without a reviewed commit. It records the selected version and content hashes, so a later init either reuses the same artefact or refuses. A lock written only on macOS makes a Linux pipeline fail at init with a checksum error that looks like corruption, which is why the lock command records both platforms. The version command captures the evidence file, and the providers command shows which module owns which provider instance.
Inspect the schema you pinned, not the schema you remember. After init, the provider schema command emits the full attribute set, and a short jq query answers concrete questions: whether a resource exposes a top-level region, whether it supports tags_all, whether an argument is deprecated. This catches documentation written for 5.x against the release in your lock file.
Several 6.72.0 behaviours are worth confirming this way. Each one has a consequence that is easy to miss in a plan diff.
| Behaviour | What the pinned release does | What to watch |
|---|---|---|
default_tags | applies to resources that implement tags, except aws_autoscaling_group; per-resource tags can override a key but not exclude it, and tags_all is the union | a provider tag missing from an autoscaling group |
TF_AWS_DEFAULT_TAGS_<key> | default tags can also arrive from the environment | the provider block wins on conflict |
ignore_tags | accepts exact keys and key prefixes, and suppresses the difference rather than the tag | a removed compliance tag stays hidden |
max_retries | 25 in the provider, 5 in the S3 backend | throttling in one layer but not the other |
s3_us_east_1_regional_endpoint | deprecated, with removal planned for 7.0.0 | do not build a pattern on it |
| Functions and ephemeral resources | arn_parse, arn_build, trim_iam_role_path; ecr_authorization_token keeps a secret out of state | only use what the pinned version ships |
Figure 4 contrasts the outcomes. On the left, a range constraint plus a fresh laptop produces a different provider binary each quarter and a plan full of changes nobody wrote. On the right, an exact version plus a committed, multi-platform lock produces the same binary and plan; any change to that contract is a reviewable diff.
Prove a Wrong-Account Plan Is Rejected
The test is deliberately boring, because a boundary test should be. It creates no VPC, no bucket and no role, applies no billable resource, and proves two things: the provider refuses to configure under the wrong account, and the configuration refuses to plan when the account does not match what the module expects.
Prove a Wrong-Account Plan Is Rejected
Status: design-only. No AWS account, credentials or billable resource was used to produce this article, and none of the commands below were executed here. The procedure is written so a reader can run it in a disposable sandbox account and produce the evidence listed at the end. Treat the identifiers as placeholders: 111122223333 is the sandbox, 444455556666 is a second, untouched account.
Prerequisites. Terraform CLI 1.17.1, the AWS provider 6.72.0, AWS CLI v2 with an Identity Center profile named aw01-sandbox, and permission to read the sandbox's own identity. Cost is zero: the identity data sources and the built-in test resource are free, and nothing is created, so there is nothing to bill or destroy.
Minimal setup. One directory and four files, with no modules:
labs/aw01-identity/
├── versions.tf # CLI = 1.17.1, provider = 6.72.0
├── providers.tf # one guarded instance, alias "sandbox"
├── variables.tf # allowed and expected account, region, role suffix
└── main.tf # three identity reads plus the guard precondition
Two gates, tested separately. The provider guard and the stack precondition fail at different moments, which is why the lab tests both.
| Gate | What it proves | Failure looks like |
|---|---|---|
| Provider account guard | the run refuses to configure under the wrong account | configuration error before refresh |
| Stack precondition | the configuration refuses a mismatched expected account | plan-time error with your own message |
The provider instance carries the account guard and the lab's default tags, and the identity reads use the same alias the real resources would use. The variables hold the guard value plus three expected values, each with validation.
- Sign in with
aws sso login --profile aw01-sandbox, then confirm the shell did not export a conflictingAWS_PROFILEor anyAWS_ACCESS_KEY_ID. This step exists because environment variables outrank the profile. - Run
terraform initand keep the resulting.terraform.lock.hcl. Captureterraform version -jsonandterraform providersinto the evidence file. - Run
terraform plan -out=aw01.tfplanand read the identity data sources throughaws.sandbox, the same alias that will own the real resources. The expected result is a plan to add oneterraform_dataobject and nothing else. - Now the actual test. Run
AWS_PROFILE=aw01-other terraform plan -out=aw01-wrong.tfplan, where that profile resolves to444455556666. Expect a non-zero exit and a provider configuration error naming the account mismatch. The failure must occur before refresh and before any resource read, andterraform state listmust remain empty. - Test the second gate independently. Keep the correct profile and run
terraform plan -var expected_account_id=444455556666. The provider guard still passes becauseallowed_account_idis unchanged, and theterraform_dataprecondition must fail during planning with your own error message. This is what catches a configuration copied from another environment while the credentials are correct. - Prove the guard cannot be bypassed with
terraform plan -refresh=false. The provider still configures itself, so the wrong account still fails. Refresh suppression is not an identity control. - Sanitize the evidence and delete the artefacts: redact account digits, drop secret and token lines, delete both plan files, remove
.terraformand any local state, and runaws sso logoutif the machine is shared.
Expected observation. The correct run produces a one-object plan and a caller record with the sandbox account, an assumed-role ARN whose session name matches the configured value, and the expected region. The wrong run produces no plan at all. In CloudTrail, the wrong-account attempt shows only identity-resolution calls, such as GetCallerIdentity, and no mutating API call, audit proof that rejection preceded creation.
Failure check. If the wrong-account plan succeeds, do not add more conditions; find the leak. The usual causes:
- a resource that omits the sandbox provider and silently uses an unguarded default instance
skip_requesting_account_id = true, which disables the resolution the guard depends on- credentials arriving from the instance metadata service because the profile was ignored
- a guard declared on an alias the tested resource never uses
Each is a wiring mistake, visible in terraform providers and the provider block in the plan output.
Evidence to keep. A caller record with account, ARN, session name, region, partition and expiry; the alias table; the terraform version -json and lock-file diff; the rejection transcript with its exit code; and the sanitized trust diagram from Figure 3. Together they satisfy the lab's acceptance criteria without publishing secrets.
Next in the Series
In AWS Networking: VPCs, Routes, Security Groups and Private Endpoints, we'll explore Model private connectivity and egress with explicit subnet, route and security-rule ownership.