provider/aws: Expose ARN suffix on ALB Target Group (#9734)

When creating a CloudWatch Metric for an Application Load Balancer Target Group  it is
neccessary to use the suffix of the ARN as the reference to the load
balancer TG . This commit exposes that as an attribute on the `aws_alb_target_group`
resource to prevent the need to use regular expression substitution to
make the reference.
This commit is contained in:
Paul Stack 2016-10-31 17:05:06 +00:00 committed by GitHub
parent 83610413e9
commit fdabf59380
3 changed files with 53 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"log"
"regexp"
"strconv"
"strings"
@ -30,6 +31,11 @@ func resourceAwsAlbTargetGroup() *schema.Resource {
Computed: true,
},
"arn_suffix": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Required: true,
@ -218,6 +224,7 @@ func resourceAwsAlbTargetGroupRead(d *schema.ResourceData, meta interface{}) err
targetGroup := resp.TargetGroups[0]
d.Set("arn", targetGroup.TargetGroupArn)
d.Set("arn_suffix", albTargetGroupSuffixFromARN(targetGroup.TargetGroupArn))
d.Set("name", targetGroup.TargetGroupName)
d.Set("port", targetGroup.Port)
d.Set("protocol", targetGroup.Protocol)
@ -463,3 +470,17 @@ func validateAwsAlbTargetGroupStickinessCookieDuration(v interface{}, k string)
}
return
}
func albTargetGroupSuffixFromARN(arn *string) string {
if arn == nil {
return ""
}
if arnComponents := regexp.MustCompile(`arn:.*:targetgroup/(.*)`).FindAllStringSubmatch(*arn, -1); len(arnComponents) == 1 {
if len(arnComponents[0]) == 2 {
return arnComponents[0][1]
}
}
return ""
}

View File

@ -13,6 +13,37 @@ import (
"github.com/hashicorp/terraform/terraform"
)
func TestALBTargetGroupCloudwatchSuffixFromARN(t *testing.T) {
cases := []struct {
name string
arn *string
suffix string
}{
{
name: "valid suffix",
arn: aws.String(`arn:aws:elasticloadbalancing:us-east-1:123456:targetgroup/my-targets/73e2d6bc24d8a067`),
suffix: `my-targets/73e2d6bc24d8a067`,
},
{
name: "no suffix",
arn: aws.String(`arn:aws:elasticloadbalancing:us-east-1:123456:targetgroup`),
suffix: ``,
},
{
name: "nil ARN",
arn: nil,
suffix: ``,
},
}
for _, tc := range cases {
actual := albTargetGroupSuffixFromARN(tc.arn)
if actual != tc.suffix {
t.Fatalf("bad suffix: %q\nExpected: %s\n Got: %s", tc.name, tc.suffix, actual)
}
}
}
func TestAccAWSALBTargetGroup_basic(t *testing.T) {
var conf elbv2.TargetGroup
targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))

View File

@ -62,6 +62,7 @@ The following attributes are exported in addition to the arguments listed above:
* `id` - The ARN of the Target Group (matches `arn`)
* `arn` - The ARN of the Target Group (matches `id`)
* `arn_suffix` - The ARN suffix for use with CloudWatch Metrics.
## Import