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

Add IAM resources for Spanner databases. #1386

Merged
merged 4 commits into from
May 2, 2018
Merged
Changes from 1 commit
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
141 changes: 141 additions & 0 deletions google/iam_spanner_database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package google

import (
"fmt"

"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/cloudresourcemanager/v1"
spanner "google.golang.org/api/spanner/v1"
)

var IamSpannerDatabaseSchema = map[string]*schema.Schema{
"instance": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"database": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
}

type SpannerDatabaseIamUpdater struct {
project string
instance string
database string
Config *Config
}

func NewSpannerDatabaseIamUpdater(d *schema.ResourceData, config *Config) (ResourceIamUpdater, error) {
project, err := getProject(d, config)
if err != nil {
return nil, err
}

return &SpannerDatabaseIamUpdater{
project: project,
instance: d.Get("instance").(string),
database: d.Get("database").(string),
Config: config,
}, nil
}

func SpannerDatabaseIdParseFunc(d *schema.ResourceData, config *Config) error {
id, err := extractSpannerDatabaseId(d.Id())
if err != nil {
return err
}
d.Set("instance", id.Instance)
d.Set("project", id.Project)
d.Set("database", id.Database)

// Explicitly set the id so imported resources have the same ID format as non-imported ones.
d.SetId(id.terraformId())
return nil
}

func (u *SpannerDatabaseIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) {
p, err := u.Config.clientSpanner.Projects.Instances.Databases.GetIamPolicy(spannerDatabaseId{
Project: u.project,
Database: u.database,
Instance: u.instance,
}.databaseUri(), &spanner.GetIamPolicyRequest{}).Do()

if err != nil {
return nil, errwrap.Wrapf(fmt.Sprintf("Error retrieving IAM policy for %s: {{err}}", u.DescribeResource()), err)
}

cloudResourcePolicy, err := spannerToResourceManagerPolicy(p)

if err != nil {
return nil, errwrap.Wrapf(fmt.Sprintf("Invalid IAM policy for %s: {{err}}", u.DescribeResource()), err)
}

return cloudResourcePolicy, nil
}

func (u *SpannerDatabaseIamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error {
spannerPolicy, err := resourceManagerToSpannerPolicy(policy)

if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Invalid IAM policy for %s: {{err}}", u.DescribeResource()), err)
}

_, err = u.Config.clientSpanner.Projects.Instances.Databases.SetIamPolicy(spannerDatabaseId{
Project: u.project,
Database: u.database,
Instance: u.instance,
}.databaseUri(), &spanner.SetIamPolicyRequest{
Policy: spannerPolicy,
}).Do()

if err != nil {
return errwrap.Wrapf(fmt.Sprintf("Error setting IAM policy for %s: {{err}}", u.DescribeResource()), err)
}

return nil
}

func (u *SpannerDatabaseIamUpdater) GetResourceId() string {
return spannerDatabaseId{
Project: u.project,
Instance: u.instance,
Database: u.database,
}.terraformId()
}

func (u *SpannerDatabaseIamUpdater) GetMutexKey() string {
return fmt.Sprintf("iam-spanner-database-%s-%s-%s", u.project, u.instance, u.database)
}

func (u *SpannerDatabaseIamUpdater) DescribeResource() string {
return fmt.Sprintf("Spanner Database: %s/%s/%s", u.project, u.instance, u.database)
}

func resourceManagerToSpannerPolicy(p *cloudresourcemanager.Policy) (*spanner.Policy, error) {
out := &spanner.Policy{}
err := Convert(p, out)
if err != nil {
return nil, errwrap.Wrapf("Cannot convert a resourcemanager policy to a spanner policy: {{err}}", err)
}
return out, nil
}

