Search code examples
aws-cloudformationamazon-ecs

Get TargetGroupArn from name?


You use TargetGroupArn in a CF template for ECS services. I have a situation where the target group has already been created and I want to make this a param for the template

But those arn's are awful:

arn:aws:elasticloadbalancing:us-east-1:123456:targetgroup/mytarget/4ed48ba353064a79

That unique number at the end makes this almost impossible. Can I reference the target by name instead of full arn in the template?

Maybe i can use Fn::GetAtt here but not sure what that looks like

This doesn't work:

  • TargetGroupArn: !GetAtt mytarget.TargetGroupName

I get error: An error occurred (ValidationError) when calling the CreateChangeSet operation: Template error: instance of Fn::GetAtt references undefined resource mytarget


Solution

    1. If you want to use the available Target-group, You pass the target group name as the default parameter to the Service CF template.
    2. Internally refer the default parameter as the ref to the TargetGroupArn in the Action section of the LiestnerRule It will get the target group ARN.
    3. Check this link: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html
    {
      "Parameters": {
          "VPC": {
          ...
          "TargetGroup": {
              "Description": "TargetGroup name for ListenerRule",
              "Type": "String",
              "Default": "my-target"
          }
      },
      "Resources": {
          "Service": {
          "TaskDefinition": {
          ....
          "ListenerRule": {
                      ....
                  "Actions": [
                      {
                          "TargetGroupArn": {
                              "Ref": "TargetGroup"
                          },
                          "Type": "forward"
                      }
                  ]
              }
          },
          "ServiceRole": {
      }
    }