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

New Resource: aws_dx_lag #2154

Merged
merged 4 commits into from
Nov 7, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions aws/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import (
"github.com/aws/aws-sdk-go/service/configservice"
"github.com/aws/aws-sdk-go/service/databasemigrationservice"
"github.com/aws/aws-sdk-go/service/devicefarm"
"github.com/aws/aws-sdk-go/service/directconnect"
"github.com/aws/aws-sdk-go/service/directoryservice"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/ec2"
Expand Down Expand Up @@ -180,6 +181,7 @@ type AWSClient struct {
wafregionalconn *wafregional.WAFRegional
iotconn *iot.IoT
batchconn *batch.Batch
dxconn *directconnect.DirectConnect
}

func (c *AWSClient) S3() *s3.S3 {
Expand Down Expand Up @@ -390,6 +392,7 @@ func (c *Config) Client() (interface{}, error) {
client.wafconn = waf.New(sess)
client.wafregionalconn = wafregional.New(sess)
client.batchconn = batch.New(sess)
client.dxconn = directconnect.New(sess)

// Workaround for https://github.com/aws/aws-sdk-go/issues/1376
client.kinesisconn.Handlers.Retry.PushBack(func(r *request.Request) {
Expand Down
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,7 @@ func Provider() terraform.ResourceProvider {
"aws_dms_replication_instance": resourceAwsDmsReplicationInstance(),
"aws_dms_replication_subnet_group": resourceAwsDmsReplicationSubnetGroup(),
"aws_dms_replication_task": resourceAwsDmsReplicationTask(),
"aws_dx_lag": resourceAwsDxLag(),
"aws_dynamodb_table": resourceAwsDynamoDbTable(),
"aws_ebs_snapshot": resourceAwsEbsSnapshot(),
"aws_ebs_volume": resourceAwsEbsVolume(),
Expand Down
162 changes: 162 additions & 0 deletions aws/resource_aws_dx_lag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package aws

import (
"fmt"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/directconnect"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsDxLag() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDxLagCreate,
Read: resourceAwsDxLagRead,
Update: resourceAwsDxLagUpdate,
Delete: resourceAwsDxLagDelete,

Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"band_width": &schema.Schema{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick, but is there any reason to drift away from the name in the API? i.e. can't we just call it connections_bandwidth?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I totally agree with your reviews!

Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateDxLagBandWidth,
},
"location": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"num_connections": &schema.Schema{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick, but is there any reason to drift away from the name in the API? i.e. can't we just call it number_of_connections ?

Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"force_destroy": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}

func resourceAwsDxLagCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dxconn

input := &directconnect.CreateLagInput{
ConnectionsBandwidth: aws.String(d.Get("band_width").(string)),
LagName: aws.String(d.Get("name").(string)),
Location: aws.String(d.Get("location").(string)),
NumberOfConnections: aws.Int64(int64(d.Get("num_connections").(int))),
}
resp, err := conn.CreateLag(input)
if err != nil {
return err
}
d.SetId(*resp.LagId)
return resourceAwsDxLagRead(d, meta)
}

func resourceAwsDxLagRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dxconn

lagId := d.Id()
input := &directconnect.DescribeLagsInput{
LagId: aws.String(lagId),
}
resp, err := conn.DescribeLags(input)
if err != nil {
d.SetId("")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't find any particular error that would mean LAG is gone in this context: http://docs.aws.amazon.com/directconnect/latest/APIReference/API_DescribeLags.html#c
so I don't think error here is a reason for removing the LAG from state. 🤔

return err
}
if len(resp.Lags) != 1 {
d.SetId("")
return fmt.Errorf("[ERROR] Number of DX Lag (%s) isn't one, got %d", lagId, len(resp.Lags))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm ok with erroring out if we get != 1 lags, but I don't think it's a reason for removing the LAG from state. We should only be removing it from state if it's not found - i.e. len(resp.Lags) < 1

}
if d.Id() != *resp.Lags[0].LagId {
d.SetId("")
return fmt.Errorf("[ERROR] DX Lag (%s) not found", lagId)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes sense to error out if wrong ID was found (not sure how/why would that happen, but strange things do happen sometimes), but I'm not sure if it's the reason for removing LAG from state.

}
return nil
}

func resourceAwsDxLagUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dxconn

input := &directconnect.UpdateLagInput{
LagId: aws.String(d.Id()),
}
if d.HasChange("name") {
input.LagName = aws.String(d.Get("name").(string))
}
_, err := conn.UpdateLag(input)
if err != nil {
return err
}
return nil
}

func resourceAwsDxLagDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dxconn

if d.Get("force_destroy").(bool) {
input := &directconnect.DescribeLagsInput{
LagId: aws.String(d.Id()),
}
resp, err := conn.DescribeLags(input)
if err != nil {
return err
}
lag := resp.Lags[0]
for _, v := range lag.Connections {
dcinput := &directconnect.DeleteConnectionInput{
ConnectionId: v.ConnectionId,
}
if _, err := conn.DeleteConnection(dcinput); err != nil {
return err
}
}
}

input := &directconnect.DeleteLagInput{
LagId: aws.String(d.Id()),
}
_, err := conn.DeleteLag(input)
if err != nil {
return err
}
deleteStateConf := &resource.StateChangeConf{
Pending: []string{directconnect.LagStateAvailable, directconnect.LagStateRequested, directconnect.LagStatePending},
Target: []string{directconnect.LagStateDeleted, directconnect.LagStateDeleting},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any reason we should treat directconnect.LagStateDeleting as Target state here?

Refresh: dxLagRefreshStateFunc(conn, d.Id()),
Timeout: 10 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = deleteStateConf.WaitForState()
if err != nil {
return fmt.Errorf("Error waiting for Dx Lag (%s) to be deleted: %s", d.Id(), err)
}
d.SetId("")
return nil
}

func dxLagRefreshStateFunc(conn *directconnect.DirectConnect, lagId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
input := &directconnect.DescribeLagsInput{
LagId: aws.String(lagId),
}
resp, err := conn.DescribeLags(input)
if err != nil {
return nil, "failed", err
}
return resp, *resp.Lags[0].LagState, nil
}
}
77 changes: 77 additions & 0 deletions aws/resource_aws_dx_lag_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package aws

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/directconnect"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccAwsDxLag_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsDxLagDestroy,
Steps: []resource.TestStep{
{
Config: testAccDxLagConfig(acctest.RandString(5)),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsDxLagExists("aws_dx_lag.hoge"),
),
},
},
})
}

func testAccCheckAwsDxLagDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).dxconn

for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_dx_lag" {
continue
}

input := &directconnect.DescribeLagsInput{
LagId: aws.String(rs.Primary.ID),
}

resp, err := conn.DescribeLags(input)
if err != nil {
return err
}
for _, v := range resp.Lags {
if *v.LagId == rs.Primary.ID && !(*v.LagState == directconnect.LagStateDeleting || *v.LagState == directconnect.LagStateDeleted) {
return fmt.Errorf("[DESTROY ERROR] Dx Lag (%s) found", rs.Primary.ID)
}
}
}

return nil
}

func testAccCheckAwsDxLagExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}

return nil
}
}

func testAccDxLagConfig(rName string) string {
return fmt.Sprintf(`
resource "aws_dx_lag" "hoge" {
name = "tf-dx-lag-%s"
band_width = "1Gbps"
location = "EqDC2"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mind changing the location to a one which is available in us-west-2 as all of our tests run in that region? e.g. EqSe2

num_connections = 2
force_destroy = true
}
`, rName)
}
18 changes: 18 additions & 0 deletions aws/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -1651,3 +1651,21 @@ func validateCognitoRoles(v map[string]interface{}, k string) (errors []error) {

return
}

func validateDxLagBandWidth(v interface{}, k string) (ws []string, errors []error) {
val, ok := v.(string)
if !ok {
errors = append(errors, fmt.Errorf("expected type of %s to be string", k))
return
}

validBandWidth := []string{"1Gbps", "10Gbps"}
for _, str := range validBandWidth {
if val == str {
return
}
}

errors = append(errors, fmt.Errorf("expected %s to be one of %v, got %s", k, validBandWidth, val))
return
}
27 changes: 27 additions & 0 deletions aws/validators_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2603,3 +2603,30 @@ func TestValidateCognitoRoleMappingsType(t *testing.T) {
}
}
}

func TestValidateDxLagBandWidth(t *testing.T) {
validValues := []string{
"1Gbps",
"10Gbps",
}

for _, s := range validValues {
_, errors := validateDxLagBandWidth(s, "match_type")
if len(errors) > 0 {
t.Fatalf("%s should be a valid Direct Connect Lag Bandwidth: %v", s, errors)
}
}

invalidValues := []string{
"1gbps",
"10GBPS",
"invalid character",
}

for _, s := range invalidValues {
_, errors := validateDxLagBandWidth(s, "match_type")
if len(errors) == 0 {
t.Fatalf("%s should not be a valid Direct Connect Lag Bandwidth: %v", s, errors)
}
}
}
9 changes: 9 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,15 @@
</ul>
</li>

<li<%= sidebar_current("docs-aws-resource-dx") %>>
<a href="#">Direct Connect Resources</a>
<ul class="nav nav-visible">
<li<%= sidebar_current("docs-aws-resource-dx-lag") %>>
<a href="/docs/providers/aws/r/dx_lag.html">aws_dx_lag</a>
</li>
</ul>
</li>

<li<%= sidebar_current("docs-aws-resource-directory-service") %>>
<a href="#">Directory Service Resources</a>
<ul class="nav nav-visible">
Expand Down
39 changes: 39 additions & 0 deletions website/docs/r/dx_lag.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
layout: "aws"
page_title: "AWS: aws_dx_lag"
sidebar_current: "docs-aws-resource-dx-lag"
description: |-
Provides a Direct Connect LAG.
---

# aws_dx_lag

Provides a Direct Connect LAG.

## Example Usage

```hcl
resource "aws_dx_lag" "hoge" {
name = "tf-dx-lag"
band_width = "1Gbps"
location = "EqDC2"
num_connections = 2
force_destroy = true
}
```

## Argument Reference

The following arguments are supported:

* `name` - (Required) The name of the LAG.
* `band_width` - (Required) The bandwidth of the individual physical connections bundled by the LAG. Available values: 1Gbps, 10Gbps. Case sensitive.
* `location` - (Required) The AWS Direct Connect location in which the LAG should be allocated. See [DescribeLocations](https://docs.aws.amazon.com/directconnect/latest/APIReference/API_DescribeLocations.html) for the list of AWS Direct Connect locations. Use `locationCode`.
* `num_connections` - (Required) The number of physical connections initially provisioned and bundled by the LAG.
* `force_destroy` - (Optional, Default:false) A boolean that indicates all connections associated with the LAG should be deleted so that the LAG can be destroyed without error. These objects are *not* recoverable.

## Attributes Reference

The following attributes are exported:

* `id` - The ID of the LAG.