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

r/redshiftdata_statement - new resource #25104

Merged
merged 8 commits into from
Jun 1, 2022
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: 3 additions & 0 deletions .changelog/25104.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_redshiftdata_statement
```
3 changes: 3 additions & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ import (
"github.com/hashicorp/terraform-provider-aws/internal/service/ram"
"github.com/hashicorp/terraform-provider-aws/internal/service/rds"
"github.com/hashicorp/terraform-provider-aws/internal/service/redshift"
"github.com/hashicorp/terraform-provider-aws/internal/service/redshiftdata"
"github.com/hashicorp/terraform-provider-aws/internal/service/resourcegroups"
"github.com/hashicorp/terraform-provider-aws/internal/service/resourcegroupstaggingapi"
"github.com/hashicorp/terraform-provider-aws/internal/service/route53"
Expand Down Expand Up @@ -1778,6 +1779,8 @@ func Provider() *schema.Provider {
"aws_redshift_subnet_group": redshift.ResourceSubnetGroup(),
"aws_redshift_usage_limit": redshift.ResourceUsageLimit(),

"aws_redshiftdata_statement": redshiftdata.ResourceStatement(),

"aws_resourcegroups_group": resourcegroups.ResourceGroup(),

"aws_route53_delegation_set": route53.ResourceDelegationSet(),
Expand Down
34 changes: 34 additions & 0 deletions internal/service/redshiftdata/find.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package redshiftdata

import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/redshiftdataapiservice"
"github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)

func FindStatementByID(conn *redshiftdataapiservice.RedshiftDataAPIService, id string) (*redshiftdataapiservice.DescribeStatementOutput, error) {
input := &redshiftdataapiservice.DescribeStatementInput{
Id: aws.String(id),
}

output, err := conn.DescribeStatement(input)

if tfawserr.ErrCodeEquals(err, redshiftdataapiservice.ErrCodeResourceNotFoundException) {
return nil, &resource.NotFoundError{
LastError: err,
LastRequest: input,
}
}

if err != nil {
return nil, err
}

if output == nil {
return nil, tfresource.NewEmptyResultError(input)
}

return output, nil
}
237 changes: 237 additions & 0 deletions internal/service/redshiftdata/statement.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
package redshiftdata

import (
"fmt"
"log"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/redshiftdataapiservice"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)

func ResourceStatement() *schema.Resource {
return &schema.Resource{
Create: resourceStatementCreate,
Read: resourceStatementRead,
Delete: schema.Noop,

Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

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

Schema: map[string]*schema.Schema{
"cluster_identifier": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"database": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"db_user": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"parameters": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MinItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"value": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
},
},
"secret_arn": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: verify.ValidARN,
},
"sql": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"statement_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"with_event": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
},
}
}

func resourceStatementCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).RedshiftDataConn

input := &redshiftdataapiservice.ExecuteStatementInput{
ClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)),
Database: aws.String(d.Get("database").(string)),
Sql: aws.String(d.Get("sql").(string)),
WithEvent: aws.Bool(d.Get("with_event").(bool)),
}

if v, ok := d.GetOk("db_user"); ok {
input.DbUser = aws.String(v.(string))
}

if v, ok := d.GetOk("parameters"); ok && len(v.([]interface{})) > 0 {
input.Parameters = expandParameters(v.([]interface{}))
}

if v, ok := d.GetOk("secret_arn"); ok {
input.SecretArn = aws.String(v.(string))
}

if v, ok := d.GetOk("statement_name"); ok {
input.StatementName = aws.String(v.(string))
}

output, err := conn.ExecuteStatement(input)

if err != nil {
return fmt.Errorf("executing Redshift Data Statement: %w", err)
}

d.SetId(aws.StringValue(output.Id))

if _, err := waitStatementFinished(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil {
return fmt.Errorf("waiting for Redshift Data Statement (%s) to finish: %w", d.Id(), err)
}

return resourceStatementRead(d, meta)
}

func resourceStatementRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).RedshiftDataConn

sub, err := FindStatementByID(conn, d.Id())

if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] Redshift Data Statement (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

if err != nil {
return fmt.Errorf("reading Redshift Data Statement (%s): %w", d.Id(), err)
}

d.Set("cluster_identifier", sub.ClusterIdentifier)
d.Set("secret_arn", sub.SecretArn)
d.Set("database", d.Get("database").(string))
d.Set("db_user", d.Get("db_user").(string))
d.Set("sql", sub.QueryString)

if err := d.Set("parameters", flattenParameters(sub.QueryParameters)); err != nil {
return fmt.Errorf("setting parameters: %w", err)
}

return nil
}

func expandParameter(tfMap map[string]interface{}) *redshiftdataapiservice.SqlParameter {
if tfMap == nil {
return nil
}

apiObject := &redshiftdataapiservice.SqlParameter{}

if v, ok := tfMap["name"].(string); ok {
apiObject.Name = aws.String(v)
}

if v, ok := tfMap["value"].(string); ok {
apiObject.Value = aws.String(v)
}

return apiObject
}

func expandParameters(tfList []interface{}) []*redshiftdataapiservice.SqlParameter {
if len(tfList) == 0 {
return nil
}

var apiObjects []*redshiftdataapiservice.SqlParameter

for _, tfMapRaw := range tfList {
tfMap, ok := tfMapRaw.(map[string]interface{})

if !ok {
continue
}

apiObject := expandParameter(tfMap)

if apiObject == nil {
continue
}

apiObjects = append(apiObjects, apiObject)
}

return apiObjects
}

func flattenParameter(apiObject *redshiftdataapiservice.SqlParameter) map[string]interface{} {
if apiObject == nil {
return nil
}

tfMap := map[string]interface{}{}

if v := apiObject.Name; v != nil {
tfMap["name"] = aws.StringValue(v)
}

if v := apiObject.Value; v != nil {
tfMap["value"] = aws.StringValue(v)
}
return tfMap
}

func flattenParameters(apiObjects []*redshiftdataapiservice.SqlParameter) []interface{} {
if len(apiObjects) == 0 {
return nil
}

var tfList []interface{}

for _, apiObject := range apiObjects {
if apiObject == nil {
continue
}

tfList = append(tfList, flattenParameter(apiObject))
}

return tfList
}
92 changes: 92 additions & 0 deletions internal/service/redshiftdata/statement_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package redshiftdata_test

import (
"fmt"
"testing"

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

func TestAccRedshiftDataStatement_basic(t *testing.T) {
var v redshiftdataapiservice.DescribeStatementOutput
resourceName := "aws_redshiftdata_statement.test"
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ErrorCheck: acctest.ErrorCheck(t, redshiftdataapiservice.EndpointsID),
ProviderFactories: acctest.ProviderFactories,
CheckDestroy: nil,
Steps: []resource.TestStep{
{
Config: testAccStatementConfigBasic(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckStatementExists(resourceName, &v),
resource.TestCheckResourceAttrPair(resourceName, "cluster_identifier", "aws_redshift_cluster.test", "cluster_identifier"),
resource.TestCheckResourceAttr(resourceName, "sql", "CREATE GROUP group_name;"),
resource.TestCheckResourceAttr(resourceName, "parameters.#", "0"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"database", "db_user"},
},
},
})
}

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

if rs.Primary.ID == "" {
return fmt.Errorf("No Redshift Data Statement ID is set")
}

conn := acctest.Provider.Meta().(*conns.AWSClient).RedshiftDataConn

output, err := tfredshiftdata.FindStatementByID(conn, rs.Primary.ID)

if err != nil {
return err
}

*v = *output

return nil
}
}

func testAccStatementConfigBasic(rName string) string {
return acctest.ConfigCompose(acctest.ConfigAvailableAZsNoOptInExclude("usw2-az2"), fmt.Sprintf(`
resource "aws_redshift_cluster" "test" {
cluster_identifier = %[1]q
availability_zone = data.aws_availability_zones.available.names[0]
database_name = "mydb"
master_username = "foo_test"
master_password = "Mustbe8characters"
node_type = "dc2.large"
automated_snapshot_retention_period = 0
allow_version_upgrade = false
skip_final_snapshot = true
}

resource "aws_redshiftdata_statement" "test" {
cluster_identifier = aws_redshift_cluster.test.cluster_identifier
database = aws_redshift_cluster.test.database_name
db_user = aws_redshift_cluster.test.master_username
sql = "CREATE GROUP group_name;"
}
`, rName))
}
Loading