Skip to content

Commit

Permalink
Convert the rest custom templates (GoogleCloudPlatform#10470)
Browse files Browse the repository at this point in the history
  • Loading branch information
zli82016 authored Apr 18, 2024
1 parent 3b4b2e0 commit 325b74c
Show file tree
Hide file tree
Showing 138 changed files with 8,100 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
log.Printf("[WARN] Attempt to clean up {{$.Name}} if it still exists")
var cleanErr error
if cleanErr = resource{{$.ResourceName}}Read(d, meta); cleanErr == nil {
if d.Id() != "" {
log.Printf("[WARN] {{$.Name}} %q still exists, attempting to delete...", d.Id())
if cleanErr = resource{{$.ResourceName}}Delete(d, meta); cleanErr == nil {
log.Printf("[WARN] Invalid {{$.Name}} was successfully deleted")
d.SetId("")
}
}
}
if cleanErr != nil {
log.Printf("[WARN] Could not confirm cleanup of {{$.Name}} if created in error state: %v", cleanErr)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// A replication CREATE also created a destination volume
// A user can chooses to delete the destination volume after deleting the replication
if d.Get("delete_destination_volume").(bool) == true {
log.Printf("[DEBUG] delete_destination_volume is true. Deleting destination volume %v", d.Get("destination_volume"))
destination_volume := d.Get("destination_volume").(string)
del_url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}NetappBasePath{{"}}"}}"+destination_volume+"?force=true")
if err != nil {
return err
}

var obj map[string]interface{}
res_del, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "DELETE",
Project: billingProject,
RawURL: del_url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutDelete),
})
if err != nil {
return transport_tpg.HandleNotFoundError(err, d, "Volume")
}

err = NetappOperationWaitTime(
config, res_del, project, "Deleting destination volume", userAgent,
d.Timeout(schema.TimeoutDelete))

if err != nil {
return err
}

log.Printf("[DEBUG] Finished deleting destination Volume %q: %#v", destination_volume, res_del)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
if d.Get("delete_swg_autogen_router_on_destroy").(bool) {
log.Print("[DEBUG] The field delete_swg_autogen_router_on_destroy is true. Deleting swg_autogen_router.")
gateways, err := gatewaysSameLocation(d, config, billingProject, userAgent)
if err != nil {
return err
}

network := d.Get("network").(string)
if isLastSWGGateway(gateways, network) {
err := deleteSWGAutoGenRouter(d, config, billingProject, userAgent)
if err != nil {
return err
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
parent := d.Get("parent").(string)
var opRes map[string]interface{}
err = ComputeOrgOperationWaitTimeWithResponse(
config, res, &opRes, parent, "Creating OrganizationSecurityPolicy", userAgent,
d.Timeout(schema.TimeoutCreate))

if err != nil {
// The resource didn't actually delete
return fmt.Errorf("Error waiting to delete OrganizationSecurityPolicy: %s", err)
}
39 changes: 39 additions & 0 deletions mmv1/templates/terraform/post_delete/go/private_cloud.go.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
privateCloudPollRead := func(d *schema.ResourceData, meta interface{}) transport_tpg.PollReadFunc {
return func() (map[string]interface{}, error) {
config := meta.(*transport_tpg.Config)
url, err := tpgresource.ReplaceVars(d, config, "{{"{{"}}{{$.ProductMetadata.Name}}BasePath{{"}}"}}{{$.SelfLinkUri}}")
if err != nil {
return nil, err
}
billingProject := ""
project, err := tpgresource.GetProject(d, config)
if err != nil {
return nil, fmt.Errorf("Error fetching project for PrivateCloud: %s", err)
}
billingProject = project
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return nil, err
}
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
})
if err != nil {
return res, err
}
return res, nil
}
}

