When using the AWS provider in Terraform, one of the methods of authentication is the shared credentials file. The notion of keeping a long-term AWS Access key and Secret key in here is unsettling, but it’s a great place to keep a short-term token issued by the AWS Security Token Service (STS). There are posts about automating the population of tokens with Linux commands and some with JQ but when supporting clients in a Windows environment who don’t operate Linux subsystems and aren’t comfortable parsing JSON, a little old-fashioned Windows scripting comes to the rescue.
The following bat file uses AWS CLI to issue an assume-role command to obtain a short-term token for authentication and parses the JSON response for the elements we need. It uses those elements to populate a shared credential file that we specify in our provider.tf file.
The following assumptions are made:
- Your AWS CLI installation is in the default location and your default credentials have authority to (hopefully, ONLY) run sts assume-role.
- This script is run from the same directory that contains your terraform.tfvars file.
- Your terraform.tfvars file contains variables with values for the profile name you’d like to use, the target AWS account ID and (in this case) the AWS partition (
awsfor commercial and
- Your target AWS account has an IAM role named TerraformAdmin that has all the permissions you need to provision infrastructure and a trust policy that allows you to assume it.