0
votes

I have a resource in terraform that I need to run an AWS command on after it is created. But I want it to run using the same AWS credentials that terraform is using. The AWS provider is using a profile which it then uses to assume a role:

provider "aws" {
  profile = "terraform"
  assume_role {
    role_arn = local.my_arn
  }
}

I had hoped that terraform would expose the necessary environment variables, but that doesn't seem to be the case. What is the best way to do this?

1

1 Answers

1
votes

Could you use role assumption via the AWS configuration? Doc: Using an IAM Role in the AWS CLI

~/.aws/config:

[user1]
aws_access_key_id =  ACCESS_KEY
aws_secret_access_key = SECRET_KEY

[test-assume]
role_arn = arn:aws:iam::123456789012:role/test-assume
source_profile = user1

main.tf:

provider "aws" {
  profile = var.aws_profile
  version = "~> 2.0"
  region  = "us-east-1"
}

variable "aws_profile" {
  default = "test-assume"
}

resource "aws_instance" "instances" {
  ami           = "ami-009d6802948d06e52"
  instance_type = "t2.micro"
  subnet_id     = "subnet-002df68a36948517c"

  provisioner "local-exec" {
    command = "aws sts get-caller-identity --profile ${var.aws_profile}"
  }
}

If you can't, here's a really messy way of doing it. I don't particularly recommend this method, but it will work. This has a dependency on jq but you could also use something else to parse the output from the aws sts assume-role command

main.tf:

provider "aws" {
  profile = var.aws_profile
  version = "~> 2.0"
  region  = "us-east-1"
  assume_role {
    role_arn = var.assume_role
  }
}

variable "aws_profile" {
  default = "default"
}

variable "assume_role" {
  default = "arn:aws:iam::123456789012:role/test-assume"
}

resource "aws_instance" "instances" {
  ami           = "ami-009d6802948d06e52"
  instance_type = "t2.micro"
  subnet_id     = "subnet-002df68a36948517c"

  provisioner "local-exec" {
    command = "aws sts assume-role --role-arn ${var.assume_role} --role-session-name Testing --profile ${var.aws_profile} --output json > test.json && export AWS_ACCESS_KEY_ID=`jq -r '.Credentials.AccessKeyId' test.json` && export AWS_SECRET_ACCESS_KEY=`jq -r '.Credentials.SecretAccessKey' test.json` && export AWS_SESSION_TOKEN=`jq -r '.Credentials.SessionToken' test.json` && aws sts get-caller-identity && rm test.json && unset AWS_ACCESS_KEY_ID && unset AWS_SECRET_ACCESS_KEY && unset AWS_SESSION_TOKEN"
  } 
}