err = transport_tpg.PollingWaitTime(privateCloudPollRead(d, meta), transport_tpg.PollCheckForAbsence, "Deleting {{$.Name}}", d.Timeout(schema.TimeoutDelete), 10)
if err != nil {
return fmt.Errorf("Error waiting to delete PrivateCloud: %s", err)
}
2 changes: 1 addition & 1 deletion mmv1/templates/terraform/post_delete/private_cloud.go.erb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
privateCloudPollRead := func(d *schema.ResourceData, meta interface{}) transport_tpg.PollReadFunc {
return func() (map[string]interface{}, error) {
config := meta.(*transport_tpg.Config)
url, err := tpgresource.ReplaceVars(d, config, "<%= "{{#{object.__product.name}BasePath}}#{object.self_link_uri}" -%>")
url, err := tpgresource.ReplaceVars(d, config, "{{<%=object.__product.name-%>BasePath}}<%=object.self_link_uri-%>")
if err != nil {
return nil, err
}
Expand Down
3 changes: 3 additions & 0 deletions mmv1/templates/terraform/post_import/go/agent_pool.go.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
if err := waitForAgentPoolReady(d, config, d.Timeout(schema.TimeoutCreate) - time.Minute); err != nil {
return nil, fmt.Errorf("Error waiting for AgentPool %q to be CREATED during importing: %q", d.Get("name").(string), err)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{{- /*
The license inside this block applies to this file
Copyright 2024 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/}}
// Configure "group" property, which does not appear in the response body.
group := regexp.MustCompile(`groups/[^/]+`).FindString(id)
if err := d.Set("group", group); err != nil {
return nil, fmt.Errorf("Error setting group property: %s", err)
}
20 changes: 20 additions & 0 deletions mmv1/templates/terraform/post_import/go/cloudbuild_trigger.go.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{{- /*
The license inside this block applies to this file
Copyright 2024 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/}}
// Force legacy id format for global triggers.
id = strings.ReplaceAll(id, "/locations//", "/")
id = strings.ReplaceAll(id, "/locations/global/", "/")
d.SetId(id)
if d.Get("location") == "" {
// Happens when imported with legacy import format.
d.Set("location", "global")
}
15 changes: 15 additions & 0 deletions mmv1/templates/terraform/post_import/go/datastream_stream.go.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{{- /*
The license inside this block applies to this file
Copyright 2024 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/}}
if err := waitForDatastreamStreamReady(d, config, d.Timeout(schema.TimeoutCreate) - time.Minute); err != nil {
return nil, fmt.Errorf("Error waiting for Stream %q to be NOT_STARTED, RUNNING, or PAUSED during import: %q", d.Get("name").(string), err)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
if err := waitforConnectionReady(d, config, d.Timeout(schema.TimeoutCreate) - time.Minute); err != nil {
return nil, fmt.Errorf("Error waiting for Connection %q to be in a stable state: %q", d.Get("name").(string), err)
}
7 changes: 7 additions & 0 deletions mmv1/templates/terraform/post_import/go/lien_import.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
parent, err := tpgresource.ReplaceVars(d, config, "projects/{{"{{"}}parent{{"}}"}}")
if err != nil {
return nil, err
}
if err := d.Set("parent", parent); err != nil {
return nil, fmt.Errorf("Error setting parent: %s", err)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
if err := waitForPrivateConnectionReady(d, config, d.Timeout(schema.TimeoutCreate) - time.Minute); err != nil {
return nil, fmt.Errorf("Error waiting for PrivateConnection %q to be CREATED during importing: %q", d.Get("name").(string), err)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
if err := d.Set("ignore_active_certificates_on_deletion", false); err != nil {
return nil, err
}
33 changes: 33 additions & 0 deletions mmv1/templates/terraform/post_update/go/cloud_scheduler.go.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
if d.HasChange("paused") {
endpoint := "resume" // Default to enabled
logSuccessMsg := "Job state has been set to ENABLED"
if paused, pausedOk := d.GetOk("paused"); pausedOk {
if paused.(bool) {
endpoint = "pause"
logSuccessMsg = "Job state has been set to PAUSED"
}
}

linkTmpl := fmt.Sprintf("{{"{{"}}CloudSchedulerBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/locations/{{"{{"}}region{{"}}"}}/jobs/{{"{{"}}name{{"}}"}}:%s", endpoint)
url, err = tpgresource.ReplaceVars(d, config, linkTmpl)
if err != nil {
return err
}

emptyReqBody := make(map[string]interface{})

_, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: emptyReqBody,
Timeout: d.Timeout(schema.TimeoutUpdate),
})
if err != nil {
return fmt.Errorf("Error setting Cloud Scheduler Job status: %s", err)
}

log.Printf("[DEBUG] Finished updating Job %q status: %s", d.Id(), logSuccessMsg)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
if d.HasChange("connected_repositories") {
o, n := d.GetChange("connected_repositories")
oReposSet, ok := o.(*schema.Set)
if !ok {
return fmt.Errorf("Error reading old connected repositories")
}
nReposSet, ok := n.(*schema.Set)
if !ok {
return fmt.Errorf("Error reading new connected repositories")
}

removeRepos := oReposSet.Difference(nReposSet).List()
createRepos := nReposSet.Difference(oReposSet).List()

url, err = tpgresource.ReplaceVars(d, config, "{{"{{"}}CloudBuildBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/locations/{{"{{"}}location{{"}}"}}/bitbucketServerConfigs/{{"{{"}}config_id{{"}}"}}:removeBitbucketServerConnectedRepository")
if err != nil {
return err
}

// send remove repo requests.
for _, repo := range removeRepos {
obj := make(map[string]interface{})
obj["connectedRepository"] = repo
_, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutCreate),
})
if err != nil {
return fmt.Errorf("Error removing connected_repositories: %s", err)
}
}

// if repos to create, prepare and send batchCreate request
if len(createRepos) > 0 {
parent, err := tpgresource.ReplaceVars(d, config, "projects/{{"{{"}}project{{"}}"}}/locations/{{"{{"}}location{{"}}"}}/bitbucketServerConfigs/{{"{{"}}config_id{{"}}"}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
var requests []interface{}
for _, repo := range createRepos {
connectedRepo := make(map[string]interface{})
connectedRepo["parent"] = parent
connectedRepo["repo"] = repo

connectedRepoRequest := make(map[string]interface{})
connectedRepoRequest["parent"] = parent
connectedRepoRequest["bitbucketServerConnectedRepository"] = connectedRepo

requests = append(requests, connectedRepoRequest)
}
obj = make(map[string]interface{})
obj["requests"] = requests

url, err = tpgresource.ReplaceVars(d, config, "{{"{{"}}CloudBuildBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/locations/{{"{{"}}location{{"}}"}}/bitbucketServerConfigs/{{"{{"}}config_id{{"}}"}}/connectedRepositories:batchCreate")
if err != nil {
return err
}

res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutCreate),
})
if err != nil {
return fmt.Errorf("Error creating connected_repositories: %s", err)
}

err = CloudBuildOperationWaitTime(
config, res, project, "Updating connected_repositories on BitbucketServerConfig", userAgent,
d.Timeout(schema.TimeoutUpdate))
if err != nil {
return fmt.Errorf("Error waiting to create connected_repositories: %s", err)
}
}
} else {
log.Printf("[DEBUG] connected_repositories have no changes")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Instance name in applyUpdatesToInstances request must include zone
instanceName, err := tpgresource.ReplaceVars(d, config, "zones/{{"{{"}}zone{{"}}"}}/instances/{{"{{"}}name{{"}}"}}")
if err != nil {
return err
}

obj = make(map[string]interface{})
obj["instances"] = []string{instanceName}

minAction := d.Get("minimal_action")
if minAction == "" {
minAction = "NONE"
}
obj["minimalAction"] = minAction

mostDisruptiveAction := d.Get("most_disruptive_allowed_action")
if tpgresource.IsEmptyValue(reflect.ValueOf(mostDisruptiveAction)) {
mostDisruptiveAction = "REPLACE"
}
obj["mostDisruptiveAllowedAction"] = mostDisruptiveAction

url, err = tpgresource.ReplaceVars(d, config, "{{"{{"}}ComputeBasePath{{"}}"}}projects/{{"{{"}}project{{"}}"}}/zones/{{"{{"}}zone{{"}}"}}/instanceGroupManagers/{{"{{"}}instance_group_manager{{"}}"}}/applyUpdatesToInstances")
if err != nil {
return err
}

log.Printf("[DEBUG] Applying updates to PerInstanceConfig %q: %#v", d.Id(), obj)
res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: project,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutUpdate),
})

if err != nil {
return fmt.Errorf("Error updating PerInstanceConfig %q: %s", d.Id(), err)
}

err = ComputeOperationWaitTime(
config, res, project, "Applying update to PerInstanceConfig", userAgent,
d.Timeout(schema.TimeoutUpdate))

if err != nil {
return err
}
Loading

0 comments on commit 325b74c

Please sign in to comment.