Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detecting drift on aws_lb_target_group_attachment #9610

Merged
merged 8 commits into from
Aug 12, 2019
24 changes: 24 additions & 0 deletions aws/resource_aws_lb_target_group_attachment.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ func resourceAwsLbAttachmentRead(d *schema.ResourceData, meta interface{}) error
TargetGroupArn: aws.String(d.Get("target_group_arn").(string)),
Targets: []*elbv2.TargetDescription{target},
})

if err != nil {
if isAWSErr(err, elbv2.ErrCodeTargetGroupNotFoundException, "") {
log.Printf("[WARN] Target group does not exist, removing target attachment %s", d.Id())
Expand All @@ -140,6 +141,29 @@ func resourceAwsLbAttachmentRead(d *schema.ResourceData, meta interface{}) error
return fmt.Errorf("Error reading Target Health: %s", err)
}

for _, targetDesc := range resp.TargetHealthDescriptions {
if targetDesc == nil || targetDesc.Target == nil {
continue
}

if *targetDesc.Target.Id == d.Get("target_id").(string) {
bflad marked this conversation as resolved.
Show resolved Hide resolved
// These will catch targets being removed by hand (draining as we plan) or that have been removed for a while
// without trying to re-create ones that are just not in use. For example, a target can be `unused` if the
// target group isnt assigned to anything, a scenario where we don't want to continuously recreate the resource.
if targetDesc.TargetHealth == nil {
continue
}

reason := aws.StringValue(targetDesc.TargetHealth.Reason)

if reason == elbv2.TargetHealthReasonEnumTargetNotRegistered || reason == elbv2.TargetHealthReasonEnumTargetDeregistrationInProgress {
log.Printf("[WARN] Target Attachment does not exist, recreating attachment")
d.SetId("")
return nil
}
}
}

if len(resp.TargetHealthDescriptions) != 1 {
log.Printf("[WARN] Target does not exist, removing target attachment %s", d.Id())
d.SetId("")
Expand Down
54 changes: 54 additions & 0 deletions aws/resource_aws_lb_target_group_attachment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,26 @@ func TestAccAWSLBTargetGroupAttachment_basic(t *testing.T) {
})
}

func TestAccAWSLBTargetGroupAttachment_missingAttachmentDrift(t *testing.T) {
targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "aws_lb_target_group.test",
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSLBTargetGroupAttachmentDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSLBTargetGroupAttachmentConfig_basic(targetGroupName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSLBTargetGroupAttachmentExists("aws_lb_target_group_attachment.test"),
deregisterTarget("aws_lb_target_group_attachment.test"),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func TestAccAWSLBTargetGroupAttachmentBackwardsCompatibility(t *testing.T) {
targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))

Expand Down Expand Up @@ -108,6 +128,40 @@ func TestAccAWSALBTargetGroupAttachment_lambda(t *testing.T) {
})
}

func deregisterTarget(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Attachment not found: %s", n)
}

conn := testAccProvider.Meta().(*AWSClient).elbv2conn
targetGroupArn := rs.Primary.Attributes["target_group_arn"]

target := &elbv2.TargetDescription{
Id: aws.String(rs.Primary.Attributes["target_id"]),
}

_, hasPort := rs.Primary.Attributes["port"]
if hasPort {
port, _ := strconv.Atoi(rs.Primary.Attributes["port"])
target.Port = aws.Int64(int64(port))
}

params := &elbv2.DeregisterTargetsInput{
TargetGroupArn: aws.String(targetGroupArn),
Targets: []*elbv2.TargetDescription{target},
}

_, err := conn.DeregisterTargets(params)
if err != nil && !isAWSErr(err, elbv2.ErrCodeTargetGroupNotFoundException, "") {
return fmt.Errorf("Error deregistering Targets: %s", err)
}

return err
}
}

func testAccCheckAWSLBTargetGroupAttachmentExists(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
Expand Down