我有一个terraform中的资源,创建后需要在其上运行AWS命令。但我希望它使用与terraform相同的AWS凭据运行。AWS提供商正在使用一个配置文件,然后使用该配置文件来扮演一个角色:
provider "aws" {
profile = "terraform"
assume_role {
role_arn = local.my_arn
}
}
我曾希望地形能暴露出必要的环境变量,但事实并非如此。最好的方法是什么?
您可以通过AWS配置使用角色假设吗?文档:在AWS CLI 中使用IAM角色
~/.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"
}
}