Skip to content

Add ceritificateManagerCertificates field to ComputeTargetHttpsProxy resource #9144

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

Merged
Show file tree
Hide file tree
Changes from all 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
30 changes: 28 additions & 2 deletions mmv1/products/compute/TargetHttpsProxy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ async: !ruby/object:Api::OpAsync
error: !ruby/object:Api::OpAsync::Error
path: 'error/errors'
message: 'message'
custom_code: !ruby/object:Provider::Terraform::CustomCode
encoder: templates/terraform/encoders/compute_target_https_proxy.go.erb
decoder: templates/terraform/decoders/compute_target_https_proxy.go.erb
examples:
- !ruby/object:Provider::Terraform::Examples
name: 'target_https_proxy_basic'
Expand Down Expand Up @@ -74,6 +77,14 @@ examples:
http_health_check_name: 'http-health-check'
server_tls_policy_name: 'my-tls-policy'
trust_config_name: 'my-trust-config'
- !ruby/object:Provider::Terraform::Examples
name: 'target_https_proxy_certificate_manager_certificate'
primary_resource_id: 'default'
vars:
target_https_proxy_name: 'target-http-proxy'
certificate_manager_certificate_name: 'my-certificate'
url_map_name: 'url-map'
backend_service_name: 'backend-service'
properties:
- !ruby/object:Api::Type::Time
name: 'creationTimestamp'
Expand Down Expand Up @@ -115,19 +126,34 @@ properties:
update_url: 'projects/{{project}}/global/targetHttpsProxies/{{name}}/setQuicOverride'
default_value: :NONE
custom_flatten: 'templates/terraform/custom_flatten/default_if_empty.erb'
- !ruby/object:Api::Type::Array
name: 'certificateManagerCertificates'
description: |
A list of Certificate Manager certificate URLs that are used to authenticate
connections between users and the load balancer. At least one resource must be specified.
Accepted format is `//certificatemanager.googleapis.com/projects/{project}/locations/{location}/certificates/{resourceName}` or just the self_link projects/{project}/locations/{location}/certificates/{resourceName}
update_verb: :POST
update_url: 'projects/{{project}}/targetHttpsProxies/{{name}}/setSslCertificates'
item_type: Api::Type::String
custom_expand: 'templates/terraform/custom_expand/certificate_manager_certificate_construct_full_url.go.erb'
diff_suppress_func: 'tpgresource.CompareResourceNames'
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this necessary? I'm not sure I understand how it is being used

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Do you mean the diff_suppress_func or something else?

