Docker on Amazon Web Services
上QQ阅读APP看书,第一时间看更新

Configuring the AWS CLI to use a named profile

With the configuration in place, you no longer have a default profile in place, so running the AWS CLI will return the same output. To use a named profile, you have two options available:

  • Specify the profile name using the --profile flag in the AWS CLI command.
  • Specify the profile name in an environment variable called AWS_PROFILE. This is my preferred mechanism and I will assume that you are taking this approach throughout this book.

The preceding code demonstrates using both of these approaches:

> aws ec2 describe-vpcs --profile docker-in-aws
Enter MFA code for arn:aws:iam::385605022855:mfa/justin.menga: ******
{
"Vpcs": [
{
"VpcId": "vpc-f8233a80",
"InstanceTenancy": "default",
"CidrBlockAssociationSet": [
{
"AssociationId": "vpc-cidr-assoc-32524958",
"CidrBlock": "172.31.0.0/16",
"CidrBlockState": {
"State": "associated"
}
}
],
"State": "available",
"DhcpOptionsId": "dopt-a037f9d8",
"CidrBlock": "172.31.0.0/16",
"IsDefault": true
}
]
}
> export AWS_PROFILE=docker-in-aws
> aws ec2 describe-vpcs --query Vpcs[].VpcId
[
"vpc-f8233a80"
]

In the preceding example, notice that when you run first run the aws command, you are prompted for your MFA token, however when you next run the command, you are not prompted. This is because, by default, the temporary session credentials obtained from assuming a role are valid for one hour, and the AWS CLI caches the credentials so that you reuse them without having to refresh the credentials on each command execution. Of course, after one hour, you will be prompted once again for your MFA token, given that the temporary session credentials will have expired.

One other interesting point to note in the preceding code is the use of the --query flag in the last command example. This allows you to specify a JMESPath query, which is a query language that can be used to query JSON data structures. The AWS CLI outputs JSON by default, so you can use queries to extract specific information from the AWS CLI output. Throughout this book, I will frequently use examples of these queries, and you can read more about the JMESPath query language at http://jmespath.org/tutorial.html.