Search code examples
amazon-web-servicesterraformamazon-elastic-beanstalkamazon-rdsterraform-provider-aws

Set rds endpoint as an environment variable to Elastic Beanstalk in terraform


I have the following terraform script which creates Elastic Beanstalk with rds:

resource "aws_elastic_beanstalk_application" "elb_app" {
  name = "my-app"

}


resource "aws_elastic_beanstalk_environment" "elb_env" {
  name                = "my-env"
  application         = aws_elastic_beanstalk_application.elb_app.name
  solution_stack_name = data.aws_elastic_beanstalk_solution_stack.net_latest.name
  
  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "RDS_HOSTNAME"
    value     = #  How can I set here the RDS endpoint ???
  }

  setting {
    namespace = "aws:rds:dbinstance"
    name      = "HasCoupledDatabase"
    value     = "true"
  }

  setting {
    namespace = "aws:rds:dbinstance"
    name      = "DBEngine"
    value     = var.db_engine
  }

  setting {
    namespace = "aws:rds:dbinstance"
    name      = "DBEngineVersion"
    value     = var.db_engine_version
  }

  setting {
    namespace = "aws:rds:dbinstance"
    name      = "DBInstanceClass"
    value     = var.db_instance_type
  }

  setting {
    namespace = "aws:rds:dbinstance"
    name      = "DBPassword"
    value     = var.db_password
  }

  setting {
    namespace = "aws:rds:dbinstance"
    name      = "DBUser"
    value     = var.db_user
  }
 }

The question is: how can I set the RDS_HOSTNAME ?

As far as I know, it is possible to get the endpoint from an RDS created as a separate resource, but I didn't find any documentation how to get this from RDS created as part of an Elastic Beanstalk. I spent many days and didn't find any example however it should be a typical case for developers.


Solution

  • I have not tried it but according to the docs, these env variables are injected automatically by the elastic bean stalk:

    https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-nodejs.rds.html#nodejs-rds-connect

    Adding a DB instance takes about 10 minutes. When the environment update is complete, the DB instance's hostname and other connection information are available to your application through the following environment properties:

    enter image description here

    To validate it, you can create manually env environment with and RDS, then perform one of these validations:

    1. Using the UI, go to the configuration and check if these variables exist

    enter image description here

    1. Using the shell, enter to the ec2 and execute env.
    2. From the inside of your application, at the entrypoint print the env variables