diff --git a/.changelog/14193.txt b/.changelog/14193.txt new file mode 100644 index 00000000000..9d588853c0d --- /dev/null +++ b/.changelog/14193.txt @@ -0,0 +1,3 @@ +```release-note:enhancement +resource/aws_ecr_repository_policy: Add plan time validation for `policy` +``` diff --git a/aws/resource_aws_ecr_repository_policy.go b/aws/resource_aws_ecr_repository_policy.go index ba710623901..53d0c2e9859 100644 --- a/aws/resource_aws_ecr_repository_policy.go +++ b/aws/resource_aws_ecr_repository_policy.go @@ -6,17 +6,17 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ecr" "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 resourceAwsEcrRepositoryPolicy() *schema.Resource { return &schema.Resource{ - Create: resourceAwsEcrRepositoryPolicyCreate, + Create: resourceAwsEcrRepositoryPolicyPut, Read: resourceAwsEcrRepositoryPolicyRead, - Update: resourceAwsEcrRepositoryPolicyUpdate, + Update: resourceAwsEcrRepositoryPolicyPut, Delete: resourceAwsEcrRepositoryPolicyDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, @@ -31,6 +31,7 @@ func resourceAwsEcrRepositoryPolicy() *schema.Resource { "policy": { Type: schema.TypeString, Required: true, + ValidateFunc: validation.StringIsJSON, DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs, }, "registry_id": { @@ -41,7 +42,7 @@ func resourceAwsEcrRepositoryPolicy() *schema.Resource { } } -func resourceAwsEcrRepositoryPolicyCreate(d *schema.ResourceData, meta interface{}) error { +func resourceAwsEcrRepositoryPolicyPut(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ecrconn input := ecr.SetRepositoryPolicyInput{ @@ -49,7 +50,7 @@ func resourceAwsEcrRepositoryPolicyCreate(d *schema.ResourceData, meta interface PolicyText: aws.String(d.Get("policy").(string)), } - log.Printf("[DEBUG] Creating ECR resository policy: %s", input) + log.Printf("[DEBUG] Creating ECR repository policy: %#v", input) // Retry due to IAM eventual consistency var err error @@ -57,7 +58,7 @@ func resourceAwsEcrRepositoryPolicyCreate(d *schema.ResourceData, meta interface err = resource.Retry(2*time.Minute, func() *resource.RetryError { out, err = conn.SetRepositoryPolicy(&input) - if isAWSErr(err, "InvalidParameterException", "Invalid repository policy provided") { + if isAWSErr(err, ecr.ErrCodeInvalidParameterException, "Invalid repository policy provided") { return resource.RetryableError(err) } if err != nil { @@ -69,15 +70,12 @@ func resourceAwsEcrRepositoryPolicyCreate(d *schema.ResourceData, meta interface out, err = conn.SetRepositoryPolicy(&input) } if err != nil { - return fmt.Errorf("Error creating ECR Repository Policy: %s", err) + return fmt.Errorf("error creating ECR Repository Policy: %w", err) } - repositoryPolicy := *out + log.Printf("[DEBUG] ECR repository policy created: %s", aws.StringValue(out.RepositoryName)) - log.Printf("[DEBUG] ECR repository policy created: %s", *repositoryPolicy.RepositoryName) - - d.SetId(aws.StringValue(repositoryPolicy.RepositoryName)) - d.Set("registry_id", repositoryPolicy.RegistryId) + d.SetId(aws.StringValue(out.RepositoryName)) return resourceAwsEcrRepositoryPolicyRead(d, meta) } @@ -90,70 +88,20 @@ func resourceAwsEcrRepositoryPolicyRead(d *schema.ResourceData, meta interface{} RepositoryName: aws.String(d.Id()), }) if err != nil { - if ecrerr, ok := err.(awserr.Error); ok { - switch ecrerr.Code() { - case "RepositoryNotFoundException", "RepositoryPolicyNotFoundException": - d.SetId("") - return nil - default: - return err - } + if isAWSErr(err, ecr.ErrCodeRepositoryNotFoundException, "") || + isAWSErr(err, ecr.ErrCodeRepositoryPolicyNotFoundException, "") { + log.Printf("[WARN] ECR Repository Policy %s not found, removing", d.Id()) + d.SetId("") + return nil } return err } - log.Printf("[DEBUG] Received repository policy %s", out) - - repositoryPolicy := out - - d.SetId(aws.StringValue(repositoryPolicy.RepositoryName)) - d.Set("repository", repositoryPolicy.RepositoryName) - d.Set("registry_id", repositoryPolicy.RegistryId) - d.Set("policy", repositoryPolicy.PolicyText) - - return nil -} - -func resourceAwsEcrRepositoryPolicyUpdate(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*AWSClient).ecrconn - - if !d.HasChange("policy") { - return nil - } - - input := ecr.SetRepositoryPolicyInput{ - RepositoryName: aws.String(d.Get("repository").(string)), - RegistryId: aws.String(d.Get("registry_id").(string)), - PolicyText: aws.String(d.Get("policy").(string)), - } - - log.Printf("[DEBUG] Updating ECR resository policy: %s", input) - - // Retry due to IAM eventual consistency - var err error - var out *ecr.SetRepositoryPolicyOutput - err = resource.Retry(2*time.Minute, func() *resource.RetryError { - out, err = conn.SetRepositoryPolicy(&input) - - if isAWSErr(err, "InvalidParameterException", "Invalid repository policy provided") { - return resource.RetryableError(err) - } - if err != nil { - return resource.NonRetryableError(err) - } - return nil - }) - if isResourceTimeoutError(err) { - out, err = conn.SetRepositoryPolicy(&input) - } - if err != nil { - return fmt.Errorf("Error updating ECR Repository Policy: %s", err) - } - - repositoryPolicy := *out + log.Printf("[DEBUG] Received repository policy %#v", out) - d.SetId(aws.StringValue(repositoryPolicy.RepositoryName)) - d.Set("registry_id", repositoryPolicy.RegistryId) + d.Set("repository", out.RepositoryName) + d.Set("registry_id", out.RegistryId) + d.Set("policy", out.PolicyText) return nil } @@ -166,13 +114,9 @@ func resourceAwsEcrRepositoryPolicyDelete(d *schema.ResourceData, meta interface RegistryId: aws.String(d.Get("registry_id").(string)), }) if err != nil { - if ecrerr, ok := err.(awserr.Error); ok { - switch ecrerr.Code() { - case "RepositoryNotFoundException", "RepositoryPolicyNotFoundException": - return nil - default: - return err - } + if isAWSErr(err, ecr.ErrCodeRepositoryNotFoundException, "") || + isAWSErr(err, ecr.ErrCodeRepositoryPolicyNotFoundException, "") { + return nil } return err } diff --git a/aws/resource_aws_ecr_repository_policy_test.go b/aws/resource_aws_ecr_repository_policy_test.go index d2ee93e38d8..7027c5a693b 100644 --- a/aws/resource_aws_ecr_repository_policy_test.go +++ b/aws/resource_aws_ecr_repository_policy_test.go @@ -2,10 +2,10 @@ package aws import ( "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ecr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -13,8 +13,8 @@ import ( ) func TestAccAWSEcrRepositoryPolicy_basic(t *testing.T) { - randString := acctest.RandString(10) - resourceName := "aws_ecr_repository_policy.default" + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ecr_repository_policy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -23,9 +23,12 @@ func TestAccAWSEcrRepositoryPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckAWSEcrRepositoryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcrRepositoryPolicy(randString), + Config: testAccAWSEcrRepositoryPolicyConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcrRepositoryPolicyExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "repository", "aws_ecr_repository.test", "name"), + resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(rName)), + testAccCheckResourceAttrAccountID(resourceName, "registry_id"), ), }, { @@ -33,13 +36,23 @@ func TestAccAWSEcrRepositoryPolicy_basic(t *testing.T) { ImportState: true, ImportStateVerify: true, }, + { + Config: testAccAWSEcrRepositoryPolicyConfigUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcrRepositoryPolicyExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "repository", "aws_ecr_repository.test", "name"), + resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(rName)), + resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile("ecr:DescribeImages")), + testAccCheckResourceAttrAccountID(resourceName, "registry_id"), + ), + }, }, }) } func TestAccAWSEcrRepositoryPolicy_iam(t *testing.T) { - randString := acctest.RandString(10) - resourceName := "aws_ecr_repository_policy.default" + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ecr_repository_policy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -48,9 +61,11 @@ func TestAccAWSEcrRepositoryPolicy_iam(t *testing.T) { CheckDestroy: testAccCheckAWSEcrRepositoryPolicyDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEcrRepositoryPolicyWithIAMRole(randString), + Config: testAccAWSEcrRepositoryPolicyWithIAMRoleConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcrRepositoryPolicyExists(resourceName), + resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile(rName)), + resource.TestMatchResourceAttr(resourceName, "policy", regexp.MustCompile("iam")), ), }, { @@ -62,6 +77,48 @@ func TestAccAWSEcrRepositoryPolicy_iam(t *testing.T) { }) } +func TestAccAWSEcrRepositoryPolicy_disappears(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ecr_repository_policy.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcrRepositoryPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEcrRepositoryPolicyConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcrRepositoryPolicyExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEcrRepositoryPolicy(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAWSEcrRepositoryPolicy_disappears_repository(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ecr_repository_policy.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcrRepositoryPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEcrRepositoryPolicyConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcrRepositoryPolicyExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEcrRepository(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSEcrRepositoryPolicyDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ecrconn @@ -72,10 +129,11 @@ func testAccCheckAWSEcrRepositoryPolicyDestroy(s *terraform.State) error { _, err := conn.GetRepositoryPolicy(&ecr.GetRepositoryPolicyInput{ RegistryId: aws.String(rs.Primary.Attributes["registry_id"]), - RepositoryName: aws.String(rs.Primary.Attributes["repository"]), + RepositoryName: aws.String(rs.Primary.ID), }) if err != nil { - if ecrerr, ok := err.(awserr.Error); ok && ecrerr.Code() == "RepositoryNotFoundException" { + if isAWSErr(err, ecr.ErrCodeRepositoryNotFoundException, "") || + isAWSErr(err, ecr.ErrCodeRepositoryPolicyNotFoundException, "") { return nil } return err @@ -96,21 +154,21 @@ func testAccCheckAWSEcrRepositoryPolicyExists(name string) resource.TestCheckFun } } -func testAccAWSEcrRepositoryPolicy(randString string) string { +func testAccAWSEcrRepositoryPolicyConfig(rName string) string { return fmt.Sprintf(` -resource "aws_ecr_repository" "foo" { - name = "tf-acc-test-ecr-%s" +resource "aws_ecr_repository" "test" { + name = %[1]q } -resource "aws_ecr_repository_policy" "default" { - repository = aws_ecr_repository.foo.name +resource "aws_ecr_repository_policy" "test" { + repository = aws_ecr_repository.test.name policy = <