Skip to content

Init Storage IAM policy #493

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

Closed
wants to merge 14 commits into from
Closed
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
2 changes: 2 additions & 0 deletions google/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ func Provider() terraform.ResourceProvider {
"google_service_account_key": resourceGoogleServiceAccountKey(),
"google_storage_bucket": resourceStorageBucket(),
"google_storage_bucket_acl": resourceStorageBucketAcl(),
"google_storage_bucket_iam_policy": resourceStorageBucketIAMPolicy(),
"google_storage_object_iam_policy": resourceStorageObjectIAMPolicy(),
"google_storage_bucket_object": resourceStorageBucketObject(),
"google_storage_object_acl": resourceStorageObjectAcl(),
},
Expand Down
134 changes: 134 additions & 0 deletions google/resource_storage_bucket_iam_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package google

import (
"encoding/json"
"fmt"
"log"

"github.com/hashicorp/terraform/helper/schema"

storagev1 "google.golang.org/api/storage/v1"
)

func resourceStorageBucketIAMPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceStorageBucketIAMPolicyCreate,
Read: resourceStorageBucketIAMPolicyRead,
Update: resourceStorageBucketIAMPolicyUpdate,
Delete: resourceStorageBucketIAMPolicyDelete,

Schema: map[string]*schema.Schema{
"bucket": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"policy_data": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: jsonPolicyDiffSuppress,
ValidateFunc: validateV2IamPolicy,
},
"etag": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func setBucketIamPolicy(d *schema.ResourceData, config *Config) error {
bucket := d.Get("bucket").(string)
policy, err := unmarshalStorageIamPolicy(d.Get("policy_data").(string))
if err != nil {
return fmt.Errorf("'policy_data' is not valid for %s: %s", bucket, err)
}

log.Printf("[DEBUG] Setting IAM policy for bucket %q", bucket)
_, err = config.clientStorage.Buckets.SetIamPolicy(bucket, policy).Do()
log.Printf("[DEBUG] Set IAM policy for bucket %q", bucket)
return err
}

func resourceStorageBucketIAMPolicyCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

if err := setBucketIamPolicy(d, config); err != nil {
return err
}

d.SetId(d.Get("bucket").(string))

return resourceStorageBucketIAMPolicyRead(d, meta)
}

func resourceStorageBucketIAMPolicyRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
bucket := d.Get("bucket").(string)

log.Printf("[DEBUG] Reading IAM policy for bucket %q", bucket)
policy, err := config.clientStorage.Buckets.GetIamPolicy(bucket).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Iam policy for %s", bucket))
}
log.Printf("[DEBUG] Read IAM policy for bucket %q: %v", bucket, policy)

d.Set("etag", policy.Etag)
policyData, err := marshalStorageIamPolicy(policy)
if err != nil {
return fmt.Errorf("Error marshal storage IAM policy: %v", err)
}
d.Set("policy_data", policyData)

return nil
}

func resourceStorageBucketIAMPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

if d.HasChange("policy_data") {
if err := setBucketIamPolicy(d, config); err != nil {
return err
}
}
return resourceStorageBucketIAMPolicyRead(d, meta)
}

func resourceStorageBucketIAMPolicyDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
bucket := d.Get("bucket").(string)

_, err := config.clientStorage.Buckets.SetIamPolicy(bucket, &storagev1.Policy{}).Do()

if err != nil {
return err
}

return nil
}

func marshalStorageIamPolicy(policy *storagev1.Policy) (string, error) {
pdBytes, err := json.Marshal(&storagev1.Policy{
Bindings: policy.Bindings,
})
if err != nil {
return "", err
}
return string(pdBytes), nil
}

func unmarshalStorageIamPolicy(policyData string) (*storagev1.Policy, error) {
policy := &storagev1.Policy{}
if err := json.Unmarshal([]byte(policyData), policy); err != nil {
return nil, fmt.Errorf("Could not unmarshal policy data %s:\n%s", policyData, err)
}
return policy, nil
}

func validateStorageIamPolicy(i interface{}, k string) (s []string, es []error) {
_, err := unmarshalV2IamPolicy(i.(string))
if err != nil {
es = append(es, err)
}
return
}
193 changes: 193 additions & 0 deletions google/resource_storage_bucket_iam_policy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package google

import (
"bytes"
"fmt"
"reflect"
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
storagev1 "google.golang.org/api/storage/v1"
)

func testBucketIamName() string {
return acctest.RandomWithPrefix("tf-test-iam-bucket")
}

