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/sagemaker_model_package_group_policy - new resource #21250

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
3 changes: 3 additions & 0 deletions .changelog/21250.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
aws_sagemaker_model_package_group_policy
```
26 changes: 26 additions & 0 deletions aws/internal/service/sagemaker/finder/finder.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,32 @@ func ModelPackageGroupByName(conn *sagemaker.SageMaker, name string) (*sagemaker
return output, nil
}

func ModelPackageGroupPolicyByName(conn *sagemaker.SageMaker, name string) (*sagemaker.GetModelPackageGroupPolicyOutput, error) {
input := &sagemaker.GetModelPackageGroupPolicyInput{
ModelPackageGroupName: aws.String(name),
}

output, err := conn.GetModelPackageGroupPolicy(input)

if tfawserr.ErrMessageContains(err, tfsagemaker.ErrCodeValidationException, "Cannot find Model Package Group") ||
tfawserr.ErrMessageContains(err, tfsagemaker.ErrCodeValidationException, "Cannot find resource policy") {
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
}

// ImageByName returns the Image corresponding to the specified name.
// Returns nil if no Image is found.
func ImageByName(conn *sagemaker.SageMaker, name string) (*sagemaker.DescribeImageOutput, error) {
Expand Down
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1072,6 +1072,7 @@ func Provider() *schema.Provider {
"aws_sagemaker_human_task_ui": resourceAwsSagemakerHumanTaskUi(),
"aws_sagemaker_model": resourceAwsSagemakerModel(),
"aws_sagemaker_model_package_group": resourceAwsSagemakerModelPackageGroup(),
"aws_sagemaker_model_package_group_policy": resourceAwsSagemakerModelPackageGroupPolicy(),
"aws_sagemaker_notebook_instance_lifecycle_configuration": resourceAwsSagemakerNotebookInstanceLifeCycleConfiguration(),
"aws_sagemaker_notebook_instance": resourceAwsSagemakerNotebookInstance(),
"aws_sagemaker_studio_lifecycle_config": resourceAwsSagemakerStudioLifecycleConfig(),
Expand Down
98 changes: 98 additions & 0 deletions aws/resource_aws_sagemaker_model_package_group_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package aws

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sagemaker"
"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"
tfsagemaker "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/sagemaker"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/service/sagemaker/finder"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/tfresource"
)

func resourceAwsSagemakerModelPackageGroupPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceAwsSagemakerModelPackageGroupPolicyPut,
Read: resourceAwsSagemakerModelPackageGroupPolicyRead,
Update: resourceAwsSagemakerModelPackageGroupPolicyPut,
Delete: resourceAwsSagemakerModelPackageGroupPolicyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"model_package_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_policy": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsJSON,
DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs,
},
},
}
}

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

name := d.Get("model_package_group_name").(string)
input := &sagemaker.PutModelPackageGroupPolicyInput{
ModelPackageGroupName: aws.String(name),
ResourcePolicy: aws.String(d.Get("resource_policy").(string)),
}

_, err := conn.PutModelPackageGroupPolicy(input)
if err != nil {
return fmt.Errorf("error creating SageMaker Model Package Group Policy %s: %w", name, err)
}

d.SetId(name)

return resourceAwsSagemakerModelPackageGroupPolicyRead(d, meta)
}

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

mpg, err := finder.ModelPackageGroupPolicyByName(conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] Unable to find SageMaker Model Package Group Policy (%s); removing from state", d.Id())
d.SetId("")
return nil
}

if err != nil {
return fmt.Errorf("error reading SageMaker Model Package Group Policy (%s): %w", d.Id(), err)
}

d.Set("model_package_group_name", d.Id())
d.Set("resource_policy", mpg.ResourcePolicy)

return nil
}

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

input := &sagemaker.DeleteModelPackageGroupPolicyInput{
ModelPackageGroupName: aws.String(d.Id()),
}

if _, err := conn.DeleteModelPackageGroupPolicy(input); err != nil {
if tfawserr.ErrMessageContains(err, tfsagemaker.ErrCodeValidationException, "Cannot find Model Package Group") ||
tfawserr.ErrMessageContains(err, tfsagemaker.ErrCodeValidationException, "Cannot find resource policy") {
return nil
}
return fmt.Errorf("error deleting SageMaker Model Package Group Policy (%s): %w", d.Id(), err)
}

return nil
}
159 changes: 159 additions & 0 deletions aws/resource_aws_sagemaker_model_package_group_policy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package aws

import (
"fmt"
"testing"

"github.com/aws/aws-sdk-go/service/sagemaker"
"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/terraform-providers/terraform-provider-aws/aws/internal/service/sagemaker/finder"
"github.com/terraform-providers/terraform-provider-aws/aws/internal/tfresource"
)

func TestAccAWSSagemakerModelPackageGroupPolicy_basic(t *testing.T) {
var mpg sagemaker.GetModelPackageGroupPolicyOutput
rName := acctest.RandomWithPrefix("tf-acc-test")
resourceName := "aws_sagemaker_model_package_group_policy.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, sagemaker.EndpointsID),
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSSagemakerModelPackageGroupPolicyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSSagemakerModelPackageGroupPolicyBasicConfig(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSagemakerModelPackageGroupPolicyExists(resourceName, &mpg),
resource.TestCheckResourceAttr(resourceName, "model_package_group_name", rName),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func TestAccAWSSagemakerModelPackageGroupPolicy_disappears(t *testing.T) {
var mpg sagemaker.GetModelPackageGroupPolicyOutput
rName := acctest.RandomWithPrefix("tf-acc-test")
resourceName := "aws_sagemaker_model_package_group_policy.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, sagemaker.EndpointsID),
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSSagemakerModelPackageGroupPolicyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSSagemakerModelPackageGroupPolicyBasicConfig(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSagemakerModelPackageGroupPolicyExists(resourceName, &mpg),
testAccCheckResourceDisappears(testAccProvider, resourceAwsSagemakerModelPackageGroupPolicy(), resourceName),
testAccCheckResourceDisappears(testAccProvider, resourceAwsSagemakerModelPackageGroupPolicy(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func TestAccAWSSagemakerModelPackageGroupPolicy_disappears_modelPackageGroup(t *testing.T) {
var mpg sagemaker.GetModelPackageGroupPolicyOutput
rName := acctest.RandomWithPrefix("tf-acc-test")
resourceName := "aws_sagemaker_model_package_group_policy.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ErrorCheck: testAccErrorCheck(t, sagemaker.EndpointsID),
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSSagemakerModelPackageGroupPolicyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSSagemakerModelPackageGroupPolicyBasicConfig(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSSagemakerModelPackageGroupPolicyExists(resourceName, &mpg),
testAccCheckResourceDisappears(testAccProvider, resourceAwsSagemakerModelPackageGroup(), "aws_sagemaker_model_package_group.test"),
testAccCheckResourceDisappears(testAccProvider, resourceAwsSagemakerModelPackageGroupPolicy(), resourceName),
),
ExpectNonEmptyPlan: true,
},
},
})
}

func testAccCheckAWSSagemakerModelPackageGroupPolicyDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).sagemakerconn

for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_sagemaker_model_package_group_policy" {
continue
}

_, err := finder.ModelPackageGroupPolicyByName(conn, rs.Primary.ID)
if tfresource.NotFound(err) {
continue
}

if err != nil {
return fmt.Errorf("error reading Sagemaker Model Package Group Policy (%s): %w", rs.Primary.ID, err)
}
}

return nil
}

func testAccCheckAWSSagemakerModelPackageGroupPolicyExists(n string, mpg *sagemaker.GetModelPackageGroupPolicyOutput) 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 sagmaker Model Package Group ID is set")
}

conn := testAccProvider.Meta().(*AWSClient).sagemakerconn
resp, err := finder.ModelPackageGroupPolicyByName(conn, rs.Primary.ID)
if err != nil {
return err
}

*mpg = *resp

return nil
}
}

func testAccAWSSagemakerModelPackageGroupPolicyBasicConfig(rName string) string {
return fmt.Sprintf(`
data "aws_caller_identity" "current" {}

