附加在另一个应用程序中创建的安全组

attach security group created in another app

folder structure.

我正在为 2 个在 terragrunt 中使用相同模块的独立应用程序创建以下内容

我的问题是如何在 app2 中引用为 app1 创建的安全组?

例如。

在应用程序 1 中 我可以将其引用为 security_groups = ["${aws_security_group.sec_group_A.id}"] 如何在 app2 中引用相同的安全组?

resource "aws_security_group" "sec_group_A" { 
  name   =   "sec_group_A"
  ...
  ...
  }

resource "aws_elb" "bar" {
  name               = "foobar-terraform-elb"
  security_groups    =  ["${aws_security_group.sec_group_A.id}"]
  ...
  ...
  }

我没有使用 terragrunt 的经验,但通常我会从项目根目录中的 "main.tf" 文件调用我的模块。下面是一个示例文件夹结构

.
├── main.tf
└── modules
    ├── app1
    │   ├── main.tf
    │   ├── outputs.tf
    │   └── variables.tf
    └── app2
        ├── main.tf
        ├── outputs.tf
        └── variables.tf

我的app1outputs.tf声明了一个安全组A输出

output "sec_group_a" { value = "${aws_security_group.sec_group_A}" }

然后我可以在项目根目录中的 main.tf 文件中调用此输出。这看起来像下面

module "app1" {
  source = "./modules/app1"
  ...
  // Pass in my variables
}

module "app2" {
  source = "./modules/app2"
  sec_group_A = "${module.app1.sec_group_A}"
  ...
  //Pass in the rest of my variables
}

最后,在 app2 模块中,您可以像调用任何其他变量一样调用它。

resource "aws_elb" "bar" {
  name               = "foobar-terraform-elb"
  security_groups    =  ["${var.sec_group_A.id}"]
  ...
  ...
  }

我在这里 https://www.terraform.io/docs/modules/index.html 阅读了有关模块的内容,以更好地了解它们是如何组合在一起的。

或者,只要 sec_group_A 在 app1 中声明为输出,您就可以从远程状态(如果您配置了一个)获取数据。参见 https://www.terraform.io/docs/providers/terraform/d/remote_state.html

在app2中,您可以:

data "aws_security_group" "other" {
    name = "sec_group_A"
}

然后使用ID:

resource "aws_elb" "bar" {
    name               = "foobar-terraform-elb"
    security_groups    =  ["${data.aws_security_group.other.id}"]
    ...
    ...
}

(使用 data 的警告是您是 运行 两个独立的 terraform applys - 一个配置创建组,其他配置引用组)。