Skip to content

Commit

Permalink
Add aws_elasticsearch_outbound_connection and aws_inbound_connection_…
Browse files Browse the repository at this point in the history
…accepter resources
  • Loading branch information
Symbianx committed Apr 19, 2022
1 parent ad07902 commit ca6abcc
Show file tree
Hide file tree
Showing 8 changed files with 850 additions and 3 deletions.
7 changes: 7 additions & 0 deletions .changelog/22988.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
```release-note:new-resource
aws_opensearch_outbound_connection
```

```release-note:new-resource
aws_opensearch_inbound_connection_accepter
```
8 changes: 5 additions & 3 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1642,9 +1642,11 @@ func Provider() *schema.Provider {
"aws_networkmanager_transit_gateway_connect_peer_association": networkmanager.ResourceTransitGatewayConnectPeerAssociation(),
"aws_networkmanager_transit_gateway_registration": networkmanager.ResourceTransitGatewayRegistration(),

"aws_opensearch_domain": opensearch.ResourceDomain(),
"aws_opensearch_domain_policy": opensearch.ResourceDomainPolicy(),
"aws_opensearch_domain_saml_options": opensearch.ResourceDomainSAMLOptions(),
"aws_opensearch_domain": opensearch.ResourceDomain(),
"aws_opensearch_domain_policy": opensearch.ResourceDomainPolicy(),
"aws_opensearch_domain_saml_options": opensearch.ResourceDomainSAMLOptions(),
"aws_opensearch_outbound_connection": opensearch.ResourceOutboundConnection(),
"aws_opensearch_inbound_connection_accepter": opensearch.ResourceInboundConnectionAccepter(),

"aws_opsworks_application": opsworks.ResourceApplication(),
"aws_opsworks_custom_layer": opsworks.ResourceCustomLayer(),
Expand Down
185 changes: 185 additions & 0 deletions internal/service/opensearch/inbound_connection_accepter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
package opensearch

import (
"context"
"fmt"
"log"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/opensearchservice"
"github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
)

func ResourceInboundConnectionAccepter() *schema.Resource {
return &schema.Resource{
CreateContext: resourceInboundConnectionAccepterCreate,
ReadContext: resourceInboundConnectionRead,
DeleteContext: resourceInboundConnectionDelete,
Importer: &schema.ResourceImporter{
State: func(d *schema.ResourceData, m interface{}) (result []*schema.ResourceData, err error) {
d.Set("connection_id", d.Id())

return []*schema.ResourceData{d}, nil
},
},

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

Schema: map[string]*schema.Schema{
"connection_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"connection_status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func resourceInboundConnectionAccepterCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).OpenSearchConn

// Create the Inbound Connection
acceptOpts := &opensearchservice.AcceptInboundConnectionInput{
ConnectionId: aws.String(d.Get("connection_id").(string)),
}

log.Printf("[DEBUG] Inbound Connection Accept options: %#v", acceptOpts)

resp, err := conn.AcceptInboundConnectionWithContext(ctx, acceptOpts)
if err != nil {
return diag.FromErr(fmt.Errorf("Error accepting Inbound Connection: %s", err))
}

// Get the ID and store it
d.SetId(aws.StringValue(resp.Connection.ConnectionId))
log.Printf("[INFO] Inbound Connection ID: %s", d.Id())

err = inboundConnectionWaitUntilActive(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate))
if err != nil {
return diag.FromErr(fmt.Errorf("Error waiting for Inbound Connection to become active: %s", err))
}

return resourceInboundConnectionRead(ctx, d, meta)
}

func resourceInboundConnectionRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).OpenSearchConn

ccscRaw, statusCode, err := inboundConnectionRefreshState(ctx, conn, d.Id())()

if err != nil {
return diag.FromErr(fmt.Errorf("Error reading Inbound Connection: %s", err))
}

ccsc := ccscRaw.(*opensearchservice.InboundConnection)
log.Printf("[DEBUG] Inbound Connection response: %#v", ccsc)

d.Set("connection_id", ccsc.ConnectionId)
d.Set("connection_status", statusCode)
return nil
}

func resourceInboundConnectionDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).OpenSearchConn

req := &opensearchservice.DeleteInboundConnectionInput{
ConnectionId: aws.String(d.Id()),
}

_, err := conn.DeleteInboundConnectionWithContext(ctx, req)

if tfawserr.ErrMessageContains(err, "ResourceNotFoundException", "") {
return nil
}

if err != nil {
return diag.FromErr(fmt.Errorf("Error deleting Inbound Connection (%s): %s", d.Id(), err))
}

if err := waitForInboundConnectionDeletion(ctx, conn, d.Id(), d.Timeout(schema.TimeoutDelete)); err != nil {
return diag.FromErr(fmt.Errorf("Error waiting for VPC Peering Connection (%s) to be deleted: %s", d.Id(), err))
}

return nil
}

