如何在本地执行配置器中从Terraform继承AWS凭证

时间:2019-11-06 00:19:03

标签: terraform aws-cli terraform-provider-aws

在terraform中有一个资源,在创建它后,需要在其上运行AWS命令。但是我希望它使用与terraform使用的相同的AWS凭证运行。 AWS提供程序正在使用一个配置文件,然后将其用作角色:

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

我曾希望terraform能够公开必要的环境变量,但事实并非如此。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以通过AWS配置使用角色假设吗? 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}"
  }
}

如果不能这样做,这是一种非常麻烦的方式。我不特别推荐这种方法,但是它可以工作。这取决于jq,但您也可以使用其他方法来解析aws sts assume-role命令的输出

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"
  } 
}