我一辈子都无法做到这一点。我需要设置AWS_PROFILE
环境变量,以使terragrunt正常运行。如果我运行:
export AWS_PROFILE=myprofile; terragrunt plan
这会起作用,但这不是我想要的,我只想运行:
terragrunt plan
并让它自动选择我应该使用的正确aws配置文件。这是我所拥有的:
generate "provider" {
path = "provider.tf"
if_exists = "overwrite_terragrunt"
contents = <<EOF
provider "aws" {
region = "${local.region}"
profile = "${trimspace(run_cmd("bash", "${get_parent_terragrunt_dir()}/../../set_profile.sh",local.profile))}"
}
EOF
}
remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite"
}
config = {
...
...
region = local.region
profile = local.profile
...
...
}
}
它总是给我带来错误:
Error finding AWS credentials (did you set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables?): NoCredentialProviders: no valid providers in chain. Deprecated.
For verbose messaging see aws.Config.CredentialsChainVerboseErrors
set_profile.sh
脚本如下:
#!/bin/bash
VALUE=$(echo $1 | sed $'s/r//')
export AWS_PROFILE=$VALUE
echo "$AWS_PROFILE"
如果我回显我的AWS_PROFILE
,它仍然是空白的。因此,run命令实际上并没有将导出值保存到我的控制台。
我做错了什么?有人真的能够成功地用terragrunt动态设置他们的AWS_PROFILE
吗?
这是我的解决方案。我有以下结构:
<project>
|-- <region1>
|-- <region2>
|-- account.hcl
terragrunt.hcl
在account.hcl
中
locals {
aws_profile_name = "myprofile"
}
主terragrunt.hcl
locals {
# Automatically load account-level variables
account_vars = read_terragrunt_config(find_in_parent_folders("account.hcl"))
aws_profile = local.account_vars.locals.aws_profile_name
}
terraform {
extra_arguments "aws_profile" {
commands = [
"init",
"apply",
"refresh",
"import",
"plan",
"taint",
"untaint"
]
env_vars = {
AWS_PROFILE = "${local.aws_profile}"
}
}
}
remote_state {
...
config = {
...
profile = "${local.aws_profile}"
}
}
generate "provider" {
...
contents
contents = <<EOF
provider "aws" {
profile = "${local.aws_profile}"
}
EOF
}
...
这篇文章帮助我解决了我的问题:
我忘记了我的配置有2个AWS连接来设置的事实
- 后端
- 提供者
因此,AWS配置文件必须设置两次:
remote_state
中的remote_state { backend = "s3" config = { ... profile = local.profile ... } }
- 在
provider.tf
中generate "provider" { path = "provider.tf" if_exists = "skip" contents = <<EOF provider "aws" { ... profile = "${local.profile}" ... } EOF }
希望这能节省我今天浪费的所有时间!