Reputation:
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?
Upvotes: 3
Views: 4170
Reputation: 3865
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>
Upvotes: 3
Reputation: 71
The idea is same as from [tyron], but you can actually make the code way shorter in YAML, since !Sub can resolve the same as !GetAtt as an expression:
Resources:
Rds:
Type: AWS::RDS::DBInstance
Properties:
...
Ec2:
Type: AWS::EC2::Instance
Properties:
...
UserData:
Fn::Base64:
!Sub |
#!/bin/bash
echo "DB_CONNECTION=${Rds.Endpoint.Address}" >> /etc/profile
The ${Rds.Endpoint.Address} will be resolved by !Sub - before starting the instance - it won't we the bash shell interpreting it, even though the syntax looks very similar.
The actual shell code in the UserData depends on who (which user / process) is intended to use the variable. With code like I gave, it should be set system-wide, so no matter who logs in, it should have that property. Of course, if the process is already running and already read the env properties, it won't see the new value - only new shell instances started after the user-data was executed.
Best check related answer(s) for the shell code you need, like this one: https://stackoverflow.com/a/1641531/4966203
Upvotes: 1