AWS
boto3
CloudFront
AWS profiles
cloud computing

How to choose an AWS profile when using boto3 to connect to CloudFront

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When a script can access multiple AWS accounts, choosing the right profile in Boto3 is a safety requirement, not a convenience detail. One mistaken profile can invalidate or modify the wrong CloudFront distribution. The reliable pattern is explicit session creation, identity verification, and clear logging of account context for every run.

How Boto3 Selects Credentials

Boto3 uses a provider chain. Credentials may come from environment variables, shared profile files, role assumptions, container metadata, or instance metadata. If your code relies on implicit behavior, it can work locally and fail in CI, or worse, run in the wrong account.

Make profile selection explicit for local multi-account workflows:

python
1import boto3
2
3session = boto3.Session(profile_name="prod-admin", region_name="us-east-1")
4cloudfront = session.client("cloudfront")
5
6result = cloudfront.list_distributions()
7count = result.get("DistributionList", {}).get("Quantity", 0)
8print("distribution count:", count)

Explicit session setup is the simplest way to make intent visible in code review.

Verify Active Identity with STS

Before any write operation, verify the active principal and account. This one check prevents many incidents.

python
1import boto3
2
3def build_session(profile: str) -> boto3.Session:
4    session = boto3.Session(profile_name=profile, region_name="us-east-1")
5    sts = session.client("sts")
6    who = sts.get_caller_identity()
7    print("account:", who["Account"])
8    print("arn:", who["Arn"])
9    return session
10
11session = build_session("staging-reader")

In deployment tooling, fail fast if the account id is not in an allow-list for that workflow.

Local Development with AWS_PROFILE

For command-line workflows, using AWS_PROFILE is convenient.

bash
export AWS_PROFILE=dev-engineering
python cloudfront_audit.py

Code can still support this pattern while preserving explicitness:

python
1import os
2import boto3
3
4profile = os.getenv("AWS_PROFILE")
5session = boto3.Session(profile_name=profile) if profile else boto3.Session()
6
7identity = session.client("sts").get_caller_identity()
8print("active account:", identity["Account"])

This keeps scripts ergonomic for developers without hardcoding profile names.

Multi-Account Automation Pattern

If one script needs to scan many accounts, isolate each context with its own session and client objects.

python
1import boto3
2
3profiles = ["dev-engineering", "staging-reader", "prod-admin"]
4
5for profile in profiles:
6    session = boto3.Session(profile_name=profile, region_name="us-east-1")
7    sts = session.client("sts")
8    cf = session.client("cloudfront")
9
10    account = sts.get_caller_identity()["Account"]
11    qty = cf.list_distributions().get("DistributionList", {}).get("Quantity", 0)
12    print(profile, account, qty)

Do not reuse a client from one session in another account block. Keep boundaries strict.

Profile Configuration and Role Assumption

Profile entries usually live in ~/.aws/config and ~/.aws/credentials. Prefer role assumption and short-lived credentials over static keys.

Example profile setup:

ini
1[profile prod-admin]
2region = us-east-1
3role_arn = arn:aws:iam::123456789012:role/ProdAdmin
4source_profile = base-sso

If your organization uses AWS IAM Identity Center, make sure interactive logins are refreshed before local script runs.

CI/CD and Non-Profile Runtimes

In CI, credentials often come from OIDC role assumption and not local profile files. Your code should allow that mode naturally by only forcing profile_name when needed.

Operationally useful checks:

  • print account id at startup
  • validate account against expected environment
  • require a confirmation flag for write operations in production
  • use least-privilege read and write roles separately

These controls reduce human error far more than any single credential trick.

Common Pitfalls

  • Depending on the default profile in scripts that touch multiple accounts.
  • Skipping STS identity checks before CloudFront mutations.
  • Reusing clients across account contexts and losing credential clarity.
  • Assuming local profile behavior matches CI credential behavior.
  • Using long-lived static access keys when role-based short-lived credentials are available.

Summary

  • Use explicit Boto3 sessions when account context must be controlled.
  • Verify identity with STS before destructive CloudFront operations.
  • Support both explicit profile arguments and AWS_PROFILE workflows.
  • Isolate each account with separate sessions and clients in multi-account scripts.
  • Prefer role assumption and short-lived credentials for stronger operational safety.

Course illustration
Course illustration

All Rights Reserved.