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: appsync_graphql_api #2494

Merged
merged 6 commits into from
Feb 12, 2018
Merged
Show file tree
Hide file tree
Changes from 4 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 aws/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/aws/aws-sdk-go/service/acm"
"github.com/aws/aws-sdk-go/service/apigateway"
"github.com/aws/aws-sdk-go/service/applicationautoscaling"
"github.com/aws/aws-sdk-go/service/appsync"
"github.com/aws/aws-sdk-go/service/athena"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/batch"
Expand Down Expand Up @@ -194,6 +195,7 @@ type AWSClient struct {
athenaconn *athena.Athena
dxconn *directconnect.DirectConnect
mediastoreconn *mediastore.MediaStore
appsyncconn *appsync.AppSync
}

func (c *AWSClient) S3() *s3.S3 {
Expand Down Expand Up @@ -436,6 +438,7 @@ func (c *Config) Client() (interface{}, error) {
client.athenaconn = athena.New(sess)
client.dxconn = directconnect.New(sess)
client.mediastoreconn = mediastore.New(sess)
client.appsyncconn = appsync.New(sess)

// Workaround for https://github.com/aws/aws-sdk-go/issues/1376
client.kinesisconn.Handlers.Retry.PushBack(func(r *request.Request) {
Expand Down
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ func Provider() terraform.ResourceProvider {
"aws_appautoscaling_target": resourceAwsAppautoscalingTarget(),
"aws_appautoscaling_policy": resourceAwsAppautoscalingPolicy(),
"aws_appautoscaling_scheduled_action": resourceAwsAppautoscalingScheduledAction(),
"aws_appsync_graphql_api": resourceAwsAppsyncGraphqlApi(),
"aws_athena_database": resourceAwsAthenaDatabase(),
"aws_athena_named_query": resourceAwsAthenaNamedQuery(),
"aws_autoscaling_attachment": resourceAwsAutoscalingAttachment(),
Expand Down
215 changes: 215 additions & 0 deletions aws/resource_aws_appsync_graphql_api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
package aws

import (
"fmt"
"regexp"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/appsync"
"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsAppsyncGraphqlApi() *schema.Resource {
return &schema.Resource{
Create: resourceAwsAppsyncGraphqlApiCreate,
Read: resourceAwsAppsyncGraphqlApiRead,
Update: resourceAwsAppsyncGraphqlApiUpdate,
Delete: resourceAwsAppsyncGraphqlApiDelete,

Schema: map[string]*schema.Schema{
"authentication_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToUpper(v.(string))
validTypes := []string{"API_KEY", "AWS_IAM", "AMAZON_COGNITO_USER_POOLS"}
for _, str := range validTypes {
if value == str {
return
}
}
errors = append(errors, fmt.Errorf("expected %s to be one of %v, got %s", k, validTypes, value))
return
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you mind using constants available in the SDK?
Also we have a built-in validation helper for this:

ValidateFunc: validation.StringInSlice([]string{
  appsync.AuthenticationTypeApiKey,
  appsync.AuthenticationTypeAwsIam,
  appsync.AuthenticationTypeAmazonCognitoUserPools,
}, false),

😉

},
StateFunc: func(v interface{}) string {
return strings.ToUpper(v.(string))
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we avoid this just by tightening the validation above (i.e. by not accepting lowercase)?

},
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if !regexp.MustCompile(`[_A-Za-z][_0-9A-Za-z]*`).MatchString(value) {
errors = append(errors, fmt.Errorf("%q must match [_A-Za-z][_0-9A-Za-z]*", k))
}
return
},
},
"user_pool_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"app_id_client_regex": {
Type: schema.TypeString,
Optional: true,
},
"aws_region": {
Type: schema.TypeString,
Required: true,
},
"default_action": {
Type: schema.TypeString,
Required: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToUpper(v.(string))
validTypes := []string{"ALLOW", "DENY"}
for _, str := range validTypes {
if value == str {
return
}
}
errors = append(errors, fmt.Errorf("expected %s to be one of %v, got %s", k, validTypes, value))
return
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question as above ^

StateFunc: func(v interface{}) string {
return strings.ToUpper(v.(string))
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question as above ^

},
"user_pool_id": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

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

input := &appsync.CreateGraphqlApiInput{
AuthenticationType: aws.String(d.Get("authentication_type").(string)),
Name: aws.String(d.Get("name").(string)),
UserPoolConfig: expandAppsyncGraphqlApiUserPoolConfig(d.Get("user_pool_config").([]interface{})),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am admittedly surprised this isn't causing a crash in the attached test where user_pool_config is not present. It's no big deal as it's not crashing, but it may be safer to always wrap optional fields in d.GetOk().

}

resp, err := conn.CreateGraphqlApi(input)
if err != nil {
return err
}

d.SetId(*resp.GraphqlApi.ApiId)
d.Set("arn", resp.GraphqlApi.Arn)
return nil
}

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

input := &appsync.GetGraphqlApiInput{
ApiId: aws.String(d.Id()),
}

resp, err := conn.GetGraphqlApi(input)
if err != nil {
if isAWSErr(err, appsync.ErrCodeNotFoundException, "") {
d.SetId("")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mind adding our usual WARN log message here?

return nil
}
return err
}

d.Set("authentication_type", resp.GraphqlApi.AuthenticationType)
d.Set("name", resp.GraphqlApi.Name)
d.Set("user_pool_config", flattenAppsyncGraphqlApiUserPoolConfig(resp.GraphqlApi.UserPoolConfig))
d.Set("arn", resp.GraphqlApi.Arn)
return nil
}

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

input := &appsync.UpdateGraphqlApiInput{
ApiId: aws.String(d.Id()),
Name: aws.String(d.Get("name").(string)),
}

if d.HasChange("authentication_type") {
input.AuthenticationType = aws.String(d.Get("authentication_type").(string))
}
if d.HasChange("user_pool_config") {
input.UserPoolConfig = expandAppsyncGraphqlApiUserPoolConfig(d.Get("user_pool_config").([]interface{}))
}

_, err := conn.UpdateGraphqlApi(input)
if err != nil {
if isAWSErr(err, appsync.ErrCodeNotFoundException, "") {
d.SetId("")
return nil
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't think of a reason why the user would want to silently fail updating API when it doesn't exist. 🤔 Is there any?

The most common cases (refresh, deletion) are covered correctly, but I think we should just error out on update.

return err
}

return resourceAwsAppsyncGraphqlApiRead(d, meta)
}

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

input := &appsync.DeleteGraphqlApiInput{
ApiId: aws.String(d.Id()),
}
_, err := conn.DeleteGraphqlApi(input)
if err != nil {
if isAWSErr(err, appsync.ErrCodeNotFoundException, "") {
d.SetId("")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: I know we still have it in many resources, but it's redundant. The ID is emptied automatically in the core.

See https://github.com/hashicorp/terraform/blob/096847c9f774bfb946de7413260b30f9f6041241/helper/schema/resource.go#L197-L206

return nil
}
return err
}

d.SetId("")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise ^

return nil
}

func expandAppsyncGraphqlApiUserPoolConfig(config []interface{}) *appsync.UserPoolConfig {
if len(config) < 1 {
return nil
}
cg := config[0].(map[string]interface{})
upc := &appsync.UserPoolConfig{
AwsRegion: aws.String(cg["aws_region"].(string)),
DefaultAction: aws.String(cg["default_action"].(string)),
UserPoolId: aws.String(cg["user_pool_id"].(string)),
}
if v, ok := cg["app_id_client_regex"].(string); ok && v != "" {
upc.AppIdClientRegex = aws.String(v)
}
return upc
}

func flattenAppsyncGraphqlApiUserPoolConfig(upc *appsync.UserPoolConfig) []interface{} {
if upc == nil {
return []interface{}{}
}
m := make(map[string]interface{}, 1)

m["aws_region"] = *upc.AwsRegion
m["default_action"] = *upc.DefaultAction
m["user_pool_id"] = *upc.UserPoolId
if upc.AppIdClientRegex != nil {
m["app_id_client_regex"] = *upc.AppIdClientRegex
}

return []interface{}{m}
}
112 changes: 112 additions & 0 deletions aws/resource_aws_appsync_graphql_api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package aws

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/appsync"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccAwsAppsyncGraphqlApi_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAwsAppsyncGraphqlApiDestroy,
Steps: []resource.TestStep{
{
Config: testAccAppsyncGraphqlApiConfig_apikey(acctest.RandString(5)),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsAppsyncGraphqlApiExists("aws_appsync_graphql_api.test_apikey"),
resource.TestCheckResourceAttrSet("aws_appsync_graphql_api.test_apikey", "arn"),
),
},
{
Config: testAccAppsyncGraphqlApiConfig_iam(acctest.RandString(5)),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsAppsyncGraphqlApiExists("aws_appsync_graphql_api.test_iam"),
resource.TestCheckResourceAttrSet("aws_appsync_graphql_api.test_iam", "arn"),
),
},
{
Config: testAccAppsyncGraphqlApiConfig_cognito(acctest.RandString(5)),
Check: resource.ComposeTestCheckFunc(
testAccCheckAwsAppsyncGraphqlApiExists("aws_appsync_graphql_api.test_cognito"),
resource.TestCheckResourceAttrSet("aws_appsync_graphql_api.test_cognito", "arn"),
),
},
},
})
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mind separating out the 3 steps into 3 tests? This will allow us to run them in parallel more easily. You can keep testAccAppsyncGraphqlApiConfig_apikey in _basic here, just to stick to the convention.


