Terraform:如何将文件资源与实例和 RDS 解耦
Terraform: How to decouple a file resource from an instance and RDS
我有一个要部署到 AWS 的标准 2 层应用程序。作为此部署的一部分,我需要将配置文件写入 EC2 实例。此配置文件包含数据库 (RDS) 设置。现在我将此文件定义为 EC2 实例中的提供程序。所以 Terraform 所做的是它甚至不会开始构建 EC2 实例,直到 RDS 达到 100% 并且 运行(这大约需要 5 分钟)。这让事情变得很慢。
有没有办法可以在 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 or Consul Template。
我有一个要部署到 AWS 的标准 2 层应用程序。作为此部署的一部分,我需要将配置文件写入 EC2 实例。此配置文件包含数据库 (RDS) 设置。现在我将此文件定义为 EC2 实例中的提供程序。所以 Terraform 所做的是它甚至不会开始构建 EC2 实例,直到 RDS 达到 100% 并且 运行(这大约需要 5 分钟)。这让事情变得很慢。
有没有办法可以在 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 or Consul Template。