如何在 terraform 中管理三个(每个环境)用户数据文件?

How do I manage three (per-environment) user data files in terraform?

我有三个用于三种不同环境的特定用户数据文件。根据用户在 env(环境)变量上的输入,我们必须为 aws_instance terraform 资源选择一个用户数据文件。

variable "env" {
   description = "choose env between dev | prod | qa "
}

以下是三个用户数据文件:

  1. user_data_dev.sh:

    #!/bin/bash
    DOMAIN = "testing.dev.xxxx.com"
    PORT = "8080"
    
  2. user_data_prod.sh

    #!/bin/bash
    DOMAIN = "testing.prod.xxxx.com"
    PORT = "8080"
    
  3. user_data_qa.sh

    #!/bin/bash
    DOMAIN = "testing.qa.xxxx.com"
    PORT = "8080"
    
    resource "aws_instance" "server" {
      ami = "ami-123456"
      instance_type = "t2.medium"
      availability_zone = "us-east-1"
      user_data = "${template_file.user_data_graphite.rendered}"
      root_block_device {
        delete_on_termination = true
        volume_size = "${var.volume_size}"
        volume_type = "${var.volume_type}"
      }
      tags {
        Name = "domain_testing"
    }
    

除非您过度简化问题中的问题,否则您正在为静态文件创建模板而不是实际将变量传递给它们。

因为这些静态文件似乎只因该硬编码域而异,所以您应该使用类似以下内容动态呈现它们:

用户-data.sh.tpl

#!/usr/bin/env bash
DOMAIN="${domain}"
PORT="8080"

instance.tf

variable "environment" {}

variable "environment_domains" {
  default = {
    "dev"  = "testing.dev.xxxx.com"
    "qa"   = "testing.prod.xxxx.com"
    "prod" = "testing.qa.xxxx.com"
  }
}

data "template_file" "user_data" {
  template = "${file("${path.module}/user-data.sh.tpl")}"

  vars {
    domain = "${lookup(var.environment_domains, var.environment)}"
  }
}


resource "aws_instance" "server" {
  ...
  user_data = "${template_file.user_data.rendered}"
  ...
}

给定一个环境,Terraform 然后会从 environment_domains 映射中查找与环境匹配的域,然后将其替换到模板的渲染输出中。

如果您确实想为每个环境使用单独的模板文件,您可以按环境名称查找合适的文件:

data "template_file" "user_data" {
  template = "${file("${path.module}/user-data-${var.env}.sh")}"
  ...
}

resource "aws_instance" "server" {
  user_data = "${template_file.user_data.rendered}"
  ...
}