From 3e6c082ecd135e7b5c26fe7a2823281b9c3ade17 Mon Sep 17 00:00:00 2001 From: Brian Flad Date: Sun, 11 Nov 2018 15:47:58 -0500 Subject: [PATCH] New Resource: aws_glacier_vault_lock ``` --- PASS: TestAccAWSGlacierVaultLock_basic (18.63s) --- PASS: TestAccAWSGlacierVaultLock_CompleteLock (19.02s) ``` --- aws/provider.go | 1 + aws/resource_aws_glacier_vault_lock.go | 188 ++++++++++++++++++ aws/resource_aws_glacier_vault_lock_test.go | 173 ++++++++++++++++ website/aws.erb | 5 +- website/docs/r/glacier_vault.html.markdown | 2 +- .../docs/r/glacier_vault_lock.html.markdown | 78 ++++++++ 6 files changed, 445 insertions(+), 2 deletions(-) create mode 100644 aws/resource_aws_glacier_vault_lock.go create mode 100644 aws/resource_aws_glacier_vault_lock_test.go create mode 100644 website/docs/r/glacier_vault_lock.html.markdown diff --git a/aws/provider.go b/aws/provider.go index d92664e937cf..5745b1f20f29 100644 --- a/aws/provider.go +++ b/aws/provider.go @@ -444,6 +444,7 @@ func Provider() terraform.ResourceProvider { "aws_gamelift_build": resourceAwsGameliftBuild(), "aws_gamelift_fleet": resourceAwsGameliftFleet(), "aws_glacier_vault": resourceAwsGlacierVault(), + "aws_glacier_vault_lock": resourceAwsGlacierVaultLock(), "aws_glue_catalog_database": resourceAwsGlueCatalogDatabase(), "aws_glue_catalog_table": resourceAwsGlueCatalogTable(), "aws_glue_classifier": resourceAwsGlueClassifier(), diff --git a/aws/resource_aws_glacier_vault_lock.go b/aws/resource_aws_glacier_vault_lock.go new file mode 100644 index 000000000000..c181510cbbb6 --- /dev/null +++ b/aws/resource_aws_glacier_vault_lock.go @@ -0,0 +1,188 @@ +package aws + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/glacier" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" +) + +func resourceAwsGlacierVaultLock() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsGlacierVaultLockCreate, + Read: resourceAwsGlacierVaultLockRead, + // Allow ignore_deletion_error update + Update: schema.Noop, + Delete: resourceAwsGlacierVaultLockDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "complete_lock": { + Type: schema.TypeBool, + Required: true, + ForceNew: true, + }, + "ignore_deletion_error": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "policy": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs, + ValidateFunc: validateIAMPolicyJson, + }, + "vault_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.NoZeroValues, + }, + }, + } +} + +func resourceAwsGlacierVaultLockCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).glacierconn + vaultName := d.Get("vault_name").(string) + + input := &glacier.InitiateVaultLockInput{ + AccountId: aws.String("-"), + Policy: &glacier.VaultLockPolicy{ + Policy: aws.String(d.Get("policy").(string)), + }, + VaultName: aws.String(vaultName), + } + + log.Printf("[DEBUG] Initiating Glacier Vault Lock: %s", input) + output, err := conn.InitiateVaultLock(input) + if err != nil { + return fmt.Errorf("error initiating Glacier Vault Lock: %s", err) + } + + d.SetId(vaultName) + + if !d.Get("complete_lock").(bool) { + return resourceAwsGlacierVaultLockRead(d, meta) + } + + completeLockInput := &glacier.CompleteVaultLockInput{ + LockId: output.LockId, + VaultName: aws.String(vaultName), + } + + log.Printf("[DEBUG] Completing Glacier Vault (%s) Lock: %s", vaultName, completeLockInput) + if _, err := conn.CompleteVaultLock(completeLockInput); err != nil { + return fmt.Errorf("error completing Glacier Vault (%s) Lock: %s", vaultName, err) + } + + if err := waitForGlacierVaultLockCompletion(conn, vaultName); err != nil { + return fmt.Errorf("error waiting for Glacier Vault Lock (%s) completion: %s", d.Id(), err) + } + + return resourceAwsGlacierVaultLockRead(d, meta) +} + +func resourceAwsGlacierVaultLockRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).glacierconn + + input := &glacier.GetVaultLockInput{ + AccountId: aws.String("-"), + VaultName: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Reading Glacier Vault Lock (%s): %s", d.Id(), input) + output, err := conn.GetVaultLock(input) + + if isAWSErr(err, glacier.ErrCodeResourceNotFoundException, "") { + log.Printf("[WARN] Glacier Vault Lock (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading Glacier Vault Lock (%s): %s", d.Id(), err) + } + + if output == nil { + log.Printf("[WARN] Glacier Vault Lock (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + d.Set("complete_lock", aws.StringValue(output.State) == "Locked") + d.Set("policy", output.Policy) + d.Set("vault_name", d.Id()) + + return nil +} + +func resourceAwsGlacierVaultLockDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).glacierconn + + input := &glacier.AbortVaultLockInput{ + VaultName: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Aborting Glacier Vault Lock (%s): %s", d.Id(), input) + _, err := conn.AbortVaultLock(input) + + if isAWSErr(err, glacier.ErrCodeResourceNotFoundException, "") { + return nil + } + + if err != nil && !d.Get("ignore_deletion_error").(bool) { + return fmt.Errorf("error aborting Glacier Vault Lock (%s): %s", d.Id(), err) + } + + return nil +} + +func glacierVaultLockRefreshFunc(conn *glacier.Glacier, vaultName string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + input := &glacier.GetVaultLockInput{ + AccountId: aws.String("-"), + VaultName: aws.String(vaultName), + } + + log.Printf("[DEBUG] Reading Glacier Vault Lock (%s): %s", vaultName, input) + output, err := conn.GetVaultLock(input) + + if isAWSErr(err, glacier.ErrCodeResourceNotFoundException, "") { + return nil, "", nil + } + + if err != nil { + return nil, "", fmt.Errorf("error reading Glacier Vault Lock (%s): %s", vaultName, err) + } + + if output == nil { + return nil, "", nil + } + + return output, aws.StringValue(output.State), nil + } +} + +func waitForGlacierVaultLockCompletion(conn *glacier.Glacier, vaultName string) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{"InProgress"}, + Target: []string{"Locked"}, + Refresh: glacierVaultLockRefreshFunc(conn, vaultName), + Timeout: 5 * time.Minute, + } + + log.Printf("[DEBUG] Waiting for Glacier Vault Lock (%s) completion", vaultName) + _, err := stateConf.WaitForState() + + return err +} diff --git a/aws/resource_aws_glacier_vault_lock_test.go b/aws/resource_aws_glacier_vault_lock_test.go new file mode 100644 index 000000000000..e0d6c04a5827 --- /dev/null +++ b/aws/resource_aws_glacier_vault_lock_test.go @@ -0,0 +1,173 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/glacier" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSGlacierVaultLock_basic(t *testing.T) { + var vaultLock1 glacier.GetVaultLockOutput + rName := acctest.RandomWithPrefix("tf-acc-test") + glacierVaultResourceName := "aws_glacier_vault.test" + resourceName := "aws_glacier_vault_lock.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckGlacierVaultLockDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlacierVaultLockConfigCompleteLock(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckGlacierVaultLockExists(resourceName, &vaultLock1), + resource.TestCheckResourceAttr(resourceName, "complete_lock", "false"), + resource.TestCheckResourceAttr(resourceName, "ignore_deletion_error", "false"), + resource.TestCheckResourceAttrSet(resourceName, "policy"), + resource.TestCheckResourceAttrPair(resourceName, "vault_name", glacierVaultResourceName, "name"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"ignore_deletion_error"}, + }, + }, + }) +} + +func TestAccAWSGlacierVaultLock_CompleteLock(t *testing.T) { + var vaultLock1 glacier.GetVaultLockOutput + rName := acctest.RandomWithPrefix("tf-acc-test") + glacierVaultResourceName := "aws_glacier_vault.test" + resourceName := "aws_glacier_vault_lock.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckGlacierVaultLockDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGlacierVaultLockConfigCompleteLock(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckGlacierVaultLockExists(resourceName, &vaultLock1), + resource.TestCheckResourceAttr(resourceName, "complete_lock", "true"), + resource.TestCheckResourceAttr(resourceName, "ignore_deletion_error", "true"), + resource.TestCheckResourceAttrSet(resourceName, "policy"), + resource.TestCheckResourceAttrPair(resourceName, "vault_name", glacierVaultResourceName, "name"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"ignore_deletion_error"}, + }, + }, + }) +} + +func testAccCheckGlacierVaultLockExists(resourceName string, getVaultLockOutput *glacier.GetVaultLockOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).glacierconn + + input := &glacier.GetVaultLockInput{ + VaultName: aws.String(rs.Primary.ID), + } + output, err := conn.GetVaultLock(input) + + if err != nil { + return fmt.Errorf("error reading Glacier Vault Lock (%s): %s", rs.Primary.ID, err) + } + + if output == nil { + return fmt.Errorf("error reading Glacier Vault Lock (%s): empty response", rs.Primary.ID) + } + + *getVaultLockOutput = *output + + return nil + } +} + +func testAccCheckGlacierVaultLockDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).glacierconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_glacier_vault_lock" { + continue + } + + input := &glacier.GetVaultLockInput{ + VaultName: aws.String(rs.Primary.ID), + } + output, err := conn.GetVaultLock(input) + + if isAWSErr(err, glacier.ErrCodeResourceNotFoundException, "") { + continue + } + + if err != nil { + return fmt.Errorf("error reading Glacier Vault Lock (%s): %s", rs.Primary.ID, err) + } + + if output != nil { + return fmt.Errorf("Glacier Vault Lock (%s) still exists", rs.Primary.ID) + } + } + + return nil +} + +func testAccGlacierVaultLockConfigCompleteLock(rName string, completeLock bool) string { + return fmt.Sprintf(` +resource "aws_glacier_vault" "test" { + name = %q +} + +data "aws_caller_identity" "current" {} +data "aws_partition" "current" {} + +data "aws_iam_policy_document" "test" { + statement { + # Allow for testing purposes + actions = ["glacier:DeleteArchive"] + effect = "Allow" + resources = ["${aws_glacier_vault.test.arn}"] + + condition { + test = "NumericLessThanEquals" + variable = "glacier:ArchiveAgeinDays" + values = ["0"] + } + + principals { + identifiers = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:root"] + type = "AWS" + } + } +} + +resource "aws_glacier_vault_lock" "test" { + complete_lock = %t + ignore_deletion_error = %t + policy = "${data.aws_iam_policy_document.test.json}" + vault_name = "${aws_glacier_vault.test.name}" +} +`, rName, completeLock, completeLock) +} diff --git a/website/aws.erb b/website/aws.erb index bcfa17988bf3..e6826e9f71c2 100644 --- a/website/aws.erb +++ b/website/aws.erb @@ -1298,9 +1298,12 @@ > Glacier Resources diff --git a/website/docs/r/glacier_vault.html.markdown b/website/docs/r/glacier_vault.html.markdown index 59439ae4fa46..1f1c5a76e0f9 100644 --- a/website/docs/r/glacier_vault.html.markdown +++ b/website/docs/r/glacier_vault.html.markdown @@ -1,7 +1,7 @@ --- layout: "aws" page_title: "AWS: aws_glacier_vault" -sidebar_current: "docs-aws-resource-glacier-vault" +sidebar_current: "docs-aws-resource-glacier-vault-x" description: |- Provides a Glacier Vault. --- diff --git a/website/docs/r/glacier_vault_lock.html.markdown b/website/docs/r/glacier_vault_lock.html.markdown new file mode 100644 index 000000000000..d7b81d4155dc --- /dev/null +++ b/website/docs/r/glacier_vault_lock.html.markdown @@ -0,0 +1,78 @@ +--- +layout: "aws" +page_title: "AWS: aws_glacier_vault_lock" +sidebar_current: "docs-aws-resource-glacier-vault-lock" +description: |- + Manages a Glacier Vault Lock. +--- + +# aws_glacier_vault_lock + +Manages a Glacier Vault Lock. You can refer to the [Glacier Developer Guide](https://docs.aws.amazon.com/amazonglacier/latest/dev/vault-lock.html) for a full explanation of the Glacier Vault Lock functionality. + +~> **NOTE:** This resource allows you to test Glacier Vault Lock policies by setting the `complete_lock` argument to `false`. When testing policies in this manner, the Glacier Vault Lock automatically expires after 24 hours and Terraform will show this resource as needing recreation after that time. To permanently apply the policy, set the `complete_lock` argument to `true`. When changing `complete_lock` to `true`, it is expected the resource will show as recreating. + +!> **WARNING:** Once a Glacier Vault Lock is completed, it is immutable. The deletion of the Glacier Vault Lock is not be possible and attempting to remove it from Terraform will return an error. Set the `ignore_deletion_error` argument to `true` and apply this configuration before attempting to delete this resource via Terraform or use `terraform state rm` to remove this resource from Terraform management. + +## Example Usage + +### Testing Glacier Vault Lock Policy + +```hcl +resource "aws_glacier_vault" "example" { + name = "example" +} + +data "aws_iam_policy_document" "example" { + statement { + actions = ["glacier:DeleteArchive"] + effect = "Deny" + resources = ["${aws_glacier_vault.example.arn}"] + + condition { + test = "NumericLessThanEquals" + variable = "glacier:ArchiveAgeinDays" + values = ["365"] + } + } +} + +resource "aws_glacier_vault_lock" "example" { + complete_lock = false + policy = "${data.aws_iam_policy_document.example.json}" + vault_name = "${aws_glacier_vault.example.name}" +} +``` + +### Permanently Applying Glacier Vault Lock Policy + +```hcl +resource "aws_glacier_vault_lock" "example" { + complete_lock = true + policy = "${data.aws_iam_policy_document.example.json}" + vault_name = "${aws_glacier_vault.example.name}" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `complete_lock` - (Required) Boolean whether to permanently apply this Glacier Lock Policy. Once completed, this cannot be undone. If set to `false`, the Glacier Lock Policy remains in a testing mode for 24 hours. After that time, the Glacier Lock Policy is automatically removed by Glacier and the Terraform resource will show as needing recreation. Changing this from `false` to `true` will show as resource recreation, which is expected. Changing this from `true` to `false` is not possible unless the Glacier Vault is recreated at the same time. +* `policy` - (Required) JSON string containing the IAM policy to apply as the Glacier Vault Lock policy. +* `vault_name` - (Required) The name of the Glacier Vault. +* `ignore_deletion_error` - (Optional) Allow Terraform to ignore the error returned when attempting to delete the Glacier Lock Policy. This can be used to delete or recreate the Glacier Vault via Terraform, for example, if the Glacier Vault Lock policy permits that action. This should only be used in conjunction with `complete_lock` being set to `true`. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - Glacier Vault name. + +## Import + +Glacier Vault Locks can be imported using the Glacier Vault name, e.g. + +``` +$ terraform import aws_glacier_vault_lock.example example-vault +```