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/appsync_api_cache - new resource #22578

Merged
merged 7 commits into from
Jan 18, 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/22578.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_appsync_api_cache
```
1 change: 1 addition & 0 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,7 @@ func Provider() *schema.Provider {
"aws_appstream_user": appstream.ResourceUser(),
"aws_appstream_user_stack_association": appstream.ResourceUserStackAssociation(),

"aws_appsync_api_cache": appsync.ResourceAPICache(),
"aws_appsync_api_key": appsync.ResourceAPIKey(),
"aws_appsync_datasource": appsync.ResourceDataSource(),
"aws_appsync_function": appsync.ResourceFunction(),
Expand Down
169 changes: 169 additions & 0 deletions internal/service/appsync/api_cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package appsync

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/appsync"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)

func ResourceAPICache() *schema.Resource {

return &schema.Resource{
Create: resourceAPICacheCreate,
Read: resourceAPICacheRead,
Update: resourceAPICacheUpdate,
Delete: resourceAPICacheDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"api_id": {
Type: schema.TypeString,
Required: true,
},
"api_caching_behavior": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(appsync.ApiCachingBehavior_Values(), false),
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(appsync.ApiCacheType_Values(), false),
},
"ttl": {
Type: schema.TypeInt,
Required: true,
},
"at_rest_encryption_enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
"transit_encryption_enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
},
},
}
}

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

apiID := d.Get("api_id").(string)

params := &appsync.CreateApiCacheInput{
ApiId: aws.String(apiID),
Type: aws.String(d.Get("type").(string)),
ApiCachingBehavior: aws.String(d.Get("api_caching_behavior").(string)),
Ttl: aws.Int64(int64(d.Get("ttl").(int))),
}

if v, ok := d.GetOk("at_rest_encryption_enabled"); ok {
params.AtRestEncryptionEnabled = aws.Bool(v.(bool))
}

if v, ok := d.GetOk("transit_encryption_enabled"); ok {
params.TransitEncryptionEnabled = aws.Bool(v.(bool))
}

_, err := conn.CreateApiCache(params)
if err != nil {
return fmt.Errorf("error creating Appsync API Cache: %w", err)
}

d.SetId(apiID)

if err := waitApiCacheAvailable(conn, d.Id()); err != nil {
return fmt.Errorf("error waiting for Appsync API Cache (%s) availability: %w", d.Id(), err)
}

return resourceAPICacheRead(d, meta)
}

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

cache, err := FindApiCacheByID(conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] AppSync API Cache (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}

if err != nil {
return fmt.Errorf("error getting Appsync API Cache %q: %s", d.Id(), err)
}

d.Set("api_id", d.Id())
d.Set("type", cache.Type)
d.Set("api_caching_behavior", cache.ApiCachingBehavior)
d.Set("ttl", cache.Ttl)
d.Set("at_rest_encryption_enabled", cache.AtRestEncryptionEnabled)
d.Set("transit_encryption_enabled", cache.TransitEncryptionEnabled)

return nil
}

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

params := &appsync.UpdateApiCacheInput{
ApiId: aws.String(d.Id()),
}

if d.HasChange("type") {
params.Type = aws.String(d.Get("type").(string))
}

if d.HasChange("api_caching_behavior") {
params.ApiCachingBehavior = aws.String(d.Get("api_caching_behavior").(string))
}

if d.HasChange("ttl") {
params.Ttl = aws.Int64(int64(d.Get("ttl").(int)))
}

_, err := conn.UpdateApiCache(params)
if err != nil {
return fmt.Errorf("error updating Appsync API Cache %q: %w", d.Id(), err)
}

if err := waitApiCacheAvailable(conn, d.Id()); err != nil {
return fmt.Errorf("error waiting for Appsync API Cache (%s) availability: %w", d.Id(), err)
}

return resourceAPICacheRead(d, meta)

}

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

input := &appsync.DeleteApiCacheInput{
ApiId: aws.String(d.Id()),
}
_, err := conn.DeleteApiCache(input)
if err != nil {
if tfawserr.ErrCodeEquals(err, appsync.ErrCodeNotFoundException) {
return nil
}
return fmt.Errorf("error deleting Appsync API Cache: %w", err)
}

if err := waitApiCacheDeleted(conn, d.Id()); err != nil {
return fmt.Errorf("error waiting for Appsync API Cache (%s) to be deleted: %w", d.Id(), err)
}

return nil
}
124 changes: 124 additions & 0 deletions internal/service/appsync/api_cache_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package appsync_test

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/appsync"
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"
tfappsync "github.com/hashicorp/terraform-provider-aws/internal/service/appsync"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
)

func testAccAppSyncApiCache_basic(t *testing.T) {
var apiCache appsync.ApiCache
resourceName := "aws_appsync_api_cache.test"
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(appsync.EndpointsID, t) },
ErrorCheck: acctest.ErrorCheck(t, appsync.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckApiCacheDestroy,
Steps: []resource.TestStep{
{
Config: testAccAppsyncApiCacheBasicConfig(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckApiCacheExists(resourceName, &apiCache),
resource.TestCheckResourceAttrPair(resourceName, "api_id", "aws_appsync_graphql_api.test", "id"),
resource.TestCheckResourceAttr(resourceName, "type", "SMALL"),
resource.TestCheckResourceAttr(resourceName, "api_caching_behavior", "FULL_REQUEST_CACHING"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func testAccAppSyncApiCache_disappears(t *testing.T) {
var apiCache appsync.ApiCache
resourceName := "aws_appsync_api_cache.test"
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t); acctest.PreCheckPartitionHasService(appsync.EndpointsID, t) },
ErrorCheck: acctest.ErrorCheck(t, appsync.EndpointsID),
Providers: acctest.Providers,
CheckDestroy: testAccCheckApiCacheDestroy,
Steps: []resource.TestStep{
{
Config: testAccAppsyncApiCacheBasicConfig(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckApiCacheExists(resourceName, &apiCache),
acctest.CheckResourceDisappears(acctest.Provider, tfappsync.ResourceAPICache(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckApiCacheDestroy(s *terraform.State) error {
conn := acctest.Provider.Meta().(*conns.AWSClient).AppSyncConn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_appsync_api_cache" {
continue
}

_, err := tfappsync.FindApiCacheByID(conn, rs.Primary.ID)
if err == nil {
if tfresource.NotFound(err) {
return nil
}
return err
}

return nil

}
return nil
}

func testAccCheckApiCacheExists(resourceName string, apiCache *appsync.ApiCache) resource.TestCheckFunc {
return func(s *terraform.State) error {

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("Appsync Api Cache Not found in state: %s", resourceName)
}

conn := acctest.Provider.Meta().(*conns.AWSClient).AppSyncConn
cache, err := tfappsync.FindApiCacheByID(conn, rs.Primary.ID)
if err != nil {
return err
}

*apiCache = *cache

return nil
}
}

func testAccAppsyncApiCacheBasicConfig(rName string) string {
return fmt.Sprintf(`
resource "aws_appsync_graphql_api" "test" {
authentication_type = "API_KEY"
name = %[1]q
}

