2

假设我正在使用 Terraform 在 AWS 中预置两台机器:

  • 运行 NodeJS 的 EC2 机器
  • 一个 RDS 实例

NodeJS代码如何获取RDS实例的地址?

4

2 回答 2

1

你在这里有几个选择。最简单的一种是在 Route53 中为数据库创建一条 CNAME 记录,然后在您的应用程序中始终指向该 CNAME。

一个基本示例如下所示:

resource "aws_db_instance" "mydb" {
  allocated_storage    = 10
  engine               = "mysql"
  engine_version       = "5.6.17"
  instance_class       = "db.t2.micro"
  name                 = "mydb"
  username             = "foo"
  password             = "bar"
  db_subnet_group_name = "my_database_subnet_group"
  parameter_group_name = "default.mysql5.6"
}

resource "aws_route53_record" "database" {
   zone_id = "${aws_route53_zone.primary.zone_id}"
   name = "database.example.com"
   type = "CNAME"
   ttl = "300"
   records = ["${aws_db_instance.default.endpoint}"]
}

替代选项包括在创建实例或将其传递给Consul并使用 Consul 模板控制应用程序使用的配置时,endpoint从 获取输出aws_db_instance并将其传递到用户数据脚本。

于 2016-05-07T18:07:44.883 回答
0

您可以尝试Sparrowform - 一个基于 Terraform 的实例的轻量级配置工具,它能够创建 Terraform 资源清单和配置相关主机,传递所有必要的数据:

$ terrafrom apply # bootstrap infrastructure

$ cat sparrowfile # this scenario
                  # fetches DB address from terraform cache 
                  # and populate configuration file 
                  # at server with node js code:

#!/usr/bin/env perl6

use Sparrowform;

$ sparrowfrom --ssh_private_key=~/.ssh/aws.pem --ssh_user=ec2 # run provision tool

my $rdb-adress; 

for tf-resources() -> $r {
  my $r-id = $r[0]; # resource id
  if ( $r-id 'aws_db_instance.mydb') {
    my $r-data = $r[1];                
    $rdb-address = $r-data<address>;
    last;
  }
}

# For instance, we can 
# Install configuration file
# Next chunk of code will be applied to  
# The server with node-js code: 

template-create '/path/to/config/app.conf', %(
  source => ( slurp 'app.conf.tmpl' ),
  variables => %(
    rdb-address => $rdb-address
  ),
);

# sparrowform --ssh_private_key=~/.ssh/aws.pem --ssh_user=ec2 # run provisioning 

PS。披露 - 我是工具作者

于 2018-01-26T20:57:24.627 回答