Software Engineering

Methods to AssumeRole in Terraform LocalExec Provisioner Block

Methods to AssumeRole in Terraform LocalExec Provisioner Block
Written by admin


I wanted to execute a Terraform null_resource provisioner (local-exec) block to run an awscli command, however assume a job handed all the way down to it.

There was no apparent technique to cross the credentials to it, or assume a job instantly, so the next workaround did the trick:

AssumeRole and Cross LocalExec Provisioner Command

useful resource "null_resource" "start-appstream-fleet" {
  provisioner "local-exec" {
    interpreter = ["/bin/bash", "-c"]
    command = <<EOF
set -e
CREDENTIALS=(`aws sts assume-role 
  --role-arn ${native.workspace.position} 
  --role-session-name "start-appstream-fleet" 
  --query "[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]" 
  --output textual content`)

unset AWS_PROFILE
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID="$${CREDENTIALS[0]}"
export AWS_SECRET_ACCESS_KEY="$${CREDENTIALS[1]}"
export AWS_SESSION_TOKEN="$${CREDENTIALS[2]}"

aws appstream start-fleet --name sample-app-${var.surroundings}-fleet --region ${var.area} --output json
EOF
  }
}

The above code snippet runs 2 aws cli instructions. The primary is to get the credentials, that are then saved in surroundings variables, adopted by consuming them within the precise aws cli command on the backside.

The position that we wish to assume, has been setup within the native.workspace.position native variable.

It’s an ARN string that appears one thing like this:

"arn:aws:iam::<ACCOUNTID>:position/<PROJECT>-Pipeline-Function"

About the author

admin

Leave a Comment