【问题标题】:Terraform: How to decouple a file resource from an instance and RDSTerraform:如何将文件资源与实例和 RDS 分离
【发布时间】:2018-04-18 01:06:27
【问题描述】:

我有一个要部署到 AWS 的标准 2 层应用程序。作为此部署的一部分,我需要将配置文件写入 EC2 实例。此配置文件包含数据库 (RDS) 设置。现在,我将此文件定义为 EC2 实例中的提供程序。所以 terraform 所做的是,在 RDS 100% 启动并运行(大约需要 5 分钟)之前,它甚至不会开始构建 EC2 实例。这会使事情变得非常缓慢。

有没有办法可以在 EC2 实例的上下文之外创建文件资源,以便并行创建 RDS 实例和 EC2 实例?还是我应该在这里使用另一种模式?

这里有一些代码位:

resource "aws_instance" "foo" {
  ami           = "${lookup(var.AMIS, var.AWS_REGION)}"
  instance_type = "t2.micro"
    //setup the config file
    provisioner "file" {
      destination = "foo/config.json"
      content     = "${data.template_file.config_file.rendered}"
 ...
 }

data "template_file" "config_file" {
  template = "${file("config.json.tmpl")}"
  vars {
    mysql_pass = "${var.MYSQL_PASSWORD}"
    mysql_addr = "${aws_db_instance.mysql.endpoint}"
  }
}


resource "aws_db_instance" "mysql" {
 allocated_storage    = 20
 ...
}

【问题讨论】:

    标签: terraform terraform-template-file


    【解决方案1】:

    您可以使用null_resource 运行将配置复制到实例的配置程序步骤。

    在您的情况下,您可能会使用以下内容:

    resource "null_resource" "db_config" {
      # Recreating the instance requires the config to be redeployed
      triggers {
        instance_ids = "${aws_instance.foo.id}"
      }
    
      connection {
        host = "${aws_instance.cluster.public_ip}"
      }
    
      provisioner "file" {
          destination = "foo/config.json"
          content     = "${data.template_file.config_file.rendered}"
      }
    }
    

    这将允许同时创建您的 EC2 和 RDS 实例,然后可以生成模板文件,最后将运行用于复制模板化配置的配置程序步骤。

    请记住,您的应用程序现在将在数据库启动之前以及它有任何可用配置之前启动相当长的时间,因此请确保可以重试与数据库的连接(以及读取配置) )。

    作为替代方案,您可能需要考虑一些配置模板结构,例如confdConsul Template

    【讨论】:

    • 谢谢,这就是我所缺少的信息。今晚晚些时候我会试一试,然后标记解决方案。
    猜你喜欢
    • 1970-01-01
    • 2023-01-07
    • 2020-11-18
    • 2018-09-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    相关资源
    最近更新 更多