amazon-web-servicesregionaws-cli

Using aws cli, what is best way to determine the current region


Interactively, I can use "aws configure" to change or see the default region. Is there a "pwd" like function, documented or not that allows me to determine or confirm the current region mid-script ? Even if AWS_DEFAULT_REGION is not defined ? I want a script to run under a number of profiles. I can scrape from aws configure list, but is there something neater ?


Solution

  • 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:

    1. Command line --region option
    2. Value of AWS_DEFAULT_REGION environment variable
    3. 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]

    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.