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

Add support for elasticsearch outbound connection and relevant accepter #22988

Merged
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
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 @@ -1818,9 +1818,11 @@ func New(_ context.Context) (*schema.Provider, error) {
"aws_networkmanager_vpc_attachment": networkmanager.ResourceVPCAttachment(),
"aws_networkmanager_site_to_site_vpn_attachment": networkmanager.ResourceSiteToSiteVPNAttachment(),

"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
184 changes: 184 additions & 0 deletions internal/service/opensearch/inbound_connection_accepter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
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),
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.ErrCodeEquals(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
}
168 changes: 168 additions & 0 deletions internal/service/opensearch/inbound_connection_accepter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
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"
tfopensearch "github.com/hashicorp/terraform-provider-aws/internal/service/opensearch"
)

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

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, opensearchservice.EndpointsID),
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
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(resourceName, "connection_status", "ACTIVE"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

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

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, opensearchservice.EndpointsID),
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
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),
acctest.CheckResourceDisappears(acctest.Provider, tfopensearch.ResourceInboundConnectionAccepter(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

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" "test" {
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" "test" {
connection_id = aws_opensearch_outbound_connection.test.id
}
`, name, pw, name, pw, name)
}
Loading