I have an AWS Cloudformation, and I want two EC2 instances A and B on a private subnet under the same VPC.
In the application, I need A to access B.
How can I configure A with the dynamically allocated private IP of B?
I believe I can configure A with an environment variable (e.g., with aws:elasticbeanstalk:application:environment
).
The problem is that I don't know how to get the IP of B. I assume it cannot be an elastic IP because it's private, hence it may be changed between deployments.
You use security groups so you don't have to worry about IP addresses. Create a sec group for instance in subnet A and one for instance in subnet b and then allow traffic between the sec groups. Any instance in sec group A can talk to an instance in sec group b over the port you define or all traffic.
instanceA:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref imageID
SecurityGroupIds:
- !Ref SGroupA
SubnetId: !Ref subnetA
instanceB:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref imageID
SecurityGroupIds:
- !Ref SGroupb
SubnetId: !Ref subnetb
SGroupA:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: EC2 Instance access
SGroupB:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: EC2 Instance access
SGroupAIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupName: !Ref SGroupA
IpProtocol: tcp
ToPort: 80
FromPort: 80
SourceSecurityGroupName: !Ref SGroupB
SGroupBIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupName: !Ref SGroupB
IpProtocol: tcp
ToPort: 80
FromPort: 80
SourceSecurityGroupName: !Ref SGroupA
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-ec2.html