Sometimes you want to retrieve EC2 insntances' region information. You can query that information through instance metadata(169.254.169.254). ``` $ curl --silent http://169.254.169.254/latest/dynamic/instance-identity/document { "privateIp" : "172.31.2.15", "instanceId" : "i-12341ee8", "billingProducts" : null, "instanceType" : "t2.small", "accountId" : "1234567890", "pendingTime" : "2015-11-03T03:09:54Z", "imageId" : "ami-383c1956", "kernelId" : null, "ramdiskId" : null, "architecture" : "x86_64", "region" : "ap-northeast-1", # <- region "version" : "2010-08-31", "availabilityZone" : "ap-northeast-1c", "devpayProductCodes" : null } ``` Response's JSON has a `region` key, so if you just want to get region, filter the key with `jq`. ``` $ sudo yum install -y jq $ curl --silent http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region ap-northeast-1 ``` ## Usecase : set aws-cli's region Even if you launch an EC2 instance with IAM role, you can't run commands without supplying region info. Otherwise, you'll encounter errors as follows. ``` $ aws ec2 describe-vpcs You must specify a region. You can also configure your region by running "aws configure". ``` Here's how to set aws-cli's region. First, check the curren settings. ``` $ aws configure list Name Value Type Location ---- ----- ---- -------- profile None None access_key ****************GVKA iam-role secret_key ****************bll+ iam-role region None None ``` `region` is not set. Now pass metadata's region to `aws configure set region` command. ``` $ aws configure set region `curl --silent http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region` $ aws configure get region ap-northeast-1 $ aws configure list Name Value Type Location ---- ----- ---- -------- profile None None access_key ****************GVKA iam-role secret_key ****************bll+ iam-role region ap-northeast-1 config-file ~/.aws/config $ cat ~/.aws/config [default] region = ap-northeast-1 ``` ### UserData To configure API region, just add following code to you UserData. ``` #!/bin/bash yum install -y jq REGION=`curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq .region -r` sudo -u ec2-user aws configure set region $REGION ```