gpt4 book ai didi

terraform - 是否可以将 terraform 工作区链接到 AWS 账户

转载 作者:行者123 更新时间:2023-12-03 14:10:41 29 4
gpt4 key购买 nike

如果一个人有两个 AWS 账户,一个用于开发,一个用于实时(例如)我知道可以使用 terraform 工作区来管理每个环境的状态。

但是,如果我将工作区从“开发”切换到“实时”,有没有办法告诉 terraform 它现在应该将状态应用于实时帐户而不是测试帐户?

我想到的一种容易出错的方法是交换我的 secret.auto.tfvars每次我切换工作区时文件,因为我假设当使用不同的访问 key (属于“实时”账户的那个)运行时,AWS 提供商将应用到该账户。但是,交换工作区并存在错误的凭据会非常容易,这将针对错误的环境运行更改。

我正在寻找一种几乎将工作区与 AWS 中的帐户 ID 链接的方法。

我确实找到了这个 https://github.com/hashicorp/terraform/issues/13700但它指的是已弃用的 env命令,this comment看起来特别有希望

更新

我在我离开的 GitHub 上找到了一些信息 this comment作为对先前评论的回复,该评论建议考虑模块而不是工作区,实际上表明工作区不太适合此任务。如果有人可以提供有关如何使用模块来解决同时维护“相同”基础架构的多个版本的问题的信息,我很想看看这如何改进工作空间的概念。

最佳答案

以下是您如何使用 Terraform 模块来构建指向不同 AWS 账户的实时与开发环境,但这些环境都具有/使用相同的 Terraform 代码。
这是您可以构建目录的(许多)方法之一;你甚至可以将这些模块放入他们自己的 Git 存储库中,但我会尽量不要把事情搞得太乱。在此示例中,您有一个简单的应用程序,它有 1 个 EC2 实例和 1 个 RDS 数据库。您可以在 modules/*/ 中编写所需的任何 Terraform 代码。子目录,确保参数化跨环境不同的任何属性。
然后在你的dev/live/目录,main.tf应该是一样的,而 provider.tfterraform.tfvars反射(reflect)特定环境的信息。 main.tf将调用模块并传入特定于环境的参数。

modules/
|-- ec2_instance/
|-- rds_db/
dev/
|-- main.tf # --> uses the 2 modules
|-- provider.tf # --> has info about dev AWS account
|-- terraform.tfvars # --> has dev-specific values
live/
|-- main.tf # --> uses the 2 modules
|-- provider.tf # --> has info about live/prod AWS account
|-- terraform.tfvars # --> has prod-specific values
当您需要计划/应用任一环境时,您可以放入适当的目录并在那里运行您的 TF 命令。

至于为什么这比使用 Terraform 工作区更受欢迎, TF docs解释得很好:

In particular, organizations commonly want to create a strong separation between multiple deployments of the same infrastructure serving different development stages (e.g. staging vs. production) or different internal teams. In this case, the backend used for each deployment often belongs to that deployment, with different credentials and access controls. Named workspaces are not a suitable isolation mechanism for this scenario.

Instead, use one or more re-usable modules to represent the common elements, and then represent each instance as a separate configuration that instantiates those common elements in the context of a different backend. In that case, the root module of each configuration will consist only of a backend configuration and a small number of module blocks whose arguments describe any small differences between the deployments.


BTW> Terraform 只是更改了 env workspace 的子命令当他们认为“env”有点太困惑时。
希望这可以帮助!

关于terraform - 是否可以将 terraform 工作区链接到 AWS 账户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51787160/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com