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 google_logging_folder_sink resource #470

Merged
merged 4 commits into from
Oct 3, 2017
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions google/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ func Provider() terraform.ResourceProvider {
"google_folder": resourceGoogleFolder(),
"google_folder_iam_policy": resourceGoogleFolderIamPolicy(),
"google_logging_billing_account_sink": resourceLoggingBillingAccountSink(),
"google_logging_folder_sink": resourceLoggingFolderSink(),
"google_logging_project_sink": resourceLoggingProjectSink(),
"google_sourcerepo_repository": resourceSourceRepoRepository(),
"google_spanner_instance": resourceSpannerInstance(),
Expand Down
95 changes: 95 additions & 0 deletions google/resource_logging_folder_sink.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package google

import (
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"strings"
)

func resourceLoggingFolderSink() *schema.Resource {
schm := &schema.Resource{
Create: resourceLoggingFolderSinkCreate,
Read: resourceLoggingFolderSinkRead,
Delete: resourceLoggingFolderSinkDelete,
Update: resourceLoggingFolderSinkUpdate,
Schema: resourceLoggingSinkSchema(),
}
schm.Schema["folder"] = &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: optionalPrefixSuppress("folders/"),
}
schm.Schema["include_children"] = &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
}

return schm
}

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

folder := d.Get("folder").(string)
Copy link
Contributor

Choose a reason for hiding this comment

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

You can use parseFolderId

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

if strings.HasPrefix(folder, "folders/") {
folder = folder[len("folders/"):]
}

id, sink := expandResourceLoggingSink(d, "folders", folder)
sink.IncludeChildren = d.Get("include_children").(bool)

// The API will reject any requests that don't explicitly set 'uniqueWriterIdentity' to true.
_, err := config.clientLogging.Folders.Sinks.Create(id.parent(), sink).UniqueWriterIdentity(true).Do()
if err != nil {
return err
}

d.SetId(id.canonicalId())
return resourceLoggingFolderSinkRead(d, meta)
}

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

sink, err := config.clientLogging.Folders.Sinks.Get(d.Id()).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Folder Logging Sink %s", d.Get("name").(string)))
}

flattenResourceLoggingSink(d, sink)
d.Set("include_children", sink.IncludeChildren)

return nil
}

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

sink := expandResourceLoggingSinkForUpdate(d)
// It seems the API might actually accept an update for include_children; this is not in the list of updatable
// properties though and might break in the future. Always include the value to prevent it changing.
sink.IncludeChildren = d.Get("include_children").(bool)
sink.ForceSendFields = append(sink.ForceSendFields, "IncludeChildren")

// The API will reject any requests that don't explicitly set 'uniqueWriterIdentity' to true.
_, err := config.clientLogging.Folders.Sinks.Patch(d.Id(), sink).UniqueWriterIdentity(true).Do()
if err != nil {
return err
}

return resourceLoggingFolderSinkRead(d, meta)
}

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

_, err := config.clientLogging.Projects.Sinks.Delete(d.Id()).Do()
if err != nil {
return err
}

return nil
}
218 changes: 218 additions & 0 deletions google/resource_logging_folder_sink_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
package google

import (
"fmt"
"os"
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"google.golang.org/api/logging/v2"
"strconv"
)

func TestAccLoggingFolderSink_basic(t *testing.T) {
skipIfEnvNotSet(t, "GOOGLE_ORG")

sinkName := "tf-test-sink-" + acctest.RandString(10)
bucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
folderName := "tf-test-folder-" + acctest.RandString(10)
org := os.Getenv("GOOGLE_ORG")

var sink logging.LogSink

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckLoggingFolderSinkDestroy,
Steps: []resource.TestStep{
{
Config: testAccLoggingFolderSink_basic(sinkName, bucketName, folderName, "organizations/"+org),
Check: resource.ComposeTestCheckFunc(
testAccCheckLoggingFolderSinkExists("google_logging_folder_sink.basic", &sink),
testAccCheckLoggingFolderSink(&sink, "google_logging_folder_sink.basic"),
),
},
},
})
}

func TestAccLoggingFolderSink_folderAcceptsFullFolderPath(t *testing.T) {
skipIfEnvNotSet(t, "GOOGLE_ORG")

sinkName := "tf-test-sink-" + acctest.RandString(10)
bucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
folderName := "tf-test-folder-" + acctest.RandString(10)
org := os.Getenv("GOOGLE_ORG")

var sink logging.LogSink

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckLoggingFolderSinkDestroy,
Steps: []resource.TestStep{
{
Config: testAccLoggingFolderSink_withFullFolderPath(sinkName, bucketName, folderName, "organizations/"+org),
Check: resource.ComposeTestCheckFunc(
testAccCheckLoggingFolderSinkExists("google_logging_folder_sink.basic", &sink),
testAccCheckLoggingFolderSink(&sink, "google_logging_folder_sink.basic"),
),
},
},
})
}

