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_bgp_peer #5886

Merged
merged 5 commits into from
Sep 14, 2018
Merged
Show file tree
Hide file tree
Changes from all 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: 2 additions & 1 deletion aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,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_dx_bgp_peer": resourceAwsDxBgpPeer(),
"aws_dx_connection": resourceAwsDxConnection(),
"aws_dx_connection_association": resourceAwsDxConnectionAssociation(),
"aws_dx_gateway": resourceAwsDxGateway(),
Expand All @@ -389,6 +389,7 @@ func Provider() terraform.ResourceProvider {
"aws_dx_hosted_private_virtual_interface_accepter": resourceAwsDxHostedPrivateVirtualInterfaceAccepter(),
"aws_dx_hosted_public_virtual_interface": resourceAwsDxHostedPublicVirtualInterface(),
"aws_dx_hosted_public_virtual_interface_accepter": resourceAwsDxHostedPublicVirtualInterfaceAccepter(),
"aws_dx_lag": resourceAwsDxLag(),
"aws_dx_private_virtual_interface": resourceAwsDxPrivateVirtualInterface(),
"aws_dx_public_virtual_interface": resourceAwsDxPublicVirtualInterface(),
"aws_dynamodb_table": resourceAwsDynamoDbTable(),
Expand Down
210 changes: 210 additions & 0 deletions aws/resource_aws_dx_bgp_peer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
package aws

import (
"fmt"
"log"
"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"
"github.com/hashicorp/terraform/helper/validation"
)

func resourceAwsDxBgpPeer() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDxBgpPeerCreate,
Read: resourceAwsDxBgpPeerRead,
Delete: resourceAwsDxBgpPeerDelete,

Schema: map[string]*schema.Schema{
"address_family": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{directconnect.AddressFamilyIpv4, directconnect.AddressFamilyIpv6}, false),
},
"bgp_asn": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"virtual_interface_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"amazon_address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"bgp_auth_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"customer_address": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"bgp_status": {
Type: schema.TypeString,
Computed: true,
},
},

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
}
}

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

vifId := d.Get("virtual_interface_id").(string)
addrFamily := d.Get("address_family").(string)
asn := int64(d.Get("bgp_asn").(int))

req := &directconnect.CreateBGPPeerInput{
VirtualInterfaceId: aws.String(vifId),
NewBGPPeer: &directconnect.NewBGPPeer{
AddressFamily: aws.String(addrFamily),
Asn: aws.Int64(asn),
},
}
if v, ok := d.GetOk("amazon_address"); ok && v.(string) != "" {
req.NewBGPPeer.AmazonAddress = aws.String(v.(string))
}
if v, ok := d.GetOk("bgp_auth_key"); ok && v.(string) != "" {
req.NewBGPPeer.AuthKey = aws.String(v.(string))
}
if v, ok := d.GetOk("customer_address"); ok && v.(string) != "" {
req.NewBGPPeer.CustomerAddress = aws.String(v.(string))
}

log.Printf("[DEBUG] Creating Direct Connect BGP peer: %#v", req)
_, err := conn.CreateBGPPeer(req)
if err != nil {
return fmt.Errorf("Error creating Direct Connect BGP peer: %s", err)
}

d.SetId(fmt.Sprintf("%s-%s-%d", vifId, addrFamily, asn))

stateConf := &resource.StateChangeConf{
Pending: []string{
directconnect.BGPPeerStatePending,
},
Target: []string{
directconnect.BGPPeerStateAvailable,
directconnect.BGPPeerStateVerifying,
},
Refresh: dxBgpPeerStateRefresh(conn, vifId, addrFamily, asn),
Timeout: d.Timeout(schema.TimeoutDelete),
Delay: 10 * time.Second,
MinTimeout: 5 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf("Error waiting for Direct Connect BGP peer (%s) to be available: %s", d.Id(), err)
}

return resourceAwsDxBgpPeerRead(d, meta)
}

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

vifId := d.Get("virtual_interface_id").(string)
addrFamily := d.Get("address_family").(string)
asn := int64(d.Get("bgp_asn").(int))

bgpPeerRaw, state, err := dxBgpPeerStateRefresh(conn, vifId, addrFamily, asn)()
if err != nil {
return fmt.Errorf("Error reading Direct Connect BGP peer: %s", err)
}
if state == directconnect.BGPPeerStateDeleted {
log.Printf("[WARN] Direct Connect BGP peer (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

bgpPeer := bgpPeerRaw.(*directconnect.BGPPeer)
d.Set("amazon_address", bgpPeer.AmazonAddress)
d.Set("bgp_auth_key", bgpPeer.AuthKey)
d.Set("customer_address", bgpPeer.CustomerAddress)
d.Set("bgp_status", bgpPeer.BgpStatus)

return nil
}

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

vifId := d.Get("virtual_interface_id").(string)
addrFamily := d.Get("address_family").(string)
asn := int64(d.Get("bgp_asn").(int))

log.Printf("[DEBUG] Deleting Direct Connect BGP peer: %s", d.Id())
_, err := conn.DeleteBGPPeer(&directconnect.DeleteBGPPeerInput{
Asn: aws.Int64(asn),
CustomerAddress: aws.String(d.Get("customer_address").(string)),
VirtualInterfaceId: aws.String(vifId),
})
if err != nil {
// This is the error returned if the BGP peering has already gone.
if isAWSErr(err, "DirectConnectClientException", "The last BGP Peer on a Virtual Interface cannot be deleted") {
return nil
}
return err
}

stateConf := &resource.StateChangeConf{
Pending: []string{
directconnect.BGPPeerStateAvailable,
directconnect.BGPPeerStateDeleting,
directconnect.BGPPeerStatePending,
directconnect.BGPPeerStateVerifying,
},
Target: []string{
directconnect.BGPPeerStateDeleted,
},
Refresh: dxBgpPeerStateRefresh(conn, vifId, addrFamily, asn),
Timeout: d.Timeout(schema.TimeoutDelete),
Delay: 10 * time.Second,
MinTimeout: 5 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf("Error waiting for Direct Connect BGP peer (%s) to be deleted: %s", d.Id(), err)
}

return nil
}

