在 Terraform 中对多个环境使用相同的设置

在 Terraform 中对多个环境使用相同的设置

我需要使用 Terraform 在 AWS 上构建多个环境。大多数设置适用于所有环境 - 如何避免代码重复?

resource "aws_elastic_beanstalk_application" "app" {
  name = "${var.appName}"
  description = ""
} 

resource "aws_elastic_beanstalk_environment" "app_env" {
  name                = "${var.envName}"
  application         = "${aws_elastic_beanstalk_application.app.name}"
  solution_stack_name = "64bit Amazon Linux 2017.09 v2.8.4 running Multi-container Docker 17.09.1-ce (Generic)"

  #the same for all envs
  setting { 
    namespace = "aws:ec2:vpc"
    name      = "VPCId"
    value     = "vpc-myVpcId"
  },
   #changes for each env
   setting {
        namespace =  "aws:elasticbeanstalk:application:environment",
        name =  "SERVICE_NAME",
        value =  "${var.ServiceName}"
    },

  resource "aws_elastic_beanstalk_application" "app" {
  name = "${var.appName}"
  description = ""
} 

resource "aws_elastic_beanstalk_environment" "app_env_2" {
  name                = "${var.envName}"
  application         = "${aws_elastic_beanstalk_application.app.name}"
  solution_stack_name = "64bit Amazon Linux 2017.09 v2.8.4 running Multi-container Docker 17.09.1-ce (Generic)"

  #the same for all envs
  setting { 
    namespace = "aws:ec2:vpc"
    name      = "VPCId"
    value     = "vpc-myVpcId"
  },
   #changes for each env
   setting {
        namespace =  "aws:elasticbeanstalk:application:environment",
        name =  "SERVICE_NAME",
        value =  "${var.ServiceName_2}"
    },


}  

答案1

有两种方法可以做到这一点。

  1. 使用环境变量,如下所示:变量
  2. 使用提供默认变量的全局模块模块

两者各有利弊。环境变量让您可以自由地不编写更多代码,但特定于运行时环境。

嗯,模块,需要编写一个模块:)

相关内容