func spannerToResourceManagerPolicy(p *spanner.Policy) (*cloudresourcemanager.Policy, error) {
out := &cloudresourcemanager.Policy{}
err := Convert(p, out)
if err != nil {
return nil, errwrap.Wrapf("Cannot convert a spanner policy to a resourcemanager policy: {{err}}", err)
}
return out, nil
}
3 changes: 3 additions & 0 deletions google/provider.go
Original file line number Diff line number Diff line change
@@ -173,6 +173,9 @@ func Provider() terraform.ResourceProvider {
"google_sourcerepo_repository": resourceSourceRepoRepository(),
"google_spanner_instance": resourceSpannerInstance(),
"google_spanner_database": resourceSpannerDatabase(),
"google_spanner_database_iam_binding": ResourceIamBindingWithImport(IamSpannerDatabaseSchema, NewSpannerDatabaseIamUpdater, SpannerDatabaseIdParseFunc),
"google_spanner_database_iam_member": ResourceIamMemberWithImport(IamSpannerDatabaseSchema, NewSpannerDatabaseIamUpdater, SpannerDatabaseIdParseFunc),
"google_spanner_database_iam_policy": ResourceIamPolicyWithImport(IamSpannerDatabaseSchema, NewSpannerDatabaseIamUpdater, SpannerDatabaseIdParseFunc),
"google_sql_database": resourceSqlDatabase(),
"google_sql_database_instance": resourceSqlDatabaseInstance(),
"google_sql_user": resourceSqlUser(),
246 changes: 246 additions & 0 deletions google/resource_spanner_database_iam_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
package google

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)