func dxBgpPeerStateRefresh(conn *directconnect.DirectConnect, vifId, addrFamily string, asn int64) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
vif, err := dxVirtualInterfaceRead(vifId, conn)
if err != nil {
return nil, "", err
}
if vif == nil {
return "", directconnect.BGPPeerStateDeleted, nil
}

for _, bgpPeer := range vif.BgpPeers {
if aws.StringValue(bgpPeer.AddressFamily) == addrFamily && aws.Int64Value(bgpPeer.Asn) == asn {
return bgpPeer, aws.StringValue(bgpPeer.BgpPeerState), nil
}
}

return "", directconnect.BGPPeerStateDeleted, nil
}
}
85 changes: 85 additions & 0 deletions aws/resource_aws_dx_bgp_peer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package aws

import (
"fmt"
"os"
"strconv"
"testing"

"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/terraform"
)

func TestAccAwsDxBgpPeer_basic(t *testing.T) {
key := "DX_VIRTUAL_INTERFACE_ID"
vifId := os.Getenv(key)
if vifId == "" {
t.Skipf("Environment variable %s is not set", key)
}
bgpAsn := randIntRange(64512, 65534)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsDxBgpPeerDestroy,
Steps: []resource.TestStep{
{
Config: testAccDxBgpPeerConfig(vifId, bgpAsn),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsDxBgpPeerExists("aws_dx_bgp_peer.foo"),
resource.TestCheckResourceAttr("aws_dx_bgp_peer.foo", "address_family", "ipv6"),
),
},
},
})
}

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

for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_dx_bgp_peer" {
continue
}
input := &directconnect.DescribeVirtualInterfacesInput{
VirtualInterfaceId: aws.String(rs.Primary.Attributes["virtual_interface_id"]),
}

resp, err := conn.DescribeVirtualInterfaces(input)
if err != nil {
return err
}
for _, peer := range resp.VirtualInterfaces[0].BgpPeers {
if *peer.AddressFamily == rs.Primary.Attributes["address_family"] &&
strconv.Itoa(int(*peer.Asn)) == rs.Primary.Attributes["bgp_asn"] &&
*peer.BgpPeerState != directconnect.BGPPeerStateDeleted {
return fmt.Errorf("[DESTROY ERROR] Dx BGP peer (%s) not deleted", rs.Primary.ID)
}
}
}
return nil
}

func testAccCheckAwsDxBgpPeerExists(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 testAccDxBgpPeerConfig(vifId string, bgpAsn int) string {
return fmt.Sprintf(`
resource "aws_dx_bgp_peer" "foo" {
virtual_interface_id = "%s"

address_family = "ipv6"
bgp_asn = %d
}
`, vifId, bgpAsn)
}
3 changes: 3 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,9 @@
<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-bgp-peer") %>>
<a href="/docs/providers/aws/r/dx_bgp_peer.html">aws_dx_bgp_peer</a>
</li>
<li<%= sidebar_current("docs-aws-resource-dx-connection") %>>
<a href="/docs/providers/aws/r/dx_connection.html">aws_dx_connection</a>
</li>
Expand Down
49 changes: 49 additions & 0 deletions website/docs/r/dx_bgp_peer.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
layout: "aws"
page_title: "AWS: aws_dx_bgp_peer"
sidebar_current: "docs-aws-resource-dx-bgp-peer"
description: |-
Provides a Direct Connect BGP peer resource.
---

# aws_dx_bgp_peer

Provides a Direct Connect BGP peer resource.

## Example Usage

```hcl
resource "aws_dx_bgp_peer" "peer" {
virtual_interface_id = "${aws_dx_private_virtual_interface.foo.id}"
address_family = "ipv6"
bgp_asn = 65351
}
```

## Argument Reference

The following arguments are supported:

* `address_family` - (Required) The address family for the BGP peer. `ipv4 ` or `ipv6`.
* `bgp_asn` - (Required) The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration.
* `virtual_interface_id` - (Required) The ID of the Direct Connect virtual interface on which to create the BGP peer.
* `amazon_address` - (Optional) The IPv4 CIDR address to use to send traffic to Amazon.
Required for IPv4 BGP peers on public virtual interfaces.
* `bgp_auth_key` - (Optional) The authentication key for BGP configuration.
* `customer_address` - (Optional) The IPv4 CIDR destination address to which Amazon should send traffic.
Required for IPv4 BGP peers on public virtual interfaces.

## Attributes Reference

In addition to all arguments above, the following attributes are exported:

* `id` - The ID of the BGP peer.
* `bgp_status` - The Up/Down state of the BGP peer.

## Timeouts

`aws_dx_bgp_peer` provides the following
[Timeouts](/docs/configuration/resources.html#timeouts) configuration options:

- `create` - (Default `10 minutes`) Used for creating BGP peer
- `delete` - (Default `10 minutes`) Used for destroying BGP peer