-
Notifications
You must be signed in to change notification settings - Fork 1.8k
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
Closed
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
4ed5ee3
Init Storage IAM policy
a7a8730
remove unused func
f991696
Add object iam policy
37dc607
allow disabled KubernetesDashboard
78b5839
Add website doc for resource storage_bucket_iam_policy
538df50
Correct PR
e3c7096
Add docs
3e577f0
clean
616dbda
clean
fa1d298
correct PR
44b4eb9
correct pr
1487793
remove duplicate
580b153
Add comment on test
09007e7
correct
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
} | ||
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()) | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.