首页 > 解决方案 > 如何将 ECS 服务注册到另一个堆栈中定义的目标组

问题描述

我有 2 个堆栈,第一个定义我的应用程序 LB,另一个定义我的 ECS 服务。

在第一个堆栈中,我为我的多个 ECS 服务定义了多个目标组,并希望注册其对应的服务。

作为参考,我在此处按照此示例拆分了我的应用程序

如何将我的 ECS 服务注册到另一个堆栈中定义的目标组?

我的 ECS 服务...

    const service = new ecs.Ec2Service(this, 'jenkinsService', {
      cluster: props.cluster,
      taskDefinition,
      serviceName: 'Jenkins-Master',
      minHealthyPercent: 0,
      maxHealthyPercent: 100
    });

    props.targetGroup.addTarget(service) // I want to register against a specific Target Group

我的自定义目标组


        const jenkinsMastertargetGroup = this.targetGroup = new elbv2.ApplicationTargetGroup(this, 'Jenkins-Master', {
          vpc: props.vpc,
          port: 80,
          targetType: elbv2.TargetType.INSTANCE,
          targetGroupName: 'WDD-Jenkins-Master',
          deregistrationDelay: cdk.Duration.seconds(250),
          healthCheck:{
            port: '8080',
            path:'/log/all',
            interval: cdk.Duration.minutes(3)
          }

        });

我的听众转发给 TG 的动作

        elbHTTPlistener.addAction('JenkinsMasterResponse', {
          priority: 5,
          conditions: [
            //ListenerCondition.hostHeaders(['sub1.test.com.au/jenkins']),
            ListenerCondition.pathPatterns(['/jenkins']),
          ],
          action: ListenerAction.forward([jenkinsMastertargetGroup]),
        });

标签: amazon-web-servicesamazon-cloudformationamazon-ecsaws-cdk

解决方案


我找到了一个相对简单的解决方案,在 cloudformation 中使用导入/导出。

在我定义应用程序 ELB 的第一个堆栈中,我定义了一个空目标组,然后导出目标组的 ARN。

确保为您的 TG 添加规则。


const emptytg = new elbv2.ApplicationTargetGroup(this, 'tg1', {
        vpc,
        port: 80,
        targetGroupName: 'name',
        targetType: elbv2.TargetType.INSTANCE,
});

Listener.addAction('tg1', {
        priority: 2,
        conditions:[
          ListenerCondition.pathPatterns(['/tg1']),
        ],
        action: ListenerAction.forward([tg1])
      });

new cdk.CfnOutput(this,'tg1Export', {
      value: emptytg.targetGroupArn,
      exportName: 'emptytgARN'
    });

下面是另一个包含 ECS 服务的堆栈,您可以导入 TG,然后使用 .addTarget 目标方法。


const importedGroup = elbv2.ApplicationTargetGroup.fromTargetGroupAttributes(this, 'imported-tg',{
targetGroupArn: cdk.Fn.importValue('wddSharedResourcesjenkinsMastertargetGrouptargetGroupArn'),
});

importedGroup.addTarget(service);  

这对我来说效果很好,我希望它在未来对其他人有所帮助。


推荐阅读