func TestAccSpannerDatabaseIamBinding(t *testing.T) {
t.Parallel()

account := acctest.RandomWithPrefix("tf-test")
role := "roles/spanner.databaseAdmin"
project := getTestProjectFromEnv()
database := fmt.Sprintf("tf-test-%s", acctest.RandString(10))
instance := fmt.Sprintf("tf-test-%s", acctest.RandString(10))

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccSpannerDatabaseIamBinding_basic(account, instance, database, role),
},
resource.TestStep{
ResourceName: "google_spanner_database_iam_binding.foo",
ImportStateId: fmt.Sprintf("%s %s", spannerDatabaseId{
Project: project,
Instance: instance,
Database: database,
}.terraformId(), role),
ImportState: true,
ImportStateVerify: true,
},
{
// Test Iam Binding update
Config: testAccSpannerDatabaseIamBinding_update(account, instance, database, role),
},
resource.TestStep{
ResourceName: "google_spanner_database_iam_binding.foo",
ImportStateId: fmt.Sprintf("%s %s", spannerDatabaseId{
Project: project,
Instance: instance,
Database: database,
}.terraformId(), role),
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func TestAccSpannerDatabaseIamMember(t *testing.T) {
t.Parallel()

project := getTestProjectFromEnv()
account := acctest.RandomWithPrefix("tf-test")
role := "roles/spanner.databaseAdmin"
database := fmt.Sprintf("tf-test-%s", acctest.RandString(10))
instance := fmt.Sprintf("tf-test-%s", acctest.RandString(10))

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
// Test Iam Member creation (no update for member, no need to test)
Config: testAccSpannerDatabaseIamMember_basic(account, instance, database, role),
},
resource.TestStep{
ResourceName: "google_spanner_database_iam_member.foo",
ImportStateId: fmt.Sprintf("%s %s serviceAccount:%s@%s.iam.gserviceaccount.com", spannerDatabaseId{
Instance: instance,
Database: database,
Project: project,
}.terraformId(), role, account, project),
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func TestAccSpannerDatabaseIamPolicy(t *testing.T) {
t.Parallel()

project := getTestProjectFromEnv()
account := acctest.RandomWithPrefix("tf-test")
role := "roles/spanner.databaseAdmin"
database := fmt.Sprintf("tf-test-%s", acctest.RandString(10))
instance := fmt.Sprintf("tf-test-%s", acctest.RandString(10))

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccSpannerDatabaseIamPolicy_basic(account, instance, database, role),
},
// Test a few import formats
resource.TestStep{
ResourceName: "google_spanner_database_iam_policy.foo",
ImportStateId: fmt.Sprintf("%s", spannerDatabaseId{
Instance: instance,
Database: database,
Project: project,
}.terraformId()),
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func testAccSpannerDatabaseIamBinding_basic(account, instance, database, roleId string) string {
return fmt.Sprintf(`
resource "google_service_account" "test_account" {
account_id = "%s"
display_name = "Spanner Iam Testing Account"
}

resource "google_spanner_instance" "instance" {
name = "%s"
config = "regional-us-central1"
display_name = "%s"
num_nodes = 1
}

resource "google_spanner_database" "database" {
instance = "${google_spanner_instance.instance.name}"
name = "%s"
}

resource "google_spanner_database_iam_binding" "foo" {
project = "${google_spanner_database.database.project}"
database = "${google_spanner_database.database.name}"
instance = "${google_spanner_database.database.instance}"
role = "%s"
members = ["serviceAccount:${google_service_account.test_account.email}"]
}
`, account, instance, instance, database, roleId)
}

func testAccSpannerDatabaseIamBinding_update(account, instance, database, roleId string) string {
return fmt.Sprintf(`
resource "google_service_account" "test_account" {
account_id = "%s"
display_name = "Spanner Iam Testing Account"
}

resource "google_service_account" "test_account_2" {
account_id = "%s-2"
display_name = "Spanner Iam Testing Account"
}

resource "google_spanner_instance" "instance" {
name = "%s"
config = "regional-us-central1"
display_name = "%s"
num_nodes = 1
}

resource "google_spanner_database" "database" {
instance = "${google_spanner_instance.instance.name}"
name = "%s"
}

resource "google_spanner_database_iam_binding" "foo" {
project = "${google_spanner_database.database.project}"
database = "${google_spanner_database.database.name}"
instance = "${google_spanner_database.database.instance}"
role = "%s"
members = [
"serviceAccount:${google_service_account.test_account.email}",
"serviceAccount:${google_service_account.test_account_2.email}"
]
}
`, account, account, instance, instance, database, roleId)
}

func testAccSpannerDatabaseIamMember_basic(account, instance, database, roleId string) string {
return fmt.Sprintf(`
resource "google_service_account" "test_account" {
account_id = "%s"
display_name = "Spanner Iam Testing Account"
}

resource "google_spanner_instance" "instance" {
name = "%s"
config = "regional-us-central1"
display_name = "%s"
num_nodes = 1
}

resource "google_spanner_database" "database" {
instance = "${google_spanner_instance.instance.name}"
name = "%s"
}

resource "google_spanner_database_iam_member" "foo" {
project = "${google_spanner_database.database.project}"
database = "${google_spanner_database.database.name}"
instance = "${google_spanner_database.database.instance}"
role = "%s"
member = "serviceAccount:${google_service_account.test_account.email}"
}
`, account, instance, instance, database, roleId)
}

func testAccSpannerDatabaseIamPolicy_basic(account, instance, database, roleId string) string {
return fmt.Sprintf(`
resource "google_service_account" "test_account" {
account_id = "%s"
display_name = "Spanner Iam Testing Account"
}

resource "google_spanner_instance" "instance" {
name = "%s"
config = "regional-us-central1"
display_name = "%s"
num_nodes = 1
}

resource "google_spanner_database" "database" {
instance = "${google_spanner_instance.instance.name}"
name = "%s"
}

data "google_iam_policy" "foo" {
binding {
role = "%s"

members = ["serviceAccount:${google_service_account.test_account.email}"]
}
}

resource "google_spanner_database_iam_policy" "foo" {
project = "${google_spanner_database.database.project}"
database = "${google_spanner_database.database.name}"
instance = "${google_spanner_database.database.instance}"
policy_data = "${data.google_iam_policy.foo.policy_data}"
}
`, account, instance, instance, database, roleId)
}