如何使用 Terraform 模块进行代码重用? [英] How to use Terraform modules for code re-use?

查看:35
本文介绍了如何使用 Terraform 模块进行代码重用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Terraform v0.12.x

Terraform v0.12.x

我以为我在阅读文档后理解了用于代码重用的 Terraform 模块,但显然不是.

I thought I understood Terraform modules for code re-use after reading the docs, but apparently not.

说我要搭建一个目标组+EC2实例基础设施.我有这个目录结构.

Say I want to build a target group+EC2 instance infrastructure. I have this directory structure.

/terraform
/terraform/green.tf
/terraform/blue.tf
/terraform/module_ec2/ec2.tf
/terraform/module_tg/tg.tf

例如,/terraform/module_ec2/ec2.tf 有这个

resource "aws_instance" "ec2" {
  ami               = var.ami
  availability_zone = var.availability_zone
  ....
}

/terraform/module_tg/tg.tf

resource "aws_lb_target_group" "tg" {
  name = var.tg_name
  ...
}

我希望blue.tfgreen.tf 使用module_tgmoodule_ec2 构建各自的目标群体+EC2 基础设施 并将每个模块所需的相应键/值对传递给它们.我该怎么做,也就是说,blue.tfgreen.tf 的内容是什么?

I want blue.tf and green.tf to build their respective target group+EC2 infrastructure by using module_tg and moodule_ec2 and just passing to them the respective key/value pairs each module needs. How can I do this, that is, what would be contents of blue.tf and green.tf?

推荐答案

考虑沿生命周期边界分解您的 terraform 配置.一组资源的生命周期是从运行 terraform apply 开始到运行 terraform destroy 结束的时间.

Consider breaking up your terraform configurations along lifecycle boundaries. The lifecycle of a set of resources is the time starting when you run terraform apply and ending when you run terraform destroy.

在您的示例和评论中,您提出了一个 EBS 卷,它应该可用于绿色和蓝色堆栈.EBS 卷或任何其他比任一堆栈寿命更长的依赖项都应位于单独的文件夹中.

In your example and comments, you bring up an EBS volume which should be available to both green and blue stacks. The EBS volume or any other dependencies that outlive either stack should be in a separate folder.

要从每个堆栈访问 EBS 卷或其他长期依赖项的详细信息,有几个选项:

To access details of the EBS volume or other longer-lived dependencies from each of your stacks there are a few options:

  1. 使用 terraform_remote_state 数据源指向您的依赖项配置的远程状态.
  2. 采用命名约定,以便可以使用特定数据源发现依赖项
  3. 第 1 项的变体,在您的依赖项配置的子文件夹中创建一个输出模块,其中包含一个 terraform_remote_state 并仅公开配置的输出.
  1. use a terraform_remote_state data source pointed at the remote state of your dependencies configuration.
  2. employ a naming convention so the dependencies can be discovered using specific data sources
  3. a variation on item 1, create an output module in a subfolder of your dependency configuration which includes a terraform_remote_state and exposes only the outputs of the configuration.

这篇关于如何使用 Terraform 模块进行代码重用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