Reputation: 2257
Similar questions have been asked before, but I could not find the exact answer to my problem...
I have a definition for an EC2 instance which needs access to its own public IP in the UserData
section:
"MyEC2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"SubnetId": {
"Fn::ImportValue": {
"Fn::Sub": "${NetworkStackName}-SubnetID"
}
},
"ImageId": "ami-xxxx",
"InstanceType": { "Ref": "InstanceTypeParameter" },
"IamInstanceProfile": { "Ref": "MasterInstanceProfile" },
"UserData": {
"Fn::Base64": {
"Fn::Join": [
"",
[
"#!/bin/bash -v\n",
" PUBLIC_IP=",
{
"Fn::GetAtt": ["MyEC2Instance", "PublicIp"]
},
" /usr/local/bin/docker-compose -f /docker-compose.yml up -d\n"
]
]
}
}
}
normally it's easy to access it via "Fn::GetAtt": ["MyEC2Instance", "PublicIp"]
, but in this case, this throws a "circular dependency error" - sure this does make sense, but how could I solve this?
Upvotes: 1
Views: 734
Reputation: 502
The public ip is assigned to the EC2 instance after its creation, therefore it is not possible to render it in its userdata.
You can use instance metadata to get the public ipv4 as well as other instance properties.
PUBLIC_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)
Upvotes: 6