func testAccCheckAwsAppsyncGraphqlApiDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).appsyncconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_appsync_graphql_api" {
continue
}

input := &appsync.GetGraphqlApiInput{
ApiId: aws.String(rs.Primary.ID),
}

_, err := conn.GetGraphqlApi(input)
if err != nil {
if isAWSErr(err, appsync.ErrCodeNotFoundException, "") {
return nil
}
return err
}
}
return nil
}

func testAccCheckAwsAppsyncGraphqlApiExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}

return nil
}
}

func testAccAppsyncGraphqlApiConfig_apikey(rName string) string {
return fmt.Sprintf(`
resource "aws_appsync_graphql_api" "test_apikey" {
authentication_type = "API_KEY"
name = "tf_appsync_%s"
}
`, rName)
}

func testAccAppsyncGraphqlApiConfig_iam(rName string) string {
return fmt.Sprintf(`
resource "aws_appsync_graphql_api" "test_iam" {
authentication_type = "AWS_IAM"
name = "tf_appsync_%s"
}
`, rName)
}

func testAccAppsyncGraphqlApiConfig_cognito(rName string) string {
return fmt.Sprintf(`
resource "aws_cognito_user_pool" "test" {
name = "tf-%s"
}

resource "aws_appsync_graphql_api" "test_cognito" {
authentication_type = "AMAZON_COGNITO_USER_POOLS"
name = "tf_appsync_%s"
user_pool_config {
aws_region = "us-west-2"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although our tests commonly run in us-west-2 I think we should keep the test region-agnostic. Do you mind adding aws_region data source here?

https://www.terraform.io/docs/providers/aws/d/region.html

default_action = "ALLOW"
user_pool_id = "${aws_cognito_user_pool.test.id}"
}
}
`, rName, rName)
}
9 changes: 9 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,15 @@
</ul>
</li>

<li<%= sidebar_current("docs-aws-resource-appsync") %>>
<a href="#">AppSync Resources</a>
<ul class="nav nav-visible">
<li<%= sidebar_current("docs-aws-resource-appsync-graphql-api") %>>
<a href="/docs/providers/aws/r/appsync_graphql_api.html">aws_appsync_graphql_api</a>
</li>
</ul>
</li>

<li<%= sidebar_current("docs-aws-resource-athena") %>>
<a href="#">Athena Resources</a>
<ul class="nav nav-visible">
Expand Down
Loading