你能在terraform子目录之间共享父资源吗?

时间:2017-11-17 18:00:00

标签: amazon-web-services aws-api-gateway terraform

我正在考虑使用这种terraform目录结构将应用程序分解为微服务:

/staging
  /global
  /service1
  /service2
/prod
  /global
  /service1
  /service2

假设我希望每个微服务都拥有自己的AWS Apigateway端点:

myurl.com/service1
myurl.com/service2

两个服务都可以是同一个父AWS apigateway资源的一部分:

#creates the api (a parent of all resources), 
resource "aws_api_gateway_rest_api" "api" {
  name        = "API root parent"
  description = "Contains all endpoints"
}

我的理解是每个顶级AWS REST api都是它自己的云端,因此我只需要其中一个用于我的所有微服务而不是每个微服务一个REST api。我想将REST api声明放在/global文件夹中,因为这将由所有微服务共享。

然后在service1子目录中,我将开始定义需要引用父代的资源:

resource "aws_api_gateway_resource" "service1" {
  rest_api_id = "${aws_api_gateway_rest_api.api.id}"
  parent_id   = "${aws_api_gateway_rest_api.api.root_resource_id}"
  path_part   = "service1"
}

但是service1子目录如何访问api资源,因为它没有在同一目录中定义?

我可能能够将现有资源的状态导入子目录,对于每个微服务子目录,但这看起来很乱。

更新:看起来AWS api网关只收取使用费用,所以我可以为每个子目录创建单独的rest api资源。但我可能仍然需要知道如何跨子文件夹收集资源变量,以便将相应的api部署阶段添加到公共自定义域。是否有一种技术或模式能够主要通过文件夹分离项目,但是能够在/global中提取变量并将它们粘合在一起,而这些变量并非特定于每个子目录?

1 个答案:

答案 0 :(得分:1)

你正在寻找的是{p> terraform中的远程状态 https://www.terraform.io/docs/state/remote.html https://www.terraform.io/docs/providers/terraform/d/remote_state.html

由于您在AWS中,因此可以使用S3作为远程状态的存储。

data "terraform_remote_state" "prod_service1" {
  backend = "s3"
  config {
    region = "eu-west-1"
    bucket = "uservices_terraform_bucket_name"
    key    = "/states/prod/service1/terraform.tfstate"

    access_key = "${var.aws_access_key}"
    secret_key = "${var.aws_secret_key}"
    token      = "${var.aws_session_token}"
  }
}

然后你可以使用

在另一个微服务中使用terraform状态的输出
"${data.terraform_remote_state.prod_service1.api_id}"