The API expects each item to be in full URL format (e.g. //certificatemanager.googleapis.com/projects/../locations/....
However, I allowed the users to only provide the Id, so customers can just provide each reference on the format of projects/../locations/../certficates/.., and I construct the full URL before sending the API request using the custom_expand function.
So, we end up having the following:

  • user input -> projects/../locations/../certificates/..
  • API response -> //certificatemanager.googleapis.com/projects/../locations/.../..certificates/..

When I run the test, TF triggers an update request(because the field value has changed) and that causes the test to fail.

Is there a better way to handle this situation?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

One more question, Are there any issues with allowing the user to provide the id and then convert it to a full URL before sending the request?

According to rileykarson's comment here #8941 (comment), it's not encouraged to let the user enter the name of the resource unless the API allows doing this, I wonder if it's also the same with letting the user provide an id if the API is expecting a full URL format.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, I'm talking about the diff_suppress_func. I understand that you are allowing the user to provide an id (which I believe is fine here), and that needs to be converted before being sent to the API, but isn't this all being handled by the expand/encoder/decoder?

I may just be missing something, but I'm wondering what caused the test failure. And for context, I'm partly asking about the diff suppress because I believe the implementation doesn't consider all parts of the id (like location), and that may cause problems.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

1- The encoder and the decoder parts are responsible for merging or splitting the fields sslCertificates and certificate_manager_certificates before constructing the API request and after receiving the response respectively. They have nothing to do with the format of the input provided by the user.

2- The custom expand is responsible for making sure that any certificate manager certificate resource is sent in the API request in the format of //certificatemanager.googleapis.com/projects/../locations/.../..certificates/... So, if the user uses the id to reference the certificate, the custom expand will convert it before sending the API request.

The response that we receive from the API will contain the certificates in the full URL format (//certificatemanager.googleapis.com/projects/../locations/.../..certificates/..). Hence if the user provides only the id, there will be a difference between the input provided by the user and the response from the API.

Error Message:

2023-10-06T18:46:25.436Z [ERROR] sdk.helper_resource: Unexpected error:
  error=
  | After applying this test step, the plan was not empty.
  | stdout:
  | 
  | 
  | Terraform used the selected providers to generate the following execution
  | plan. Resource actions are indicated with the following symbols:
  |   ~ update in-place
  | 
  | Terraform will perform the following actions:
  | 
  |   # google_compute_target_https_proxy.default will be updated in-place
  |   ~ resource "google_compute_target_https_proxy" "default" {
  |       ~ certificate_manager_certificates = [
  |           - "//certificatemanager.googleapis.com/projects/hamzahassan/locations/global/certificates/tf-test-my-certificate4di3je7hnx",
  |           + "projects/hamzahassan/locations/global/certificates/tf-test-my-certificate4di3je7hnx",
  |         ]
  |         id                               = "projects/hamzahassan/global/targetHttpsProxies/tf-test-target-http-proxy4di3je7hnx"
  |         name                             = "tf-test-target-http-proxy4di3je7hnx"
  |         # (8 unchanged attributes hidden)
  |     }
  | 
  | Plan: 0 to add, 1 to change, 0 to destroy.
  • This error only happens if the user provides id to reference a certificate resource

Copy link
Contributor

Choose a reason for hiding this comment

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

Got it, that all makes sense, thanks for clarifying. Despite my concern with the other parts of the id diffing (like location and project), it appears this same function is used in many other fields with similar structure, so seems good to me.

conflicts:
- ssl_certificates
- !ruby/object:Api::Type::Array
name: 'sslCertificates'
description: |
A list of SslCertificate resource URLs or Certificate Manager certificate URLs that are used to authenticate
A list of SslCertificate resource URLs that are used to authenticate
connections between users and the load balancer. At least one resource must be specified.
update_verb: :POST
update_url: 'projects/{{project}}/targetHttpsProxies/{{name}}/setSslCertificates'
item_type: !ruby/object:Api::Type::ResourceRef
name: 'sslCertificate'
resource: 'SslCertificate'
imports: 'selfLink'
description: 'The SSL certificate URL or Certificate Manager certificate resource URL used by this TargetHttpsProxy'
description: 'The SSL certificate URL used by this TargetHttpsProxy'
custom_expand: 'templates/terraform/custom_expand/array_resourceref_with_validation.go.erb'
conflicts:
- certificate_manager_certificates
- !ruby/object:Api::Type::String
name: 'certificateMap'
description: |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<%# The license inside this block applies to this file.
# Copyright 2017 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.
-%>
func expand<%= prefix -%><%= titlelize_property(property) -%>(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) {
if v == nil {
return nil, nil
}
l := v.([]interface{})
req := make([]interface{}, 0, len(l))
for _, raw := range l {
if raw == nil {
return nil, fmt.Errorf("Invalid value for <%= property.name.underscore -%>: nil")
}
if strings.HasPrefix(raw.(string), "//") || strings.HasPrefix(raw.(string), "https://") {
// Any full URL will be passed to the API request (regardless of the resource type). This is to allow self_links of CertificateManagerCeritificate resources.
// If the full URL is an invalid reference, that should be handled by the API.
req = append(req, raw.(string))
} else if reg,_ := regexp.Compile("projects/(.*)/locations/(.*)/certificates/(.*)") ; reg.MatchString(raw.(string)) {
// If the input is the id pattern of CertificateManagerCertificate resource, a prefix will be added to construct the full URL before constructing the API request.
self_link := "https://certificatemanager.googleapis.com/v1/" + raw.(string)
req = append(req, self_link)
} else {
return nil, fmt.Errorf("Invalid value for <%= property.name.underscore -%>: %v is an invalid format for a certificateManagerCertificate resource", raw.(string))
}
}
return req, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Since both sslCertificates and certificateManagerCertificates maps to the same API field (sslCertificates), we need to check the types
// of certificates that exist in the array and decide whether to change the field to certificateManagerCertificate or not.
// The decoder logic depends on the fact that the API does not allow mixed type of certificates and it returns
// certificate manager certificates in the format of //certificatemanager.googleapis.com/projects/*/locations/*/certificates/*
if sslCertificates, ok := res["sslCertificates"].([]interface{}); ok && len(sslCertificates) > 0 {
regPat, _ := regexp.Compile("//certificatemanager.googleapis.com/projects/(.*)/locations/(.*)/certificates/(.*)")

if regPat.MatchString(sslCertificates[0].(string)) {
// It is enough to check only the type of one of the provided certificates beacuse all the certificates should be the same type.
log.Printf("[DEBUG] The field sslCertificates contains certificateManagerCertificates, the field name will be converted to certificateManagerCertificates")
res["certificateManagerCertificates"] = res["sslCertificates"]
delete(res, "sslCertificates")
}
}
return res, nil
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

if _, ok := obj["certificateManagerCertificates"]; ok {
// The field certificateManagerCertificates should not be included in the API request, and it should be renamed to `sslCertificates`
// The API does not allow using both certificate manager certificates and sslCertificates. If that changes
// in the future, the encoder logic should change accordingly because this will mean that both fields are no longer mutual exclusive.
log.Printf("[DEBUG] converting the field CertificateManagerCertificates to sslCertificates before sending the request")
obj["sslCertificates"] = obj["certificateManagerCertificates"]
delete(obj, "certificateManagerCertificates")
}
return obj, nil
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@

resource "google_compute_target_https_proxy" "<%= ctx[:primary_resource_id] %>" {
name = "<%= ctx[:vars]['target_https_proxy_name'] %>"
url_map = google_compute_url_map.default.id
certificate_manager_certificates = ["//certificatemanager.googleapis.com/${google_certificate_manager_certificate.default.id}"] # [google_certificate_manager_certificate.default.id] is also acceptable
}

resource "google_certificate_manager_certificate" "default" {
name = "<%= ctx[:vars]['certificate_manager_certificate_name'] %>"
scope = "ALL_REGIONS"
self_managed {
pem_certificate = file("test-fixtures/cert.pem")
pem_private_key = file("test-fixtures/private-key.pem")
}
}

resource "google_compute_url_map" "default" {
name = "<%= ctx[:vars]['url_map_name'] %>"
description = "a description"

default_service = google_compute_backend_service.default.id

host_rule {
hosts = ["mysite.com"]
path_matcher = "allpaths"
}

path_matcher {
name = "allpaths"
default_service = google_compute_backend_service.default.id

path_rule {
paths = ["/*"]
service = google_compute_backend_service.default.id
}
}
}

resource "google_compute_backend_service" "default" {
name = "<%= ctx[:vars]['backend_service_name'] %>"
port_name = "http"
protocol = "HTTP"
timeout_sec = 10
load_balancing_scheme = "INTERNAL_MANAGED"
}
19 changes: 19 additions & 0 deletions mmv1/third_party/terraform/services/compute/test-fixtures/cert.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDDzCCAfegAwIBAgIUDOiCLH9QNMMYnjPZVf4VwO9blsEwDQYJKoZIhvcNAQEL
BQAwFjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wIBcNMjIwODI0MDg0MDUxWhgPMzAy
MTEyMjUwODQwNTFaMBYxFDASBgNVBAMMC2V4YW1wbGUuY29tMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvOT925GG4lKV9HvAHsbecMhGPAqjhVRC26iZ
UJC8oSWOu95lWJSX5ZhbiF6Nz192wDGV/VAh3Lxj8RYtcn75eDxQKTcKouDld+To
CGIStPFWbR6rbysLuZqFVEXVOTvp2QIegInfrvnGC4j7Qpic7zrFB9HzJx+0HpeE
yO4gkdzJfEK/gMmolUgJrKX59o+0+Rj+Jq3EtcQxL1fVBVJSx0NvpoR1eYpnHMr/
rJKZkUUZ2xE86hrtpiP6OEYQTi00rmf4GnZF5QfGGD0xuoQXtR7Tu+XhKibXIhxc
D4RzPLX1QS040PXvmMPLDb4YlUQ6V3Rs42JDvkkDwIMXZvn8awIDAQABo1MwUTAd
BgNVHQ4EFgQURuo1CCZZAUv7xi02f2nC5tRbf18wHwYDVR0jBBgwFoAURuo1CCZZ
AUv7xi02f2nC5tRbf18wDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC
AQEAqx3tDxurnYr9EUPhF5/LlDPYM+VI7EgrKdRnuIqUlZI0tm3vOGME0te6dBTC
YLNaHLW3m/4Tm4M2eg0Kpz6CxJfn3109G31dCi0xwzSDHf5TPUWvqIVhq5WRgMIf
n8KYBlQSmqdJBRztUIQH/UPFnSbxymlS4s5qwDgTH5ag9EEBcnWsQ2LZjKi0eqve
MaqAvvB+j8RGZzYY4re94bSJI42zIZ6nMWPtXwRuDc30xl/u+E0jWIgWbPwSd6Km
3wnJnGiU2ezPGq3zEU+Rc39VVIFKQpciNeYuF3neHPJvYOf58qW2Z8s0VH0MR1x3
3DoO/e30FIr9j+PRD+s5BPKF2A==
-----END CERTIFICATE-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC85P3bkYbiUpX0
e8Aext5wyEY8CqOFVELbqJlQkLyhJY673mVYlJflmFuIXo3PX3bAMZX9UCHcvGPx
Fi1yfvl4PFApNwqi4OV35OgIYhK08VZtHqtvKwu5moVURdU5O+nZAh6Aid+u+cYL
iPtCmJzvOsUH0fMnH7Qel4TI7iCR3Ml8Qr+AyaiVSAmspfn2j7T5GP4mrcS1xDEv
V9UFUlLHQ2+mhHV5imccyv+skpmRRRnbETzqGu2mI/o4RhBOLTSuZ/gadkXlB8YY
PTG6hBe1HtO75eEqJtciHFwPhHM8tfVBLTjQ9e+Yw8sNvhiVRDpXdGzjYkO+SQPA
gxdm+fxrAgMBAAECggEAV4/A24TQpV4KFBw/WSTvnRFBeXinB1mhamhztWR6hCrA
SPcVPKQY632eRI8sJmpGxl3V/Ogl4khT/cA9jfstEl7G++v/WrRsupCaPLSVnlnX
KdsTNgOauk1WK9P5PMA4rPcuA4Cl91riQpubeWn8KWsxRWg90i+Ak8PB8lBsOaB1
QzjigWlrRWSpodaw0MBIMZFDL2BYK8HEr+wyATYIyGvDQc9zCnMQIQIZyEPYepLO
04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