Safe multi-account AWS access: Granted + direnv

Generate IAM Identity Center profiles with Granted and let direnv pick the right AWS account per repo, so Terraform never hits the wrong client.

8 min read

aws-granted-tool

Introduction

When you work across several AWS organizations, the riskiest command in your day isn’t terraform destroy. It’s any command run in the wrong account. Exported credentials linger in a terminal tab, you cd into another client’s repo, and the AWS CLI happily keeps using the old session.

This article builds a setup that removes that class of mistake:

  • Granted handles authentication. It generates profiles from IAM Identity Center, caches credentials in the OS keychain, and opens the AWS Console for any role in an isolated browser container.
  • direnv handles context. Each repo carries an .envrc that sets AWS_PROFILE when you enter the directory and unsets it when you leave.

Why Granted rather than the alternatives? aws-vault is excellent for long-lived IAM user keys but has a weaker console story. The native aws sso login works, but it doesn’t give you per-role browser isolation or a fuzzy picker across hundreds of profiles. Leapp is a GUI rather than a CLI. Granted sits in the sweet spot for SSO-heavy, multi-org work.

By the end you’ll have: every account/role you can reach generated as a profile, the AWS CLI and Terraform authenticating automatically per repo, and side-by-side consoles for dev and prod in separate containers.


Prerequisites

ItemDetails
AWS accessAt least one AWS Organization with IAM Identity Center enabled, and a user assigned to one or more permission sets. Option B below covers IAM users without SSO.
IAM permissionsNo admin rights needed on your side. You only need the permission sets you’ve been assigned. Generating profiles calls the SSO portal APIs (ListAccounts, ListAccountRoles), which any Identity Center user can call.
ToolsmacOS or Linux, Homebrew, AWS CLI v2, zsh or bash. Firefox if you want container-based console isolation. Terraform is optional.
CostZero. IAM Identity Center, STS and both tools are free. Nothing in this guide creates billable resources.
Assumed knowledgeComfort with ~/.aws/config profiles, environment variables, and basic shell configuration.

Architecture overview

The key idea is a split of responsibilities. direnv never touches credentials. It only decides which profile name is active, based on the directory you’re in. Granted never decides which account you want. It only turns a profile name into short-lived credentials.

The glue is the AWS SDK’s credential_process setting. When Terraform or the AWS CLI sees AWS_PROFILE=DunderMifflin-dev, it reads that profile, finds credential_process = granted credential-process --profile DunderMifflin-dev, and runs it. Granted checks its keychain cache. If the role credentials are still valid it returns them immediately. If not, it uses the cached SSO token to call GetRoleCredentials, and only falls back to a browser login when the SSO session itself has expired.

That design gives you two properties that matter in practice. First, there are no long-lived secrets in plaintext anywhere. Second, the “current account” lives in the directory structure rather than in the terminal’s memory. Closing a tab or opening a new one can’t leave you pointed somewhere unexpected.

The console path is separate. assume -c builds a federated sign-in URL and opens it in a Firefox container dedicated to that role, so DunderMifflin-prod and clientB-dev can sit in neighbouring tabs without logging each other out.

Describe the image


Step-by-step deployment

Phase 1: Setup

Step 1. Install Granted

brew tap fwdcloudsec/granted
brew install granted

Check the install:

granted -v

Describe the image

Step 2. Configure the assume alias

assume must be sourced to export variables into your current shell. Run it once and accept the prompt:

assume

Describe the image

If you prefer to do it manually, add this to ~/.zshrc, then reload with source ~/.zshrc:

alias assume=". assume"

Step 3. Choose the console browser

If you want to change the console browser:

granted browser set

Describe the image Pick Firefox, then install the Granted Containers extension from addons.mozilla.org when prompted. Chromium-based browsers work too, but Granted uses separate browser profiles there rather than containers.

Step 4. Install direnv and hook it into your shell

brew install direnv

 

Add the hook as the last line of ~/.zshrc:

For bash use eval "$(direnv hook bash)"

eval "$(direnv hook zsh)"

 

Reload the shell, then check:

source ~/.zshrc
direnv version

Describe the image

Phase 2: Configure

Run this once per client organization. Use --prefix to namespace profiles by client:

granted sso populate \
  --sso-region eu-north-1 \
  --prefix DunderMifflin- \
  https://d-xxxxxxxxxx.awsapps.com/start

 

A browser tab opens with a device code. Approve it, and Granted lists every account and role you can reach:

