Terraform setup of postgres conf files (pg_hba_conf + postgresql.conf) via User Data on AWS ec2 instance

amazon ec2postgresqlterraform

I am setting up a cheap postgres server on amazon ec2, using Terraform.

I know I can add a User Data file when setting up a ec2 instance.
I know that with terraform, I can provide that User Data script file, using the file(..) function. So far so good.

My problem is I would like to also automate the final steps of pg setup, i.e. modifying the pg_hba.conf and postgresql.conf files during that same user data script's execution. Is that possible?

I.e. If I create a pghbaconftpl.conf file alongside my other terraform files, can I do cat pghbaconftpl.conf > /correct/path/to/pg_hba.conf in the ec2 User Data script and expect it to work? I don't see how that would work. :-/

In general is it possible to inject other script files that can be launch from user data script? If so, how?

Any help appreciated.

Best Answer

You can use the templatefile function to create a template of the required file.

Alternatively, you can use the remote-exec to run whatever you want on the remote file

The remote-exec provisioner invokes a script on a remote resource after it is created. This can be used to run a configuration management tool, bootstrap into a cluster, etc. To invoke a local process, see the local-exec provisioner instead. The remote-exec provisioner requires a connection and supports both ssh and winrm.

So you could do

... 
 provisioner "remote-exec" {
    inline = [
       "cat pghbaconftpl.conf > /correct/path/to/pg_hba.conf"
    ]
  }

or whatever else you want to run on the remote instance. You can point to a shell script, copy a file from your terraform repo, template it to a location on the remote instance and run it.

The two approaches will depend on what exactly you're trying to do.

Related Question