resource "aws_appsync_api_cache" "test" {
api_id = aws_appsync_graphql_api.test.id
type = "SMALL"
api_caching_behavior = "FULL_REQUEST_CACHING"
ttl = 60
}
`, rName)
}
4 changes: 4 additions & 0 deletions internal/service/appsync/appsync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ func TestAccAppSync_serial(t *testing.T) {
"caching": testAccAppSyncResolver_caching,
"sync": testAccAppSyncResolver_syncConfig,
},
"ApiCache": {
"basic": testAccAppSyncApiCache_basic,
"disappears": testAccAppSyncApiCache_disappears,
},
}

for group, m := range testCases {
Expand Down
33 changes: 33 additions & 0 deletions internal/service/appsync/find.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package appsync

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

func FindApiCacheByID(conn *appsync.AppSync, id string) (*appsync.ApiCache, error) {
input := &appsync.GetApiCacheInput{
ApiId: aws.String(id),
}
out, err := conn.GetApiCache(input)

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

if err != nil {
return nil, err
}

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

return out.ApiCache, nil
}
24 changes: 24 additions & 0 deletions internal/service/appsync/status.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package appsync

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

func StatusApiCache(conn *appsync.AppSync, name string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
output, err := FindApiCacheByID(conn, name)

if tfresource.NotFound(err) {
return nil, "", nil
}

if err != nil {
return nil, "", err
}

return output, aws.StringValue(output.Status), nil
}
}
Loading