data "aws_iam_policy_document" "test" {
statement {
sid = "AddPermModelPackageGroup"
actions = ["sagemaker:DescribeModelPackage", "sagemaker:ListModelPackages"]
resources = [aws_sagemaker_model_package_group.test.arn]
principals {
identifiers = [data.aws_caller_identity.current.account_id]
type = "AWS"
}
}
}

resource "aws_sagemaker_model_package_group" "test" {
model_package_group_name = %[1]q
}

resource "aws_sagemaker_model_package_group_policy" "test" {
model_package_group_name = aws_sagemaker_model_package_group.test.model_package_group_name
resource_policy = jsonencode(jsondecode(data.aws_iam_policy_document.test.json))
}
`, rName)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
---
subcategory: "Sagemaker"
layout: "aws"
page_title: "AWS: aws_sagemaker_model_package_group_policy"
description: |-
Provides a Sagemaker Model Package Group Policy resource.
---

# Resource: aws_sagemaker_model_package_group_policy

Provides a Sagemaker Model Package Group Policy resource.

## Example Usage

### Basic usage

```terraform
data "aws_caller_identity" "current" {}

data "aws_iam_policy_document" "example" {
statement {
sid = "AddPermModelPackageGroup"
actions = ["sagemaker:DescribeModelPackage", "sagemaker:ListModelPackages"]
resources = [aws_sagemaker_model_package_group.example.arn]
principals {
identifiers = [data.aws_caller_identity.current.account_id]
type = "AWS"
}
}
}

resource "aws_sagemaker_model_package_group" "example" {
model_package_group_name = "example"
}

resource "aws_sagemaker_model_package_group_policy" "example" {
model_package_group_name = aws_sagemaker_model_package_group.example.model_package_group_name
resource_policy = jsonencode(jsondecode(data.aws_iam_policy_document.example.json))
}
```

## Argument Reference

The following arguments are supported:

* `model_package_group_name` - (Required) The name of the model package group.


## Attributes Reference

In addition to all arguments above, the following attributes are exported:

* `id` - The name of the Model Package Package Group.

## Import

Sagemaker Code Model Package Groups can be imported using the `name`, e.g.

```
$ terraform import aws_sagemaker_model_package_group_policy.example example
```