Skip to content

Commit b164571

Browse files
Enable Log Analytics for logging_project_bucket_config resource (#7419) (#14043)
Signed-off-by: Modular Magician <[email protected]>
1 parent 3aa212a commit b164571

File tree

4 files changed

+357
-1
lines changed

4 files changed

+357
-1
lines changed

.changelog/7419.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
```release-note:enhancement
2+
logging: added `enable_analytics` field to `google_logging_project_bucket_config`
3+
```

google/resource_logging_bucket_config_test.go

+52
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,41 @@ func TestAccLoggingBucketConfigProject_basic(t *testing.T) {
8686
})
8787
}
8888

89+
func TestAccLoggingBucketConfigProject_analyticsEnabled(t *testing.T) {
90+
t.Parallel()
91+
92+
context := map[string]interface{}{
93+
"random_suffix": RandString(t, 10),
94+
"project_name": "tf-test-" + RandString(t, 10),
95+
"org_id": GetTestOrgFromEnv(t),
96+
}
97+
98+
VcrTest(t, resource.TestCase{
99+
PreCheck: func() { testAccPreCheck(t) },
100+
Providers: TestAccProviders,
101+
Steps: []resource.TestStep{
102+
{
103+
Config: testAccLoggingBucketConfigProject_analyticsEnabled(context, true),
104+
},
105+
{
106+
ResourceName: "google_logging_project_bucket_config.basic",
107+
ImportState: true,
108+
ImportStateVerify: true,
109+
ImportStateVerifyIgnore: []string{"project"},
110+
},
111+
{
112+
Config: testAccLoggingBucketConfigProject_analyticsEnabled(context, false),
113+
},
114+
{
115+
ResourceName: "google_logging_project_bucket_config.basic",
116+
ImportState: true,
117+
ImportStateVerify: true,
118+
ImportStateVerifyIgnore: []string{"project"},
119+
},
120+
},
121+
})
122+
}
123+
89124
func TestAccLoggingBucketConfigProject_cmekSettings(t *testing.T) {
90125
t.Parallel()
91126

@@ -230,6 +265,23 @@ resource "google_logging_project_bucket_config" "basic" {
230265
`, context), retention, retention)
231266
}
232267

268+
func testAccLoggingBucketConfigProject_analyticsEnabled(context map[string]interface{}, analytics bool) string {
269+
return fmt.Sprintf(Nprintf(`
270+
resource "google_project" "default" {
271+
project_id = "%{project_name}"
272+
name = "%{project_name}"
273+
org_id = "%{org_id}"
274+
}
275+
276+
resource "google_logging_project_bucket_config" "basic" {
277+
project = google_project.default.name
278+
location = "global"
279+
enable_analytics = %t
280+
bucket_id = "_Default"
281+
}
282+
`, context), analytics)
283+
}
284+
233285
func testAccLoggingBucketConfigProject_preCmekSettings(context map[string]interface{}, keyRingName, cryptoKeyName, cryptoKeyNameUpdate string) string {
234286
return fmt.Sprintf(Nprintf(`
235287
resource "google_project" "default" {

google/resource_logging_project_bucket_config.go

+288-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package google
22

33
import (
44
"fmt"
5+
"log"
6+
"strconv"
57
"strings"
68

79
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
@@ -14,6 +16,88 @@ var loggingProjectBucketConfigSchema = map[string]*schema.Schema{
1416
ForceNew: true,
1517
Description: `The parent project that contains the logging bucket.`,
1618
},
19+
"name": {
20+
Type: schema.TypeString,
21+
Computed: true,
22+
Description: `The resource name of the bucket`,
23+
},
24+
"location": {
25+
Type: schema.TypeString,
26+
Required: true,
27+
ForceNew: true,
28+
Description: `The location of the bucket.`,
29+
},
30+
"bucket_id": {
31+
Type: schema.TypeString,
32+
Required: true,
33+
ForceNew: true,
34+
Description: `The name of the logging bucket. Logging automatically creates two log buckets: _Required and _Default.`,
35+
},
36+
"description": {
37+
Type: schema.TypeString,
38+
Optional: true,
39+
Computed: true,
40+
Description: `An optional description for this bucket.`,
41+
},
42+
"retention_days": {
43+
Type: schema.TypeInt,
44+
Optional: true,
45+
Default: 30,
46+
Description: `Logs will be retained by default for this amount of time, after which they will automatically be deleted. The minimum retention period is 1 day. If this value is set to zero at bucket creation time, the default time of 30 days will be used.`,
47+
},
48+
"enable_analytics": {
49+
Type: schema.TypeBool,
50+
Optional: true,
51+
Description: `Enable log analytics for the bucket. Cannot be disabled once enabled.`,
52+
DiffSuppressFunc: enableAnalyticsBackwardsChangeDiffSuppress,
53+
},
54+
"lifecycle_state": {
55+
Type: schema.TypeString,
56+
Computed: true,
57+
Description: `The bucket's lifecycle such as active or deleted.`,
58+
},
59+
"cmek_settings": {
60+
Type: schema.TypeList,
61+
MaxItems: 1,
62+
Optional: true,
63+
Description: `The CMEK settings of the log bucket. If present, new log entries written to this log bucket are encrypted using the CMEK key provided in this configuration. If a log bucket has CMEK settings, the CMEK settings cannot be disabled later by updating the log bucket. Changing the KMS key is allowed.`,
64+
Elem: &schema.Resource{
65+
Schema: map[string]*schema.Schema{
66+
"name": {
67+
Type: schema.TypeString,
68+
Computed: true,
69+
Description: `The resource name of the CMEK settings.`,
70+
},
71+
"kms_key_name": {
72+
Type: schema.TypeString,
73+
Required: true,
74+
Description: `The resource name for the configured Cloud KMS key.
75+
KMS key name format:
76+
"projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING]/cryptoKeys/[KEY]"
77+
To enable CMEK for the bucket, set this field to a valid kmsKeyName for which the associated service account has the required cloudkms.cryptoKeyEncrypterDecrypter roles assigned for the key.
78+
The Cloud KMS key used by the bucket can be updated by changing the kmsKeyName to a new valid key name. Encryption operations that are in progress will be completed with the key that was in use when they started. Decryption operations will be completed using the key that was used at the time of encryption unless access to that key has been revoked.
79+
See [Enabling CMEK for Logging Buckets](https://cloud.google.com/logging/docs/routing/managed-encryption-storage) for more information.`,
80+
},
81+
"kms_key_version_name": {
82+
Type: schema.TypeString,
83+
Computed: true,
84+
Description: `The CryptoKeyVersion resource name for the configured Cloud KMS key.
85+
KMS key name format:
86+
"projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEYRING]/cryptoKeys/[KEY]/cryptoKeyVersions/[VERSION]"
87+
For example:
88+
"projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key/cryptoKeyVersions/1"
89+
This is a read-only field used to convey the specific configured CryptoKeyVersion of kms_key that has been configured. It will be populated in cases where the CMEK settings are bound to a single key version.`,
90+
},
91+
"service_account_id": {
92+
Type: schema.TypeString,
93+
Computed: true,
94+
Description: `The service account associated with a project for which CMEK will apply.
95+
Before enabling CMEK for a logging bucket, you must first assign the cloudkms.cryptoKeyEncrypterDecrypter role to the service account associated with the project for which CMEK will apply. Use [v2.getCmekSettings](https://cloud.google.com/logging/docs/reference/v2/rest/v2/TopLevel/getCmekSettings#google.logging.v2.ConfigServiceV2.GetCmekSettings) to obtain the service account ID.
96+
See [Enabling CMEK for Logging Buckets](https://cloud.google.com/logging/docs/routing/managed-encryption-storage) for more information.`,
97+
},
98+
},
99+
},
100+
},
17101
}
18102

19103
func projectBucketConfigID(d *schema.ResourceData, config *Config) (string, error) {
@@ -31,5 +115,208 @@ func projectBucketConfigID(d *schema.ResourceData, config *Config) (string, erro
31115

32116
// Create Logging Bucket config
33117
func ResourceLoggingProjectBucketConfig() *schema.Resource {
34-
return ResourceLoggingBucketConfig("project", loggingProjectBucketConfigSchema, projectBucketConfigID)
118+
return &schema.Resource{
119+
Create: resourceLoggingProjectBucketConfigAcquireOrCreate("project", projectBucketConfigID),
120+
Read: resourceLoggingProjectBucketConfigRead,
121+
Update: resourceLoggingProjectBucketConfigUpdate,
122+
Delete: resourceLoggingBucketConfigDelete,
123+
Importer: &schema.ResourceImporter{
124+
State: resourceLoggingBucketConfigImportState("project"),
125+
},
126+
Schema: loggingProjectBucketConfigSchema,
127+
UseJSONNumber: true,
128+
}
129+
}
130+
131+
func resourceLoggingProjectBucketConfigAcquireOrCreate(parentType string, iDFunc loggingBucketConfigIDFunc) func(*schema.ResourceData, interface{}) error {
132+
return func(d *schema.ResourceData, meta interface{}) error {
133+
config := meta.(*Config)
134+
userAgent, err := generateUserAgentString(d, config.UserAgent)
135+
if err != nil {
136+
return err
137+
}
138+
139+
id, err := iDFunc(d, config)
140+
if err != nil {
141+
return err
142+
}
143+
144+
if parentType == "project" {
145+
//logging bucket can be created only at the project level, in future api may allow for folder, org and other parent resources
146+
147+
log.Printf("[DEBUG] Fetching logging bucket config: %#v", id)
148+
url, err := replaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", id))
149+
if err != nil {
150+
return err
151+
}
152+
153+
res, _ := SendRequest(config, "GET", "", url, userAgent, nil)
154+
if res == nil {
155+
log.Printf("[DEGUG] Loggin Bucket not exist %s", id)
156+
// we need to pass the id in here because we don't want to set it in state
157+
// until we know there won't be any errors on create
158+
return resourceLoggingProjectBucketConfigCreate(d, meta, id)
159+
}
160+
}
161+
162+
d.SetId(id)
163+
164+
return resourceLoggingProjectBucketConfigUpdate(d, meta)
165+
}
166+
}
167+
168+
func resourceLoggingProjectBucketConfigCreate(d *schema.ResourceData, meta interface{}, id string) error {
169+
config := meta.(*Config)
170+
userAgent, err := generateUserAgentString(d, config.UserAgent)
171+
if err != nil {
172+
return err
173+
}
174+
175+
obj := make(map[string]interface{})
176+
obj["name"] = d.Get("name")
177+
obj["description"] = d.Get("description")
178+
obj["retentionDays"] = d.Get("retention_days")
179+
obj["analyticsEnabled"] = d.Get("enable_analytics")
180+
obj["locked"] = d.Get("locked")
181+
obj["cmekSettings"] = expandCmekSettings(d.Get("cmek_settings"))
182+
183+
url, err := replaceVars(d, config, "{{LoggingBasePath}}projects/{{project}}/locations/{{location}}/buckets?bucketId={{bucket_id}}")
184+
if err != nil {
185+
return err
186+
}
187+
188+
log.Printf("[DEBUG] Creating new Bucket: %#v", obj)
189+
billingProject := ""
190+
191+
project, err := getProject(d, config)
192+
if err != nil {
193+
return err
194+
}
195+
billingProject = project
196+
197+
// err == nil indicates that the billing_project value was found
198+
if bp, err := getBillingProject(d, config); err == nil {
199+
billingProject = bp
200+
}
201+
202+
res, err := SendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate))
203+
if err != nil {
204+
return fmt.Errorf("Error creating Bucket: %s", err)
205+
}
206+
207+
d.SetId(id)
208+
209+
log.Printf("[DEBUG] Finished creating Bucket %q: %#v", d.Id(), res)
210+
211+
return resourceLoggingProjectBucketConfigRead(d, meta)
212+
}
213+
214+
func resourceLoggingProjectBucketConfigRead(d *schema.ResourceData, meta interface{}) error {
215+
config := meta.(*Config)
216+
userAgent, err := generateUserAgentString(d, config.UserAgent)
217+
if err != nil {
218+
return err
219+
}
220+
221+
log.Printf("[DEBUG] Fetching logging bucket config: %#v", d.Id())
222+
223+
url, err := replaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", d.Id()))
224+
if err != nil {
225+
return err
226+
}
227+
228+
res, err := SendRequest(config, "GET", "", url, userAgent, nil)
229+
if err != nil {
230+
log.Printf("[WARN] Unable to acquire logging bucket config at %s", d.Id())
231+
232+
d.SetId("")
233+
return err
234+
}
235+
236+
if err := d.Set("name", res["name"]); err != nil {
237+
return fmt.Errorf("Error setting name: %s", err)
238+
}
239+
if err := d.Set("description", res["description"]); err != nil {
240+
return fmt.Errorf("Error setting description: %s", err)
241+
}
242+
if err := d.Set("lifecycle_state", res["lifecycleState"]); err != nil {
243+
return fmt.Errorf("Error setting lifecycle_state: %s", err)
244+
}
245+
if err := d.Set("retention_days", res["retentionDays"]); err != nil {
246+
return fmt.Errorf("Error setting retention_days: %s", err)
247+
}
248+
if err := d.Set("enable_analytics", res["analyticsEnabled"]); err != nil {
249+
return fmt.Errorf("Error setting enable_analytics: %s", err)
250+
}
251+
252+
if err := d.Set("cmek_settings", flattenCmekSettings(res["cmekSettings"])); err != nil {
253+
return fmt.Errorf("Error setting cmek_settings: %s", err)
254+
}
255+
256+
return nil
257+
}
258+
259+
func resourceLoggingProjectBucketConfigUpdate(d *schema.ResourceData, meta interface{}) error {
260+
config := meta.(*Config)
261+
userAgent, err := generateUserAgentString(d, config.UserAgent)
262+
if err != nil {
263+
return err
264+
}
265+
266+
obj := make(map[string]interface{})
267+
268+
url, err := replaceVars(d, config, fmt.Sprintf("{{LoggingBasePath}}%s", d.Id()))
269+
if err != nil {
270+
return err
271+
}
272+
273+
updateMaskAnalytics := []string{}
274+
// Check if analytics is being enabled. Analytics enablement is an atomic operation and can not be performed while other fields
275+
// are being updated, so we enable analytics before updating the rest of the fields.
276+
if d.HasChange("enable_analytics") {
277+
obj["analyticsEnabled"] = d.Get("enable_analytics")
278+
updateMaskAnalytics = append(updateMaskAnalytics, "analyticsEnabled")
279+
url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMaskAnalytics, ",")})
280+
if err != nil {
281+
return err
282+
}
283+
_, err = SendRequestWithTimeout(config, "PATCH", "", url, userAgent, obj, d.Timeout(schema.TimeoutUpdate))
284+
if err != nil {
285+
return fmt.Errorf("Error updating Logging Bucket Config %q: %s", d.Id(), err)
286+
}
287+
}
288+
289+
obj["retentionDays"] = d.Get("retention_days")
290+
obj["description"] = d.Get("description")
291+
obj["cmekSettings"] = expandCmekSettings(d.Get("cmek_settings"))
292+
updateMask := []string{}
293+
if d.HasChange("retention_days") {
294+
updateMask = append(updateMask, "retentionDays")
295+
}
296+
if d.HasChange("description") {
297+
updateMask = append(updateMask, "description")
298+
}
299+
if d.HasChange("cmek_settings") {
300+
updateMask = append(updateMask, "cmekSettings")
301+
}
302+
url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")})
303+
if err != nil {
304+
return err
305+
}
306+
if len(updateMask) > 0 {
307+
_, err = SendRequestWithTimeout(config, "PATCH", "", url, userAgent, obj, d.Timeout(schema.TimeoutUpdate))
308+
}
309+
if err != nil {
310+
return fmt.Errorf("Error updating Logging Bucket Config %q: %s", d.Id(), err)
311+
}
312+
313+
return resourceLoggingProjectBucketConfigRead(d, meta)
314+
}
315+
316+
func enableAnalyticsBackwardsChangeDiffSuppress(k, old, new string, d *schema.ResourceData) bool {
317+
oldValue, _ := strconv.ParseBool(old)
318+
if oldValue {
319+
return true
320+
}
321+
return false
35322
}

0 commit comments

Comments
 (0)