[i] listing available profiles from AWS IAM Identity Center...
[✔] populated 6 profiles for https://d-xxxxxxxxxx.awsapps.com/start

 

Open ~/.aws/config and look at a generated profile. It should look roughly like this:

[profile DunderMifflin-dev/SuperPractioner]
granted_sso_start_url      = https://d-xxxxxxxxxx.awsapps.com/start
granted_sso_region         = eu-north-1
granted_sso_account_id     = 111122223333
granted_sso_role_name      = SuperPractioner
common_fate_generated_from = aws-sso
credential_process         = granted credential-process --profile DunderMifflin-dev/SuperPractioner

 

Notice the granted_ prefix on the SSO keys. That’s deliberate, and the Gotchas section explains why.

Repeat for every other organization with its own start URL and prefix (--prefix Initech-).

Step 5b. IAM user keys + role assumption (Option B)

For a client without Identity Center, store the long-lived keys in the keychain instead of ~/.aws/credentials:

granted credentials add
? Profile Name: UnicornRentals-base
? Access Key ID: AKIA...
? Secret Access Key: ****
[✔] Saved UnicornRentals-base to secure storage

 

Then define the role to assume in ~/.aws/config:

[profile UnicornRentals-base]
credential_process = granted credential-process --profile UnicornRentals-base
region             = eu-north-1
 
[profile UnicornRentals-prod]
role_arn       = arn:aws:iam::111122223333:role/Admin
source_profile = UnicornRentals-base
mfa_serial     = arn:aws:iam::444455556666:mfa/jimmy
region         = eu-north-1

Step 6. Give each repo its context with .envrc

In each client repo, create an .envrc:

# ~/work/DunderMifflin/infra-dev/.envrc
 
# Clear anything a previous `assume` left behind (see Gotchas)
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
 
export AWS_PROFILE="DunderMifflin-dev/SuperPractioner"
export AWS_REGION=eu-north-1
 
# Optional: per-client Azure and GCP context
export AZURE_CONFIG_DIR="$HOME/.azure-DunderMifflin"
export CLOUDSDK_ACTIVE_CONFIG_NAME=dundermifflin
 
# Untracked overrides
source_env_if_exists .envrc.local

 

For several environments under one client, put shared settings in a parent .envrc and use source_up in the child directories:

~/work/DunderMifflin/
├── .envrc              # shared: region, Azure/GCP context
├── infra-dev/.envrc    # source_up + AWS_PROFILE=DunderMifflin-dev/...
└── infra-prod/.envrc   # source_up + AWS_PROFILE=DunderMifflin-prod/ReadOnlyAccess
# ~/work/DunderMifflin/infra-prod/.envrc
source_up
export AWS_PROFILE="DunderMifflin-prod/ReadOnlyAccess"

Phase 3: Deploy

Step 7. Allow the .envrc files

direnv refuses to load an .envrc until you explicitly approve it:

cd ~/work/DunderMifflin/infra-dev
direnv: error /Users/jimmy/work/DunderMifflin/infra-dev/.envrc is blocked. Run `direnv allow` to approve its content
direnv allow
direnv: loading ~/work/DunderMifflin/infra-dev/.envrc
direnv: export +AWS_PROFILE +AWS_REGION +AZURE_CONFIG_DIR +CLOUDSDK_ACTIVE_CONFIG_NAME

You’ll need to re-run direnv allow after every edit of the file. That’s the security gate, not a bug. (It will feel like a bug at 2 a.m.)

Step 8. Add .envrc.local to .gitignore

echo ".envrc.local" >> .gitignore

Committing .envrc itself is usually fine. Profile names and regions aren’t secret, and teammates benefit from them.

Step 9. Show the active profile in your prompt

Any prompt framework works. With Starship, the aws module is on by default and shows the profile and region. Seeing DunderMifflin-prod in red before you hit Enter is the cheapest safety net you can buy, and cheaper than the apology email.

Phase 4: Verify

Step 10. Confirm the switch happens on cd

cd ~/work/DunderMifflin/infra-dev && echo $AWS_PROFILE
cd ~/work/DunderMifflin/infra-prod && echo $AWS_PROFILE
cd ~ && echo "profile: ${AWS_PROFILE:-<unset>}"
DunderMifflin-dev/SuperPractioner
DunderMifflin-prod/ReadOnlyAccess
direnv: unloading
profile: <unset>

Verification / testing

1. Check the identity in each repo.

cd ~/work/DunderMifflin/infra-dev
aws sts get-caller-identity
{
    "UserId": "AROAXXXXXXXXXXXXXXXXX:jimmy@archnops.com",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_SuperPractioner_abc123/jimmy@archnops.com"
}

 

