简体   繁体   中英

How do I add Targets with specific port using aws-cdk to existing ApplicationTargetGroup

I have an existing LoadBalancer and ApplicationTargetGroup and I am trying to add an autoscaling group as a target as follows

const asg = new autoscaling.AutoScalingGroup(this, 'AutoScalingGroup', {
      vpc,
      machineImage,
      instanceType: ec2.InstanceType.of(
        ec2.InstanceClass.T3,
        ec2.InstanceSize.MICRO
      ),
      allowAllOutbound: true,
      associatePublicIpAddress: true,
      vpcSubnets: {
        subnetType: ec2.SubnetType.PUBLIC,
      },
      keyName,
      autoScalingGroupName,
      desiredCapacity: 1,
      healthCheck: autoscaling.HealthCheck.ec2({
        grace: cdk.Duration.seconds(60),
      }),
    })

    asg.userData.addCommands(...commands)
    

    const tg = elbv2.ApplicationTargetGroup.fromTargetGroupAttributes(
      this,
      'TargetGroup',
      {
        targetGroupArn,
      }
    )
    
    tg.addTarget(asg)

This all works fine except the port for the ec2s in registered targets is 80 but I need it to be a different port, I am unsure how to do this with existing infrastructure

I was about to start on a similar problem and was researching. I came across this that may be of help

  1. He creates an ApplicationLoadBalancer and adds a listener to it on a specific port.

    
    
    const alb = new elbv2.ApplicationLoadBalancer(this, 'alb', {
      vpc,
      internetFacing: true,
    });
    
    const listener = alb.addListener('Listener', {
      port: 80,
      open: true,
    });
    
    

  1. He then adds targets to the listener on a specific port to an auto scaling group:

    
    
    //create auto scaling group
    const asg = new autoscaling.AutoScalingGroup(this, 'asg', {
      vpc,
      instanceType: ec2.InstanceType.of(
        ec2.InstanceClass.T2,
        ec2.InstanceSize.MICRO,
      ),
      machineImage: new ec2.AmazonLinuxImage({
        generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
      }),
      userData,
      minCapacity: 2,
      maxCapacity: 3,
    });
    
    // add target to the ALB listener
    listener.addTargets('default-target', {
      port: 80,
      targets: [asg],
      healthCheck: {
        path: '/',
        unhealthyThresholdCount: 2,
        healthyThresholdCount: 5,
        interval: cdk.Duration.seconds(30),
      },
    });
    
    

It looks like you want to investigate the config of the ALB listener. Hopefully that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM