1

I'm using aws-cdk to run 7 ec2 instances which will be MongoDB nodes. I'm able to create them with their security group and stuff, but I don't understand how can I map those in private DNS.

for (inst i = 1; inst<8; inst++) {
  new ec2.Instance(this, 'mongodb' + i, {
  instanceType: new ec2.InstanceType('t3.medium'), 
  vpc: defaultVpc,
  securityGroup: mongoGroup },
  )}

After deployment names will be ${mongodb1/InstanceRole.Arn}, ${mongodb2/InstanceRole.Arn},...

How can I set my private DNS records for those instances in cdk? I want to create a configuration in which all nodes will be listed like

 database1.test.com
 database2.test.com
 database3.test.com
 ...

Instead of

ec2-203-3-156-25.compute-1.amazonaws.com
ec2-201-1-191-21.compute-1.amazonaws.com
ec2-208-0-112-03.compute-1.amazonaws.com
...

because if I redeploy or restart, IP will change, and I will need again to change complete configuration, also these names are just not easy to remember. I guess I need to create private hosted zone, and then assign each IP address to CNAME, but wonder if can be done in cdk automatically?

Mr.Mister.
  • 23
  • 7
  • One way is setting `privateIpAddress`. Another is using a network load balancer and adding all the instance to the target group. – kichik Dec 12 '21 at 21:03
  • tnx, any suggestions maybe how can i achieve load balancer with target group in cdk? appreciate. – Mr.Mister. Dec 12 '21 at 21:10

1 Answers1

0

You can use a network load balancer (NLB) for that.

Something similar to:

import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';
import * as elasticloadbalancingv2_targets from '@aws-cdk/aws-elasticloadbalancingv2-targets';

// vpc = ...

const lb = new elbv2.NetworkLoadBalancer(this, 'lb', { vpc, internetFacing: false });
const listener = lb.addListener('listener', { port: 27017 });
listener.addTargets('target', {
  targets: [
    new elasticloadbalancingv2_targets.InstanceIdTarget(instance1.instanceId),
    new elasticloadbalancingv2_targets.InstanceIdTarget(instance2.instanceId),
    // ... more ...
  ]
});

// get domain name from lb.loadBalancerDnsName
kichik
  • 33,220
  • 7
  • 94
  • 114