func TestAccGoogleStorageBucketIAMPolicy_basic(t *testing.T) {
bucketName := testBucketIamName()
skipIfEnvNotSet(t, "GOOGLE_PROJECT_NUMBER")

policy := &storagev1.Policy{
Bindings: []*storagev1.PolicyBindings{
{
Role: "roles/viewer",
Members: []string{
"user:[email protected]",
},
},
},
}

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccGoogleStorageBucketIAMPolicyDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testGoogleStorageBucketsIAMPolicyBasic(bucketName, policy),
Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleStorageBucketIAMPolicy(bucketName, policy),
),
},
},
})
}

func TestAccGoogleStorageBucketIAMPolicy_upgrade(t *testing.T) {
bucketName := testBucketIamName()
skipIfEnvNotSet(t, "GOOGLE_PROJECT_NUMBER")

policy1 := &storagev1.Policy{
Bindings: []*storagev1.PolicyBindings{
{
Role: "roles/viewer",
Members: []string{
"user:[email protected]",
},
},
},
}
policy2 := &storagev1.Policy{
Bindings: []*storagev1.PolicyBindings{
{
Role: "roles/editor",
Members: []string{
"user:[email protected]",
},
},
{
Role: "roles/viewer",
Members: []string{
"user:[email protected]",
},
},
},
}

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccGoogleStorageBucketIAMPolicyDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testGoogleStorageBucketsIAMPolicyBasic(bucketName, policy1),
Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleStorageBucketIAMPolicy(bucketName, policy1),
),
},

resource.TestStep{
Config: testGoogleStorageBucketsIAMPolicyBasic(bucketName, policy2),
Check: resource.ComposeTestCheckFunc(
testAccCheckGoogleStorageBucketIAMPolicy(bucketName, policy2),
),
},
},
})
}

func testAccCheckGoogleStorageBucketIAMPolicy(bucket string, policy *storagev1.Policy) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[bucket]
if !ok {
return fmt.Errorf("Not found: %s", bucket)
}

if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}

config := testAccProvider.Meta().(*Config)

p, err := config.clientStorage.Buckets.GetIamPolicy(rs.Primary.ID).Do()

if err != nil {
return fmt.Errorf("Error retrieving contents of IAMPolicy for bucket %s: %s", bucket, err)
}

if !reflect.DeepEqual(p.Bindings, policy.Bindings) {
return fmt.Errorf("Incorrect iam policy bindings. Expected '%s', got '%s'", policy.Bindings, p.Bindings)
}

if _, ok = rs.Primary.Attributes["etag"]; !ok {
return fmt.Errorf("Etag should be set.")
}

if rs.Primary.Attributes["etag"] != p.Etag {
return fmt.Errorf("Incorrect etag value. Expected '%s', got '%s'", p.Etag, rs.Primary.Attributes["etag"])
}

return nil
}
}

func testAccGoogleStorageBucketIAMPolicyDestroy(s *terraform.State) error {
config := testAccProvider.Meta().(*Config)

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

bucket := rs.Primary.Attributes["bucket"]

policy, err := config.clientStorage.Buckets.GetIamPolicy(bucket).Do()

if err != nil && len(policy.Bindings) > 0 {
return fmt.Errorf("Bucket %s policy hasn't been deleted", bucket)
}
}

return nil
}

func testGoogleStorageBucketsIAMPolicyBasic(bucketName string, policy *storagev1.Policy) string {
var bindingBuffer bytes.Buffer

// Generate binding for google_iam_policy based on policy.Bindings
// Example:
// data "google_iam_policy" "admin" {
// binding {
// role = "roles/editor"
// members = [
// "user:[email protected]",
// ]
// }
//}

for _, binding := range policy.Bindings {
bindingBuffer.WriteString("binding {\n")
bindingBuffer.WriteString(fmt.Sprintf("role = \"%s\"\n", binding.Role))
bindingBuffer.WriteString(fmt.Sprintf("members = [\n"))
for _, member := range binding.Members {
bindingBuffer.WriteString(fmt.Sprintf("\"%s\",\n", member))
}
bindingBuffer.WriteString("]}\n")
Copy link
Contributor

Choose a reason for hiding this comment

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

This part of the code scares me, to be honest.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't understand Why?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this is the same than resource_google_folder_iam_policy_test.go;

I have added Comment on source code

Copy link
Contributor

Choose a reason for hiding this comment

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

Apologies, missed this response. It largely scares me because we're dynamically building the config string in a buffer, which is more complicated than tests usually require. I think this may be more generalized than is strictly necessary, but it's really not worth holding a merge over.

}
return fmt.Sprintf(`
resource "google_storage_bucket" "bucket" {
display_name = "%s"
}
data "google_iam_policy" "test" {
%s
}
resource "google_storage_bucket_iam_policy" "test" {
bucket = "${google_storage_bucket.bucket.name}"
policy_data = "${data.google_iam_policy.test.policy_data}"
}
`, bucketName, bindingBuffer.String())

}
Loading