Using aws cli, what is best way to determine the current region
Taken from @RichVel's comment in this answer, to get the resolved region set from either AWS_DEFAULT_REGION
or the region in the aws config file (aws configure get region
only gives the value set in the config file) use:
aws configure list | grep region | awk '{print $2}'
Example:
with $AWS_DEFAULT_REGION
unset:
$ echo $AWS_DEFAULT_REGION
$ cat ~/.aws/config
[foo]
region = us-east-1
$ aws configure list | grep region | awk '{print $2}'
us-east-1
$ aws configure get region
us-east-1
with $AWS_DEFAULT_REGION
set:
$ export AWS_DEFAULT_REGION=us-west-2
$ echo $AWS_DEFAULT_REGION
us-west-2
$ cat ~/.aws/config
[foo]
region = us-east-1
$ aws configure list | grep region | awk '{print $2}'
us-west-2
$ aws configure get region
us-east-1
aws configure get region
will get you the current region at that point in your script.
If you are using a profile, then type aws configure get region --profile $PROFILE_NAME
.
The following gives the region actually used by the CLI regardless of whether environment variables are or are not set:
aws ec2 describe-availability-zones --output text --query 'AvailabilityZones[0].[RegionName]'
The region that will be used by the CLI is determined by the following order of precedence:
- Command line
--region
option - Value of
AWS_DEFAULT_REGION
environment variable - Region specified in the 'Current profile', which is determined by the following order of precedence
- Command line
--profile
option - Value of
AWS_PROFILE
environment variable - Otherwise profile is [default]
- Command line
Unfortunately using aws configure get region
only returns the region as specified by your 'Current profile', and ignores the AWS_DEFAULT_REGION
environment variable.
Rather than assuming any precedence rules, you can just use the CLI to make an actual API call and get the region from the result. The only call I could find that should always work was to aws ec2 describe-availability-zones
. Another advantage of this method is that you can specify --region
or --profile
options and still get the right answer.
Perhaps, AWS has not provide to get the current region. However, instead of getting the current region, They provide to get a current availability zone via an instance metadata. All availability zones include a current region, so you can determine the current region with you replace a part of the current availability zone in a script on the EC2 instance.
For example:
curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/\(.*\)[a-z]/\1/'