我有一个标准的 2 层应用程序,正在部署到 AWS。作为此部署的一部分,我需要将配置文件写入 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
...
}
最佳答案
您可以使用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 实例,然后可以生成模板文件,最后将运行复制模板化配置的配置程序步骤。
请记住,您的应用程序现在将在数据库启动之前以及在有任何可用配置之前启动相当长的时间,因此请确保重试与数据库的连接(以及读取配置)是可以的)。
作为替代方案,您可能需要考虑一些配置模板结构,例如 confd或Consul Template 。
关于Terraform:如何将文件资源与实例和 RDS 解耦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47127290/