2

我一辈子都无法让它发挥作用。我需要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的,它仍然是空白的。所以这就像运行命令实际上并没有将导出值保存到我的控制台。

我究竟做错了什么?有没有人真的能够成功地AWS_PROFILE用 terragrunt 动态设置他们的?

4

2 回答 2

2

这就是我的解决方案。我有以下结构:

<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
}
...
于 2021-02-25T15:17:53.973 回答
2

这篇文章帮助我找出了我的问题:

我忘记了我的配置有 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
    }
    

希望这可以节省我今天浪费的所有时间!

于 2021-09-23T08:00:15.253 回答