Sub topic 6
Setting and inspecting the Region from the CLI and SDK
This chapter assumes you have an AWS account, the AWS CLI v2 installed, and credentials configured. It also assumes you can run commands in a terminal and read basic Python. Most "my resource disappeared" problems come from a Region mismatch, so this chapter covers where the Region comes from and how to check it.
Why the Region setting matters
Most AWS API calls go to a Regional endpoint such as ec2.eu-west-1.amazonaws.com. The Region you configure decides which endpoint receives your request. A call to the wrong Region does not fail in an obvious way. A list command returns an empty result, because your resources live in a different Region.
The CLI and the SDKs do not ask you for a Region on every call. They look for one in several places and use the first match. Knowing that order lets you predict which Region a command will use.
How the Region is resolved
The AWS CLI v2 checks these sources in order. The first one that supplies a value wins.
- The
--regionoption on the command. - The
AWS_REGIONenvironment variable (read by SDKs, and by recent CLI v2 versions). - The
AWS_DEFAULT_REGIONenvironment variable. - The
regionsetting in the active profile in~/.aws/config. - The Region from instance metadata, when running on EC2 and no other source is set. (This applies to the SDKs and to the CLI v2 on EC2.)
If none of these sources gives a Region, the CLI reports an error for most services. Some SDKs fall back to a default such as us-east-1. Do not rely on that fallback.
Setting the Region
In the config file
The usual way to set a long-lived default is aws configure. It writes to ~/.aws/config.
aws configure set region eu-west-1
aws configure set region us-east-2 --profile stagingThe resulting file looks like this:
[default]
region = eu-west-1
[profile staging]
region = us-east-2Profiles let you keep one Region per environment. Select a profile with --profile staging or the AWS_PROFILE environment variable.
With an environment variable
An environment variable overrides the config file for the current shell. This is useful for a short session.
export AWS_DEFAULT_REGION=eu-west-1
aws configure get region
aws ec2 describe-availability-zones --query "AvailabilityZones[].ZoneName" --output textaws configure get region prints the Region from the profile and environment sources it can see. Run it after you set the variable to confirm the value. The last command lists the zone names in that Region, which proves the call went where you intended.
On a single command
Use --region when you want one call to go somewhere else without changing anything else.
aws ec2 describe-instances --region ap-southeast-2 \
--query "Reservations[].Instances[].InstanceId" --output textThis is the safest form in scripts, because the Region is visible in the command itself.
Inspecting what the CLI will use
Before you create anything, check the Region. Three commands help.
aws configure list
aws configure get region
aws sts get-caller-identityaws configure list shows each setting, its value, and where it came from. The Type column tells you whether the Region came from env, config-file, or manual (a command option). This is the fastest way to find out why the CLI is using an unexpected Region.
aws sts get-caller-identity shows the account and principal. It does not show a Region, but it confirms you are in the account you expect. Check both account and Region before you run a destructive command.
Listing Regions and zones
Two calls answer "where can I work?"
aws ec2 describe-regions --query "Regions[].RegionName" --output textThis lists the Regions enabled for your account. Opt-in Regions that you have not enabled are left out.
To see the opt-in Regions you have not enabled, include all Regions and filter on the opt-in status:
aws ec2 describe-regions --all-regions \
--query "Regions[?OptInStatus=='not-opted-in'].RegionName" \
--output textRegions that are enabled by default report opt-in-not-required. Enabled opt-in Regions report opted-in.
To see the zones in one Region, with their IDs:
aws ec2 describe-availability-zones --region us-east-1 \
--query "AvailabilityZones[].[ZoneName,ZoneId,State,ZoneType]" \
--output tableThe output pairs each zone name (such as us-east-1a) with a zone ID (such as use1-az1). The name-to-ID mapping is specific to your account, so use IDs when you coordinate placement across accounts. A later chapter covers this in detail.
Setting the Region in the SDK for Python (boto3)
boto3 uses a similar lookup. A Region passed in code wins over the environment and config file.
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
response = ec2.describe_availability_zones(
Filters=[{"Name": "zone-type", "Values": ["availability-zone"]}]
)
for az in response["AvailabilityZones"]:
print(az["ZoneName"], az["ZoneId"], az["State"])The zone-type filter keeps standard Availability Zones and leaves out Local Zones and Wavelength Zones, which this API also returns when they are enabled.
Checking the Region a client actually uses
Every boto3 client records the Region it resolved. Print it to confirm.
import boto3
session = boto3.Session()
print("Session region:", session.region_name)
s3 = session.client("s3")
print("S3 client region:", s3.meta.region_name)
print("S3 endpoint:", s3.meta.endpoint_url)
ec2 = session.client("ec2", region_name="eu-central-1")
print("EC2 client region:", ec2.meta.region_name)session.region_name is None when no source supplies a Region. A client created with no Region then raises NoRegionError for services that need one. Passing region_name to client() overrides the session for that client only.
Creating a session per Region
When code works across Regions, create one client per Region and keep the Region in a variable you can log.
import boto3
def count_instances(region: str) -> int:
ec2 = boto3.client("ec2", region_name=region)
paginator = ec2.get_paginator("describe_instances")
total = 0
for page in paginator.paginate():
for reservation in page["Reservations"]:
total += len(reservation["Instances"])
return total
for region in ["us-east-1", "eu-west-1", "ap-southeast-2"]:
print(region, count_instances(region))The paginator handles results that span several pages, so the count is complete.
Placing a resource in a specific zone
Once the Region is correct, you can pin a resource to a zone. Using the zone ID keeps the placement on the same physical zone across accounts.
aws ec2 create-subnet \
--vpc-id vpc-0123456789abcdef0 \
--cidr-block 10.0.1.0/24 \
--availability-zone-id use1-az1The VPC ID is a placeholder. Replace it with a VPC from the Region you have set. A VPC belongs to one Region, so the subnet call fails if the VPC is in another Region than your CLI is using.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `You must specify a region` or `NoRegionError` | No source supplies a Region | Run `aws configure set region <name>` or pass `--region` |
| Empty list although you created resources | The command ran in a different Region | Run `aws configure list`, then repeat with `--region` |
| `InvalidParameterValue` on a zone or subnet | The zone does not exist in the Region in use | List zones in that Region and check the name |
| `AuthFailure` or `InvalidClientTokenId` on a new Region | Opt-in Region not enabled, or credentials not valid there | Enable the Region in the account settings, then retry |
| A script works on your laptop but not in CI | CI has no config file, so no Region is set | Set `AWS_REGION` in the CI environment or pass `--region` |
| Console shows resources, CLI does not | Console Region selector differs from CLI Region | Match the two, then compare again |
Habits that prevent Region mistakes
- Pass
--regionexplicitly in scripts, so a reader sees where the call goes. - Use one named profile per account and Region pair for work you repeat.
- Run
aws configure listbefore any command that creates or deletes resources. - In code, log the Region from
client.meta.region_nameat startup. - Do not hard-code a Region you did not choose. Read it from configuration.
Exercises
Exercise
You run aws ec2 describe-instances and get an empty list, but you launched an instance an hour ago in the console. The CLI profile has region = us-east-1. Name two ways to find out which Region the CLI used, and one way to check the Region of the instance.
Show answer
Run aws configure list to see the Region value and its source, or aws configure get region. Also check whether AWS_REGION or AWS_DEFAULT_REGION is exported with env | grep AWS_, since an environment variable overrides the profile. To check the instance, read the Region selector in the console, or search other Regions with aws ec2 describe-instances --region <name>. The usual cause is that the console and the CLI point at different Regions.
Exercise
A Python script calls boto3.client("ec2") with no region_name. It works on your laptop and raises NoRegionError in a container. Why, and how do you fix it?
Show answer
Your laptop has a Region in ~/.aws/config or an environment variable, and the container has neither. Fix it by passing region_name to the client, or by setting AWS_REGION in the container environment. Printing boto3.Session().region_name shows None when no Region is found.
Exercise
Write one command that lists the names and IDs of the zones in eu-west-1, without changing your default Region.
Show answer
aws ec2 describe-availability-zones --region eu-west-1 --query "AvailabilityZones[].[ZoneName,ZoneId]" --output table. The --region option overrides the profile and environment for this one call.