Q:

Automatically provisioning an instance to connect to a database cluster endpoint

I am looking for a way to provision an instance with a configuration file that contains the endpoints to connect to a database cluster in an automatic way, using terraform. I am using a aws_rds_cluster resource, from which I can get the endpoint using the expression aws_rds_cluster.my-cluster.endpoint. Then, I would like to provision machines instantiated with an aws_instance resource so that the value of that expression is stored in the file /DBConfig.sh.
The content of the DBConfig.sh file would look like this :
#!/bin/bash

ENDPOINT=<$aws_rds_cluster.my-cluster.endpoint$>
READER_ENDPOINT=<$aws_rds_cluster.my-cluster.reader_endpoint$>

Truth be told, once I successfully reach that point, I'd like to be able to do the same thing for machines created by a aws_launch_configuration resource.
Is this something that can be done with terraform? If not, what other tools can I use to achieve this kind of automation? Thanks for your help!

A:

There are few ways which can achieve that. I think all of the would involve user_data.
For example, you could have aws_instance with the user_data as follows:
resource "aws_instance" "web" {

  # other atrributes
  
  user_data = <<-EOL
  #!/bin/bash
  
  cat >./DBConfig.sh <<-EOL2
  #!/bin/bash
  ENDPOINT=${aws_rds_cluster.my-cluster.endpoint}
  READER_ENDPOINT=${aws_rds_cluster.my-cluster.reader_endpoint}
  EOL2
  
  chmod +x ./DBConfig.sh
  
  EOL
}

The above will launch an istance which will have DBConfig.sh with resolved values of the endpoints in its root (/) directory.