func TestAccLoggingFolderSink_update(t *testing.T) {
skipIfEnvNotSet(t, "GOOGLE_ORG")

sinkName := "tf-test-sink-" + acctest.RandString(10)
bucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
updatedBucketName := "tf-test-sink-bucket-" + acctest.RandString(10)
folderName := "tf-test-folder-" + acctest.RandString(10)
parent := "organizations/" + os.Getenv("GOOGLE_ORG")

var sinkBefore, sinkAfter logging.LogSink

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckLoggingFolderSinkDestroy,
Steps: []resource.TestStep{
{
Config: testAccLoggingFolderSink_basic(sinkName, bucketName, folderName, parent),
Check: resource.ComposeTestCheckFunc(
testAccCheckLoggingFolderSinkExists("google_logging_folder_sink.basic", &sinkBefore),
testAccCheckLoggingFolderSink(&sinkBefore, "google_logging_folder_sink.basic"),
),
}, {
Config: testAccLoggingFolderSink_basic(sinkName, updatedBucketName, folderName, parent),
Check: resource.ComposeTestCheckFunc(
testAccCheckLoggingFolderSinkExists("google_logging_folder_sink.basic", &sinkAfter),
testAccCheckLoggingFolderSink(&sinkAfter, "google_logging_folder_sink.basic"),
),
},
},
})

// Destination should have changed, but WriterIdentity should be the same
if sinkBefore.Destination == sinkAfter.Destination {
t.Errorf("Expected Destination to change, but it didn't: Destination = %#v", sinkBefore.Destination)
}
if sinkBefore.WriterIdentity != sinkAfter.WriterIdentity {
t.Errorf("Expected WriterIdentity to be the same, but it differs: before = %#v, after = %#v",
sinkBefore.WriterIdentity, sinkAfter.WriterIdentity)
}
}

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

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

attributes := rs.Primary.Attributes

_, err := config.clientLogging.Folders.Sinks.Get(attributes["id"]).Do()
if err == nil {
return fmt.Errorf("folder sink still exists")
}
}

return nil
}

func testAccCheckLoggingFolderSinkExists(n string, sink *logging.LogSink) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributes, err := getResourceAttributes(n, s)
if err != nil {
return err
}
config := testAccProvider.Meta().(*Config)

si, err := config.clientLogging.Folders.Sinks.Get(attributes["id"]).Do()
if err != nil {
return err
}
*sink = *si

return nil
}
}

func testAccCheckLoggingFolderSink(sink *logging.LogSink, n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
attributes, err := getResourceAttributes(n, s)
if err != nil {
return err
}

if sink.Destination != attributes["destination"] {
return fmt.Errorf("mismatch on destination: api has %s but client has %s", sink.Destination, attributes["destination"])
}

if sink.Filter != attributes["filter"] {
return fmt.Errorf("mismatch on filter: api has %s but client has %s", sink.Filter, attributes["filter"])
}

if sink.WriterIdentity != attributes["writer_identity"] {
return fmt.Errorf("mismatch on writer_identity: api has %s but client has %s", sink.WriterIdentity, attributes["writer_identity"])
}

includeChildren := false
if attributes["include_children"] != "" {
includeChildren, err = strconv.ParseBool(attributes["include_children"])
if err != nil {
return err
}
}
if sink.IncludeChildren != includeChildren {
return fmt.Errorf("mismatch on include_children: api has %s but client has %s", sink.IncludeChildren, attributes["include_children"])
Copy link
Contributor

Choose a reason for hiding this comment

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

go vet fails because you are coercing a bool to a string. Use %t

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed, went with %v (and the correct variable this time)

}

return nil
}
}

func testAccLoggingFolderSink_basic(sinkName, bucketName, folderName, folderParent string) string {
return fmt.Sprintf(`
resource "google_logging_folder_sink" "basic" {
name = "%s"
folder = "${element(split("/", google_folder.my-folder.name), 1)}"
destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}"
filter = "logName=\"projects/%s/logs/compute.googleapis.com%%2Factivity_log\" AND severity>=ERROR"
include_children = true
}

resource "google_storage_bucket" "log-bucket" {
name = "%s"
}

resource "google_folder" "my-folder" {
display_name = "%s"
parent = "%s"
}`, sinkName, getTestProjectFromEnv(), bucketName, folderName, folderParent)
}

func testAccLoggingFolderSink_withFullFolderPath(sinkName, bucketName, folderName, folderParent string) string {
return fmt.Sprintf(`
resource "google_logging_folder_sink" "basic" {
name = "%s"
folder = "${google_folder.my-folder.name}"
destination = "storage.googleapis.com/${google_storage_bucket.log-bucket.name}"
filter = "logName=\"projects/%s/logs/compute.googleapis.com%%2Factivity_log\" AND severity>=ERROR"
include_children = false
}

resource "google_storage_bucket" "log-bucket" {
name = "%s"
}

resource "google_folder" "my-folder" {
display_name = "%s"
parent = "%s"
}`, sinkName, getTestProjectFromEnv(), bucketName, folderName, folderParent)
}
6 changes: 6 additions & 0 deletions google/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,12 @@ func linkDiffSuppress(k, old, new string, d *schema.ResourceData) bool {
return false
}

func optionalPrefixSuppress(prefix string) schema.SchemaDiffSuppressFunc {
return func(k, old, new string, d *schema.ResourceData) bool {
return prefix+old == new || prefix+new == old
}
}

func ipCidrRangeDiffSuppress(k, old, new string, d *schema.ResourceData) bool {
// The range may be a:
// A) single IP address (e.g. 10.2.3.4)
Expand Down
2 changes: 1 addition & 1 deletion website/docs/r/logging_billing_account_sink.html.markdown
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
layout: "google"
page_title: "Google: google_logging_billing-account_sink"
page_title: "Google: google_logging_billing_account_sink"
sidebar_current: "docs-google-logging-billing-account-sink"
description: |-
Manages a billing account logging sink.
Expand Down
Loading