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_db_proxy_default_target_group #12743

Merged
merged 5 commits into from
Sep 10, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,7 @@ func Provider() *schema.Provider {
"aws_db_option_group": resourceAwsDbOptionGroup(),
"aws_db_parameter_group": resourceAwsDbParameterGroup(),
"aws_db_proxy": resourceAwsDbProxy(),
"aws_db_proxy_default_target_group": resourceAwsDbProxyDefaultTargetGroup(),
"aws_db_security_group": resourceAwsDbSecurityGroup(),
"aws_db_snapshot": resourceAwsDbSnapshot(),
"aws_db_subnet_group": resourceAwsDbSubnetGroup(),
Expand Down
235 changes: 235 additions & 0 deletions aws/resource_aws_db_proxy_default_target_group.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
package aws

import (
"fmt"
"log"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/rds"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)

func resourceAwsDbProxyDefaultTargetGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDbProxyDefaultTargetGroupUpdate,
Read: resourceAwsDbProxyDefaultTargetGroupRead,
Update: resourceAwsDbProxyDefaultTargetGroupUpdate,
Delete: resourceAwsDbProxyDefaultTargetGroupDelete,
gazoakley marked this conversation as resolved.
Show resolved Hide resolved
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
gazoakley marked this conversation as resolved.
Show resolved Hide resolved
},

Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"db_proxy_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateRdsIdentifier,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"connection_pool_config": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
ForceNew: false,
gazoakley marked this conversation as resolved.
Show resolved Hide resolved
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"connection_borrow_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 120,
ValidateFunc: validation.IntBetween(0, 3600),
},
"init_query": {
Type: schema.TypeString,
Optional: true,
Default: "",
gazoakley marked this conversation as resolved.
Show resolved Hide resolved
},
"max_connections_percent": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
ValidateFunc: validation.IntBetween(1, 100),
},
"max_idle_connections_percent": {
Type: schema.TypeInt,
Optional: true,
Default: 50,
ValidateFunc: validation.IntBetween(0, 100),
},
"session_pinning_filters": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
// This isn't available as a constant
ValidateFunc: validation.StringInSlice([]string{
"EXCLUDE_VARIABLE_SETS",
}, false),
},
Set: schema.HashString,
},
},
},
},
},
}
}

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

tg, err := resourceAwsDbProxyDefaultTargetGroupGet(conn, d.Id())

if err != nil {
if isAWSErr(err, rds.ErrCodeDBProxyNotFoundFault, "") {
log.Printf("[WARN] DB Proxy (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
return err
gazoakley marked this conversation as resolved.
Show resolved Hide resolved
}

if tg == nil {
log.Printf("[WARN] DB Proxy default target group (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

d.Set("arn", tg.TargetGroupArn)
d.Set("db_proxy_name", tg.DBProxyName)
d.Set("name", tg.TargetGroupName)

cpc := tg.ConnectionPoolConfig
d.Set("connection_pool_config", flattenDbProxyTargetGroupConnectionPoolConfig(cpc))

return nil
}

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

d.SetId(d.Get("db_proxy_name").(string))
gazoakley marked this conversation as resolved.
Show resolved Hide resolved

params := rds.ModifyDBProxyTargetGroupInput{
DBProxyName: aws.String(d.Get("db_proxy_name").(string)),
TargetGroupName: aws.String("default"),
}

if v, ok := d.GetOk("connection_pool_config"); ok {
params.ConnectionPoolConfig = expandDbProxyConnectionPoolConfig(v.([]interface{}))
}

log.Printf("[DEBUG] Update DB Proxy default target group: %#v", params)
_, err := conn.ModifyDBProxyTargetGroup(&params)
if err != nil {
return fmt.Errorf("Error updating DB Proxy default target group: %s", err)
gazoakley marked this conversation as resolved.
Show resolved Hide resolved
}

stateChangeConf := &resource.StateChangeConf{
Pending: []string{rds.DBProxyStatusModifying},
Target: []string{rds.DBProxyStatusAvailable},
Refresh: resourceAwsDbProxyDefaultTargetGroupRefreshFunc(conn, d.Id()),
Timeout: d.Timeout(schema.TimeoutCreate),
gazoakley marked this conversation as resolved.
Show resolved Hide resolved
}

_, err = stateChangeConf.WaitForState()
if err != nil {
return fmt.Errorf("Error waiting for DB Proxy default target group update: %s", err)
}

return resourceAwsDbProxyDefaultTargetGroupRead(d, meta)
}

func expandDbProxyConnectionPoolConfig(configs []interface{}) *rds.ConnectionPoolConfiguration {
if len(configs) < 1 {
return nil
}

config := configs[0].(map[string]interface{})

result := &rds.ConnectionPoolConfiguration{
ConnectionBorrowTimeout: aws.Int64(int64(config["connection_borrow_timeout"].(int))),
InitQuery: aws.String(config["init_query"].(string)),
MaxConnectionsPercent: aws.Int64(int64(config["max_connections_percent"].(int))),
MaxIdleConnectionsPercent: aws.Int64(int64(config["max_idle_connections_percent"].(int))),
SessionPinningFilters: expandStringSet(config["session_pinning_filters"].(*schema.Set)),
}

return result
}

func flattenDbProxyTargetGroupConnectionPoolConfig(cpc *rds.ConnectionPoolConfigurationInfo) []interface{} {
if cpc == nil {
return []interface{}{}
}

m := make(map[string]interface{})
m["connection_borrow_timeout"] = aws.Int64Value(cpc.ConnectionBorrowTimeout)
m["init_query"] = aws.StringValue(cpc.InitQuery)
m["max_connections_percent"] = aws.Int64Value(cpc.MaxConnectionsPercent)
m["max_idle_connections_percent"] = aws.Int64Value(cpc.MaxIdleConnectionsPercent)
m["session_pinning_filters"] = flattenStringSet(cpc.SessionPinningFilters)

return []interface{}{m}
}

func resourceAwsDbProxyDefaultTargetGroupGet(conn *rds.RDS, proxyName string) (*rds.DBProxyTargetGroup, error) {
params := &rds.DescribeDBProxyTargetGroupsInput{
DBProxyName: aws.String(proxyName),
}

var defaultTargetGroup *rds.DBProxyTargetGroup
err := conn.DescribeDBProxyTargetGroupsPages(params, func(page *rds.DescribeDBProxyTargetGroupsOutput, lastPage bool) bool {
for _, targetGroup := range page.TargetGroups {
if *targetGroup.IsDefault {
defaultTargetGroup = targetGroup
return false
}
}
return !lastPage
})

if err != nil {
return nil, err
}

// Return default target group
return defaultTargetGroup, nil
}

func resourceAwsDbProxyDefaultTargetGroupRefreshFunc(conn *rds.RDS, proxyName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
tg, err := resourceAwsDbProxyDefaultTargetGroupGet(conn, proxyName)

if err != nil {
if isAWSErr(err, rds.ErrCodeDBProxyNotFoundFault, "") {
return 42, "", nil
}
return 42, "", err
}

return tg, *tg.Status, nil
}
}

func resourceAwsDbProxyDefaultTargetGroupDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy DB Proxy default target group. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}
Loading