func inboundConnectionRefreshState(ctx context.Context, conn *opensearchservice.OpenSearchService, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := conn.DescribeInboundConnectionsWithContext(ctx, &opensearchservice.DescribeInboundConnectionsInput{
Filters: []*opensearchservice.Filter{
{
Name: aws.String("connection-id"),
Values: []*string{aws.String(id)},
},
},
})
if err != nil {
return nil, "", err
}

if resp == nil || resp.Connections == nil ||
len(resp.Connections) == 0 || resp.Connections[0] == nil {
// Sometimes AWS just has consistency issues and doesn't see
// our connection yet. Return an empty state.
return nil, "", nil
}
ccsc := resp.Connections[0]
if ccsc.ConnectionStatus == nil {
// Sometimes AWS just has consistency issues and doesn't see
// our connection yet. Return an empty state.
return nil, "", nil
}
statusCode := aws.StringValue(ccsc.ConnectionStatus.StatusCode)

return ccsc, statusCode, nil
}
}

func inboundConnectionWaitUntilActive(ctx context.Context, conn *opensearchservice.OpenSearchService, id string, timeout time.Duration) error {
log.Printf("[DEBUG] Waiting for Inbound Connection (%s) to become available.", id)
stateConf := &resource.StateChangeConf{
Pending: []string{
opensearchservice.InboundConnectionStatusCodeProvisioning,
opensearchservice.InboundConnectionStatusCodeApproved,
},
Target: []string{
opensearchservice.InboundConnectionStatusCodeActive,
},
Refresh: inboundConnectionRefreshState(ctx, conn, id),
Timeout: timeout,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Inbound Connection (%s) to become available: %s", id, err)
}
return nil
}

func waitForInboundConnectionDeletion(ctx context.Context, conn *opensearchservice.OpenSearchService, id string, timeout time.Duration) error {
stateConf := &resource.StateChangeConf{
Pending: []string{
opensearchservice.InboundConnectionStatusCodeDeleting,
},
Target: []string{
opensearchservice.InboundConnectionStatusCodeDeleted,
},
Refresh: inboundConnectionRefreshState(ctx, conn, id),
Timeout: timeout,
}

_, err := stateConf.WaitForState()

return err
}
136 changes: 136 additions & 0 deletions internal/service/opensearch/inbound_connection_accepter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package opensearch_test

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/opensearchservice"
sdkacctest "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-provider-aws/internal/acctest"
)

func TestAccOpensearchInboundConnectionAccepter_basic(t *testing.T) {
var domain opensearchservice.DomainStatus
ri := sdkacctest.RandString(10)
name := fmt.Sprintf("tf-test-%s", ri)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, opensearchservice.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckDomainDestroy,
Steps: []resource.TestStep{
{
Config: testAccInboundConnectionAccepterConfig(name),
Check: resource.ComposeTestCheckFunc(
testAccCheckDomainExists("aws_opensearch_domain.domain_1", &domain),
testAccCheckDomainExists("aws_opensearch_domain.domain_2", &domain),
resource.TestCheckResourceAttr("aws_opensearch_inbound_connection_accepter.main", "connection_status", "ACTIVE"),
),
},
},
})
}

func testAccInboundConnectionAccepterConfig(name string) string {
// Satisfy the pw requirements
pw := fmt.Sprintf("Aa1-%s", sdkacctest.RandString(10))
return fmt.Sprintf(`
resource "aws_opensearch_domain" "domain_1" {
domain_name = "%s-1"
engine_version = "OpenSearch_1.1"
cluster_config {
instance_type = "t3.small.search" # supported in both aws and aws-us-gov
}
ebs_options {
ebs_enabled = true
volume_size = 10
}
node_to_node_encryption {
enabled = true
}
advanced_security_options {
enabled = true
internal_user_database_enabled = true
master_user_options {
master_user_name = "test"
master_user_password = "%s"
}
}
encrypt_at_rest {
enabled = true
}
domain_endpoint_options {
enforce_https = true
tls_security_policy = "Policy-Min-TLS-1-2-2019-07"
}
}
resource "aws_opensearch_domain" "domain_2" {
domain_name = "%s-2"
engine_version = "OpenSearch_1.1"
cluster_config {
instance_type = "t3.small.search" # supported in both aws and aws-us-gov
}
ebs_options {
ebs_enabled = true
volume_size = 10
}
node_to_node_encryption {
enabled = true
}
advanced_security_options {
enabled = true
internal_user_database_enabled = true
master_user_options {
master_user_name = "test"
master_user_password = "%s"
}
}
encrypt_at_rest {
enabled = true
}
domain_endpoint_options {
enforce_https = true
tls_security_policy = "Policy-Min-TLS-1-2-2019-07"
}
}
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
resource "aws_opensearch_outbound_connection" "main" {
connection_alias = "%s"
local_domain_info {
owner_id = data.aws_caller_identity.current.account_id
region = data.aws_region.current.name
domain_name = aws_opensearch_domain.domain_1.domain_name
}
remote_domain_info {
owner_id = data.aws_caller_identity.current.account_id
region = data.aws_region.current.name
domain_name = aws_opensearch_domain.domain_2.domain_name
}
}
resource "aws_opensearch_inbound_connection_accepter" "main" {
connection_id = aws_opensearch_outbound_connection.main.id
}
`, name, pw, name, pw, name)
}
Loading

0 comments on commit ca6abcc

Please sign in to comment.