Run it again from infra-prod. The Account and the role name in the ARN must change.

 

2. Check that Terraform picks it up without any wrapper.

terraform init && terraform plan

 

The plan should run without an auth prompt. If the SSO session expired, a browser tab opens once and the plan continues.

 

3. Check the credential process directly.

granted credential-process --profile "DunderMifflin-dev/SuperPractioner" | jq '.Version, .Expiration'
1
"2026-10-25T23:45:12Z"

4. Check console isolation.

assume -c DunderMifflin-dev/SuperPractioner
assume -c DunderMifflin-prod/ReadOnlyAccess -s cloudwatch -r eu-north-1

 

Two Firefox tabs should open, each with a different container colour and signed into a different account at the same time.

Describe the image


Gotchas & lessons learned

  • assume silently beats AWS_PROFILE. Running assume in a shell exports AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN. AWS tooling gives those environment variables precedence over AWS_PROFILE. So if you run assume Initech-prod and then cd into DunderMifflin’s repo, direnv sets the right profile, but the old keys outrank it and you’re now confidently running DunderMifflin’s plan as Initech. Confidence is not correctness. That’s why every .envrc above starts with unset AWS_ACCESS_KEY_ID .... In direnv-managed repos, keep assume for -c (console) only.
  • credential_process is ignored if standard SSO keys are present. If a profile contains both credential_process and the usual sso_start_url / sso_account_id keys, the AWS CLI skips the credential process and falls back to aws sso login. That’s why Granted writes granted_sso_* keys instead. If you hand-edit a profile or copy one from an old aws configure sso setup, rename those keys or the integration quietly stops working.
  • Profiles from other tools confuse Granted. A config previously populated by aws-sso-util or similar contains a credential_process pointing to that tool plus keys Granted doesn’t expect. Clean those profiles out, or regenerate them with granted sso populate, rather than mixing generators in one file.
  • populate replaces matching profiles. Re-running granted sso populate merges into ~/.aws/config and overwrites profiles with the same name. Anything you added by hand to a generated profile, like a custom region, disappears. Keep customisations in separate, hand-written profiles, and back up the file before re-running.
  • Large organizations hit API throttling. On orgs with hundreds of accounts, populate can fail with TooManyRequestsException from the SSO portal API. AWS is rate-limiting you, not judging you: wait a bit and retry.
  • Profile names with slashes need quoting. Generated names like DunderMifflin-dev/SuperPractioner are fine for the AWS CLI, but always quote them in .envrc and scripts. Some tools that build file paths or resource names from the profile name choke on the /. If that bites you, use --profile-template on populate to choose a flatter naming scheme.
  • sso-region is not your working region. --sso-region is where Identity Center lives, which may be eu-west-1 even if all your workloads run in eu-north-1. Set AWS_REGION separately in .envrc.
  • Keychain prompts on macOS. The first few credential-process calls may trigger keychain access dialogs. Choosing “Always Allow” for the Granted binary stops them, though they may come back after an upgrade.
  • direnv hook order matters. If direnv stops reacting to cd after you add a prompt framework, check where the direnv hook line sits relative to the framework’s initialisation. Putting it last in ~/.zshrc is the usual fix, and the failure mode is pure silence, which is the worst kind.
  • Short sessions in prod are a feature. Identity Center role credentials last one hour by default, and the SSO session itself has its own duration set by the admin. Resist asking clients to lengthen these; one-hour credentials are a security team’s love language. With credential_process the refresh is invisible anyway.

Conclusion & next steps

You now have authentication and context cleanly separated. Granted turns any profile into short-lived, keychain-cached credentials and gives you isolated consoles per role. direnv makes the active profile a property of the directory, so the account you’re working in follows the repo rather than whichever terminal tab you happen to use. Picking the wrong account is still possible. It just takes effort now, which is the best a safety feature can ask for.

Where to go from here:

  • Extend it to the other clouds. The same .envrc pattern works with AZURE_CONFIG_DIR for isolated az logins and CLOUDSDK_ACTIVE_CONFIG_NAME for gcloud configurations.
  • Add a production guardrail. A small check in your prod .envrc that echoes a warning, or a Terraform allowed_account_ids setting in the provider block, makes the wrong account a hard failure instead of a surprise.
  • Explore Granted’s extras. Look at assume --exec to run a single command under a profile, and granted settings for tuning defaults.
  • Read the docs. Granted: https://docs.granted.dev · direnv: https://direnv.net