Google Compute Engine Backend Service
This page shows how to write Terraform for Compute Engine Backend Service and write them securely.
google_compute_backend_service (Terraform)
The Backend Service in Compute Engine can be configured in Terraform with the resource name google_compute_backend_service. The following sections describe 2 examples of how to use the resource and its parameters.
Example Usage from GitHub
resource "google_compute_backend_service" "gcp_website_api" {
name = "instance-backend-api"
description = "regional instance backend"
protocol = "HTTP"
port_name = "http"
#timeout_sec = 30
resource "google_compute_backend_service" "www-service" {
name = "tf-www-service"
protocol = "HTTP"
backend {
group = google_compute_instance_group.www-resources.self_link
Parameters
-
affinity_cookie_ttl_secoptional - number
Lifetime of cookies in seconds if session_affinity is GENERATED_COOKIE. If set to 0, the cookie is non-persistent and lasts only until the end of the browser session (or equivalent). The maximum allowed value for TTL is one day. When the load balancing scheme is INTERNAL, this field is not used.
-
connection_draining_timeout_secoptional - number
Time for which instance will be drained (not accept new connections, but still work to finish started).
-
creation_timestampoptional computed - string
Creation timestamp in RFC3339 text format.
-
custom_request_headersoptional - set of string
Headers that the HTTP/S load balancer should add to proxied requests.
-
descriptionoptional - string
An optional description of this resource.
-
enable_cdnoptional - bool
If true, enable Cloud CDN for this BackendService.
-
fingerprintoptional computed - string
Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking.
-
health_checksoptional - set of string
The set of URLs to the HttpHealthCheck or HttpsHealthCheck resource for health checking this BackendService. Currently at most one health check can be specified. A health check must be specified unless the backend service uses an internet or serverless NEG as a backend. For internal load balancing, a URL to a HealthCheck resource must be specified instead.
-
idoptional computed - string -
load_balancing_schemeoptional - string
Indicates whether the backend service will be used with internal or external load balancing. A backend service created for one type of load balancing cannot be used with the other. Default value: "EXTERNAL" Possible values: ["EXTERNAL", "INTERNAL_SELF_MANAGED"]
-
locality_lb_policyoptional - string
The load balancing algorithm used within the scope of the locality. The possible values are - ROUND_ROBIN - This is a simple policy in which each healthy backend is selected in round robin order. LEASTREQUEST - An O(1) algorithm which selects two random healthy hosts and picks the host which has fewer active requests. RINGHASH - The ring/modulo hash load balancer implements consistent hashing to backends. The algorithm has the property that the addition/removal of a host from a set of N hosts only affects 1/N of the requests. RANDOM - The load balancer selects a random healthy host. ORIGINAL_DESTINATION - Backend host is selected based on the client connection metadata, i.e., connections are opened to the same address as the destination address of the incoming connection before the connection was redirected to the load balancer. MAGLEV - used as a drop in replacement for the ring hash load balancer. Maglev is not as stable as ring hash but has faster table lookup build times and host selection times. For more information about Maglev, refer to https://ai.google/research/pubs/pub44824 This field is applicable only when the load_balancing_scheme is set to INTERNAL_SELF_MANAGED. Possible values: ["ROUND_ROBIN", "LEAST_REQUEST", "RING_HASH", "RANDOM", "ORIGINAL_DESTINATION", "MAGLEV"]
-
namerequired - string
Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression 'a-z?' which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.
-
port_nameoptional computed - string
Name of backend port. The same name should appear in the instance groups referenced by this service. Required when the load balancing scheme is EXTERNAL.
The protocol this BackendService uses to communicate with backends. The default is HTTP. NOTE: HTTP2 is only valid for beta HTTP/2 load balancer types and may result in errors if used with the GA API. Possible values: ["HTTP", "HTTPS", "HTTP2", "TCP", "SSL", "GRPC"]
-
security_policyoptional - string
The security policy associated with this backend service.
-
self_linkoptional computed - string -
session_affinityoptional computed - string
Type of session affinity to use. The default is NONE. Session affinity is not applicable if the protocol is UDP. Possible values: ["NONE", "CLIENT_IP", "CLIENT_IP_PORT_PROTO", "CLIENT_IP_PROTO", "GENERATED_COOKIE", "HEADER_FIELD", "HTTP_COOKIE"]
-
timeout_secoptional computed - number
How many seconds to wait for the backend before considering it a failed request. Default is 30 seconds. Valid range is [1, 86400].
-
backendset block-
balancing_modeoptional - string
Specifies the balancing mode for this backend. For global HTTP(S) or TCP/SSL load balancing, the default is UTILIZATION. Valid values are UTILIZATION, RATE (for HTTP(S)) and CONNECTION (for TCP/SSL). Default value: "UTILIZATION" Possible values: ["UTILIZATION", "RATE", "CONNECTION"]
-
capacity_scaleroptional - number
A multiplier applied to the group's maximum servicing capacity (based on UTILIZATION, RATE or CONNECTION). Default value is 1, which means the group will serve up to 100% of its configured capacity (depending on balancingMode). A setting of 0 means the group is completely drained, offering 0% of its available Capacity. Valid range is [0.0,1.0].
-
descriptionoptional - string
An optional description of this resource. Provide this property when you create the resource.
-
grouprequired - string
The fully-qualified URL of an Instance Group or Network Endpoint Group resource. In case of instance group this defines the list of instances that serve traffic. Member virtual machine instances from each instance group must live in the same zone as the instance group itself. No two backends in a backend service are allowed to use same Instance Group resource. For Network Endpoint Groups this defines list of endpoints. All endpoints of Network Endpoint Group must be hosted on instances located in the same zone as the Network Endpoint Group. Backend services cannot mix Instance Group and Network Endpoint Group backends. Note that you must specify an Instance Group or Network Endpoint Group resource using the fully-qualified URL, rather than a partial URL.
-
max_connectionsoptional - number
The max number of simultaneous connections for the group. Can be used with either CONNECTION or UTILIZATION balancing modes. For CONNECTION mode, either maxConnections or one of maxConnectionsPerInstance or maxConnectionsPerEndpoint, as appropriate for group type, must be set.
-
max_connections_per_endpointoptional - number
The max number of simultaneous connections that a single backend network endpoint can handle. This is used to calculate the capacity of the group. Can be used in either CONNECTION or UTILIZATION balancing modes. For CONNECTION mode, either maxConnections or maxConnectionsPerEndpoint must be set.
-
max_connections_per_instanceoptional - number
The max number of simultaneous connections that a single backend instance can handle. This is used to calculate the capacity of the group. Can be used in either CONNECTION or UTILIZATION balancing modes. For CONNECTION mode, either maxConnections or maxConnectionsPerInstance must be set.
-
max_rateoptional - number
The max requests per second (RPS) of the group. Can be used with either RATE or UTILIZATION balancing modes, but required if RATE mode. For RATE mode, either maxRate or one of maxRatePerInstance or maxRatePerEndpoint, as appropriate for group type, must be set.
-
max_rate_per_endpointoptional - number
The max requests per second (RPS) that a single backend network endpoint can handle. This is used to calculate the capacity of the group. Can be used in either balancing mode. For RATE mode, either maxRate or maxRatePerEndpoint must be set.
-
max_rate_per_instanceoptional - number
The max requests per second (RPS) that a single backend instance can handle. This is used to calculate the capacity of the group. Can be used in either balancing mode. For RATE mode, either maxRate or maxRatePerInstance must be set.
-
max_utilizationoptional - number
Used when balancingMode is UTILIZATION. This ratio defines the CPU utilization target for the group. The default is 0.8. Valid range is [0.0, 1.0].
-
-
cdn_policylist block-
signed_url_cache_max_age_secoptional - number
Maximum number of seconds the response to a signed URL request will be considered fresh, defaults to 1hr (3600s). After this time period, the response will be revalidated before being served. When serving responses to signed URL requests, Cloud CDN will internally behave as though all responses from this backend had a "Cache-Control: public, max-age=[TTL]" header, regardless of any existing Cache-Control header. The actual headers served in responses will not be altered.
-
cache_key_policylist block-
include_hostoptional - bool
If true requests to different hosts will be cached separately.
-
include_protocoloptional - bool
If true, http and https requests will be cached separately.
-
include_query_stringoptional - bool
If true, include query string parameters in the cache key according to query_string_whitelist and query_string_blacklist. If neither is set, the entire query string will be included. If false, the query string will be excluded from the cache key entirely.
-
query_string_blacklistoptional - set of string
Names of query string parameters to exclude in cache keys. All other parameters will be included. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and '=' will be percent encoded and not treated as delimiters.
-
query_string_whitelistoptional - set of string
Names of query string parameters to include in cache keys. All other parameters will be excluded. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and '=' will be percent encoded and not treated as delimiters.
-
-
-
circuit_breakerslist block-
max_connectionsoptional - number
The maximum number of connections to the backend cluster. Defaults to 1024.
-
max_pending_requestsoptional - number
The maximum number of pending requests to the backend cluster. Defaults to 1024.
-
max_requestsoptional - number
The maximum number of parallel requests to the backend cluster. Defaults to 1024.
-
max_requests_per_connectionoptional - number
Maximum requests for a single backend connection. This parameter is respected by both the HTTP/1.1 and HTTP/2 implementations. If not specified, there is no limit. Setting this parameter to 1 will effectively disable keep alive.
-
max_retriesoptional - number
The maximum number of parallel retries to the backend cluster. Defaults to 3.
-
-
consistent_hashlist block-
http_header_nameoptional - string
The hash based on the value of the specified header field. This field is applicable if the sessionAffinity is set to HEADER_FIELD.
-
minimum_ring_sizeoptional - number
The minimum number of virtual nodes to use for the hash ring. Larger ring sizes result in more granular load distributions. If the number of hosts in the load balancing pool is larger than the ring size, each host will be assigned a single virtual node. Defaults to 1024.
-
http_cookielist block-
nameoptional - string
Name of the cookie.
-
pathoptional - string
Path to set for the cookie.
-
ttllist block-
nanosoptional - number
Span of time that's a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 seconds field and a positive nanos field. Must be from 0 to 999,999,999 inclusive.
-
secondsrequired - number
Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive.
-
-
-
-
iaplist block-
oauth2_client_idrequired - string
OAuth2 Client ID for IAP
-
oauth2_client_secretrequired - string
OAuth2 Client Secret for IAP
-
oauth2_client_secret_sha256optional computed - string
OAuth2 Client Secret SHA-256 for IAP
-
-
log_configlist block-
enableoptional - bool
Whether to enable logging for the load balancer traffic served by this backend service.
-
sample_rateoptional - number
This field can only be specified if logging is enabled for this backend service. The value of the field must be in [0, 1]. This configures the sampling rate of requests to the load balancer where 1.0 means all logged requests are reported and 0.0 means no logged requests are reported. The default value is 1.0.
-
-
outlier_detectionlist block-
consecutive_errorsoptional - number
Number of errors before a host is ejected from the connection pool. When the backend host is accessed over HTTP, a 5xx return code qualifies as an error. Defaults to 5.
-
consecutive_gateway_failureoptional - number
The number of consecutive gateway failures (502, 503, 504 status or connection errors that are mapped to one of those status codes) before a consecutive gateway failure ejection occurs. Defaults to 5.
-
enforcing_consecutive_errorsoptional - number
The percentage chance that a host will be actually ejected when an outlier status is detected through consecutive 5xx. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 100.
-
enforcing_consecutive_gateway_failureoptional - number
The percentage chance that a host will be actually ejected when an outlier status is detected through consecutive gateway failures. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 0.
-
enforcing_success_rateoptional - number
The percentage chance that a host will be actually ejected when an outlier status is detected through success rate statistics. This setting can be used to disable ejection or to ramp it up slowly. Defaults to 100.
-
max_ejection_percentoptional - number
Maximum percentage of hosts in the load balancing pool for the backend service that can be ejected. Defaults to 10%.
-
success_rate_minimum_hostsoptional - number
The number of hosts in a cluster that must have enough request volume to detect success rate outliers. If the number of hosts is less than this setting, outlier detection via success rate statistics is not performed for any host in the cluster. Defaults to 5.
-
success_rate_request_volumeoptional - number
The minimum number of total requests that must be collected in one interval (as defined by the interval duration above) to include this host in success rate based outlier detection. If the volume is lower than this setting, outlier detection via success rate statistics is not performed for that host. Defaults to 100.
-
success_rate_stdev_factoroptional - number
This factor is used to determine the ejection threshold for success rate outlier ejection. The ejection threshold is the difference between the mean success rate, and the product of this factor and the standard deviation of the mean success rate: mean - (stdev * success_rate_stdev_factor). This factor is divided by a thousand to get a double. That is, if the desired factor is 1.9, the runtime value should be 1900. Defaults to 1900.
-
base_ejection_timelist block-
nanosoptional - number
Span of time that's a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 'seconds' field and a positive 'nanos' field. Must be from 0 to 999,999,999 inclusive.
-
secondsrequired - number
Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive.
-
-
intervallist block-
nanosoptional - number
Span of time that's a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0 'seconds' field and a positive 'nanos' field. Must be from 0 to 999,999,999 inclusive.
-
secondsrequired - number
Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive.
-
-
-
timeoutssingle block
Explanation in Terraform Registry
A Backend Service defines a group of virtual machines that will serve traffic for load balancing. This resource is a global backend service, appropriate for external load balancing or self-managed internal load balancing. For managed internal load balancing, use a regional backend service instead. Currently self-managed internal load balancing is only available in beta. To get more information about BackendService, see:
- API documentation
- How-to Guides
- Official Documentation
Warning: All arguments including
iap.oauth2_client_secretandiap.oauth2_client_secret_sha256will be stored in the raw state as plain-text. Read more about sensitive data in state.
Tips: Best Practices for The Other Google Compute Engine Resources
In addition to the google_compute_disk, Google Compute Engine has the other resources that should be configured for security reasons. Please check some examples of those resources and precautions.
google_compute_disk
Ensure the encryption key for your GCE disk is stored securely
It is better to store the encryption key for your GCE disk securely. Secret Manager could be used instead.
google_compute_firewall
Ensure your VPC firewall blocks unwanted outbound traffic
It is better to block unwanted outbound traffic not to expose resources in the VPC to unwanted attacks.
google_compute_instance
Ensure appropriate service account is assigned to your GCE instance
It is better to create a custom service account for the instance and assign it.
google_compute_project_metadata
Ensure OS login for your GCE instances is enabled at project level
It is better to enable OS login for your GCE instances. Enabling OS login ensures that SSH keys used to connect to instances are mapped with IAM users, allowing centralized and automated SSH key management.
google_compute_ssl_policy
Ensure to use modern TLS protocols
It's better to adopt TLS v1.2+ instead of outdated TLS protocols.
google_compute_subnetwork
Ensure VPC flow logging is enabled
It is better to enable VPC flow logging. VPC flow logging allows us to audit traffic in your network.
Frequently asked questions
What is Google Compute Engine Backend Service?
Google Compute Engine Backend Service is a resource for Compute Engine of Google Cloud Platform. Settings can be wrote in Terraform.
Where can I find the example code for the Google Compute Engine Backend Service?
For Terraform, the ravinayag/devops and xiaobingchan/safety-and-basic source code examples are useful. See the Terraform Example section for further details.