Search code examples
amazon-web-servicesamazon-ec2aws-cloudformationrds

How do I get the hostname of RDS instance into an Environment variable in EC2?


I have a CloudFormation template that creates both RDS and EC2 under the same stack. My problem is, how do I get the RDS hostname into one of my environment variables inside my EC2, without having to install AWS cli and adding credentials?


Solution

  • I'm assuming that "RDS hostname" is your RDS endpoint?

    You can add to your EC2 Userdata, like the code below. I'm not very used to linux, so not sure if this would be the way to set your environment variable, but you get the idea.

    Resources:
      Rds:
        Type: 'AWS::RDS::DBInstance'
        Properties:
          ...
    
      Ec2:
        Type: 'AWS::EC2::Instance'
        Properties:
          ...
          UserData: !Base64 
            'Fn::Sub': 
              - |-
                <script>
                export DB_CONNECTION="${RdsEndpoint}"
                </script>
              - { RdsEndpoint: !GetAtt Rds.Endpoint.Address }
    

    Update

    In this particular case, you need to use the long syntax of Fn::Sub, since your reference needs to use the Fn::GetAtt. If the information you wanted was retrieved by a simple Fn::Ref, you could use the short syntax:

          UserData: !Base64 
            'Fn::Sub': 
              <script>
              export DB_CONNECTION="${Rds}" # <-- this will get the DBInstanceIdentifier
              </script>
    

    Update 2: as pointed out by Josef, you can still use the short syntax, regardless if the source is !Ref or !GetAtt. So this is valid:

      UserData: !Base64 
        'Fn::Sub': |-
          <script>
          export DB_CONNECTION="${Rds.Endpoint.Address}"
          </script>