Skip to content

googleAppEngineFlexibleAppVersion

Flexible App Version resource to create a new version of flexible GAE Application. Based on Google Compute Engine, the App Engine flexible environment automatically scales your app up and down while also balancing the load. Learn about the differences between the standard environment and the flexible environment at https://cloud.google.com/appengine/docs/the-appengine-environments.

\~> Note: The App Engine flexible environment service account uses the member ID service-[yourProjectNumber]@gaeApiProdGoogleComIamGserviceaccountCom It should have the App Engine Flexible Environment Service Agent role, which will be applied when the appengineflexGoogleapisCom service is enabled.

To get more information about FlexibleAppVersion, see:

Example Usage - App Engine Flexible App Version

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
const googleProjectMyProject = new google.project.Project(this, "my_project", {
  billing_account: "000000-0000000-0000000-000000",
  name: "appeng-flex",
  org_id: "123456789",
  project_id: "appeng-flex",
});
const googleProjectServiceService = new google.projectService.ProjectService(
  this,
  "service",
  {
    disable_dependent_services: false,
    project: googleProjectMyProject.projectId,
    service: "appengineflex.googleapis.com",
  }
);
const googleServiceAccountCustomServiceAccount =
  new google.serviceAccount.ServiceAccount(this, "custom_service_account", {
    account_id: "my-account",
    display_name: "Custom Service Account",
    project: googleProjectServiceService.project,
  });
const googleStorageBucketBucket = new google.storageBucket.StorageBucket(
  this,
  "bucket",
  {
    location: "US",
    name: "appengine-static-content",
    project: googleProjectMyProject.projectId,
  }
);
const googleStorageBucketObjectObject =
  new google.storageBucketObject.StorageBucketObject(this, "object", {
    bucket: googleStorageBucketBucket.name,
    name: "hello-world.zip",
    source: "./test-fixtures/appengine/hello-world.zip",
  });
new google.appEngineApplication.AppEngineApplication(this, "app", {
  location_id: "us-central",
  project: googleProjectMyProject.projectId,
});
const googleProjectIamMemberGaeApi =
  new google.projectIamMember.ProjectIamMember(this, "gae_api", {
    member: `serviceAccount:\${${googleServiceAccountCustomServiceAccount.email}}`,
    project: googleProjectServiceService.project,
    role: "roles/compute.networkUser",
  });
new google.projectIamMember.ProjectIamMember(this, "logs_writer", {
  member: `serviceAccount:\${${googleServiceAccountCustomServiceAccount.email}}`,
  project: googleProjectServiceService.project,
  role: "roles/logging.logWriter",
});
new google.projectIamMember.ProjectIamMember(this, "storage_viewer", {
  member: `serviceAccount:\${${googleServiceAccountCustomServiceAccount.email}}`,
  project: googleProjectServiceService.project,
  role: "roles/storage.objectViewer",
});
new google.appEngineFlexibleAppVersion.AppEngineFlexibleAppVersion(
  this,
  "myapp_v1",
  {
    automatic_scaling: [
      {
        cool_down_period: "120s",
        cpu_utilization: [
          {
            target_utilization: 0.5,
          },
        ],
      },
    ],
    deployment: [
      {
        zip: [
          {
            source_url: `https://storage.googleapis.com/\${${googleStorageBucketBucket.name}}/\${${googleStorageBucketObjectObject.name}}`,
          },
        ],
      },
    ],
    entrypoint: [
      {
        shell: "node ./app.js",
      },
    ],
    env_variables: [
      {
        port: "8080",
      },
    ],
    handlers: [
      {
        auth_fail_action: "AUTH_FAIL_ACTION_REDIRECT",
        login: "LOGIN_REQUIRED",
        security_level: "SECURE_ALWAYS",
        static_files: [
          {
            path: "my-other-path",
            upload_path_regex: ".*\\/my-path\\/*",
          },
        ],
        url_regex: ".*\\/my-path\\/*",
      },
    ],
    liveness_check: [
      {
        path: "/",
      },
    ],
    noop_on_destroy: true,
    project: googleProjectIamMemberGaeApi.project,
    readiness_check: [
      {
        path: "/",
      },
    ],
    runtime: "nodejs",
    service: "default",
    service_account: googleServiceAccountCustomServiceAccount.email,
    version_id: "v1",
  }
);

Argument Reference

The following arguments are supported:

  • runtime - (Required) Desired runtime. Example python27.

  • readinessCheck - (Required) Configures readiness health checking for instances. Unhealthy instances are not put into the backend traffic rotation. Structure is documented below.

  • livenessCheck - (Required) Health checking configuration for VM instances. Unhealthy instances are killed and replaced with new instances. Structure is documented below.

  • service - (Required) AppEngine service resource. Can contain numbers, letters, and hyphens.

The readinessCheck block supports:

  • path - (Required) The request path.

  • host - (Optional) Host header to send when performing a HTTP Readiness check. Example: "myapp.appspot.com"

  • failureThreshold - (Optional) Number of consecutive failed checks required before removing traffic. Default: 2.

  • successThreshold - (Optional) Number of consecutive successful checks required before receiving traffic. Default: 2.

  • checkInterval - (Optional) Interval between health checks. Default: "5s".

  • timeout - (Optional) Time before the check is considered failed. Default: "4s"

  • appStartTimeout - (Optional) A maximum time limit on application initialization, measured from moment the application successfully replies to a healthcheck until it is ready to serve traffic. Default: "300s"

The livenessCheck block supports:

  • path - (Required) The request path.

  • host - (Optional) Host header to send when performing a HTTP Readiness check. Example: "myapp.appspot.com"

  • failureThreshold - (Optional) Number of consecutive failed checks required before considering the VM unhealthy. Default: 4.

  • successThreshold - (Optional) Number of consecutive successful checks required before considering the VM healthy. Default: 2.

  • checkInterval - (Optional) Interval between health checks.

  • timeout - (Optional) Time before the check is considered failed. Default: "4s"

  • initialDelay - (Optional) The initial delay before starting to execute the checks. Default: "300s"


  • versionId - (Optional) Relative name of the version within the service. For example, v1. Version names can contain only lowercase letters, numbers, or hyphens. Reserved names,"default", "latest", and any name with the prefix "ah-".

  • inboundServices - (Optional) A list of the types of messages that this application is able to receive. Each value may be one of inboundServiceMail, inboundServiceMailBounce, inboundServiceXmppError, inboundServiceXmppMessage, inboundServiceXmppSubscribe, inboundServiceXmppPresence, inboundServiceChannelPresence, and inboundServiceWarmup.

  • instanceClass - (Optional) Instance class that is used to run this version. Valid values are AutomaticScaling: F1, F2, F4, F4_1G ManualScaling: B1, B2, B4, B8, B4_1G Defaults to F1 for AutomaticScaling and B1 for ManualScaling.

  • network - (Optional) Extra network settings Structure is documented below.

  • resources - (Optional) Machine resources for a version. Structure is documented below.

  • runtimeChannel - (Optional) The channel of the runtime to use. Only available for some runtimes.

  • betaSettings - (Optional) Metadata settings that are supplied to this version to enable beta runtime features.

  • servingStatus - (Optional) Current serving status of this version. Only the versions with a SERVING status create instances and can be billed. Default value is serving. Possible values are serving and stopped.

  • runtimeApiVersion - (Optional) The version of the API in the given runtime environment. Please see the app.yaml reference for valid values at https://cloudGoogleCom/appengine/docs/standard/<language>/config/appref\ Substitute <language> with python, java, php, ruby, go or nodejs.

  • handlers - (Optional) An ordered list of URL-matching patterns that should be applied to incoming requests. The first matching URL handles the request and other request handlers are not attempted. Structure is documented below.

  • runtimeMainExecutablePath - (Optional) The path or name of the app's main executable.

  • serviceAccount - (Optional) The identity that the deployed version will run as. Admin API will use the App Engine Appspot service account as default if this field is neither provided in app.yaml file nor through CLI flag.

  • apiConfig - (Optional) Serving configuration for Google Cloud Endpoints. Structure is documented below.

  • envVariables - (Optional) Environment variables available to the application. As these are not returned in the API request, Terraform will not detect any changes made outside of the Terraform config.

  • defaultExpiration - (Optional) Duration that static files should be cached by web proxies and browsers. Only applicable if the corresponding StaticFilesHandler does not specify its own expiration time.

  • nobuildFilesRegex - (Optional) Files that match this pattern will not be built into this version. Only applicable for Go runtimes.

  • deployment - (Optional) Code and application artifacts that make up this version. Structure is documented below.

  • endpointsApiService - (Optional) Code and application artifacts that make up this version. Structure is documented below.

  • entrypoint - (Optional) The entrypoint for the application. Structure is documented below.

  • vpcAccessConnector - (Optional) Enables VPC connectivity for standard apps. Structure is documented below.

  • automaticScaling - (Optional) Automatic scaling is based on request rate, response latencies, and other application metrics. Structure is documented below.

  • manualScaling - (Optional) A service with manual scaling runs continuously, allowing you to perform complex initialization and rely on the state of its memory over time. Structure is documented below.

  • project - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used.

  • noopOnDestroy - (Optional) If set to true, the application version will not be deleted.

  • deleteServiceOnDestroy - (Optional) If set to true, the service will be deleted if it is the last version.

The network block supports:

  • forwardedPorts - (Optional) List of ports, or port pairs, to forward from the virtual machine to the application container.

  • instanceTag - (Optional) Tag to apply to the instance during creation.

  • name - (Required) Google Compute Engine network where the virtual machines are created. Specify the short name, not the resource path.

  • subnetwork - (Optional) Google Cloud Platform sub-network where the virtual machines are created. Specify the short name, not the resource path. If the network that the instance is being created in is a Legacy network, then the IP address is allocated from the IPv4Range. If the network that the instance is being created in is an auto Subnet Mode Network, then only network name should be specified (not the subnetworkName) and the IP address is created from the IPCidrRange of the subnetwork that exists in that zone for that network. If the network that the instance is being created in is a custom Subnet Mode Network, then the subnetworkName must be specified and the IP address is created from the IPCidrRange of the subnetwork. If specified, the subnetwork must exist in the same region as the App Engine flexible environment application.

  • sessionAffinity - (Optional) Enable session affinity.

The resources block supports:

  • cpu - (Optional) Number of CPU cores needed.

  • diskGb - (Optional) Disk size (GB) needed.

  • memoryGb - (Optional) Memory (GB) needed.

  • volumes - (Optional) List of ports, or port pairs, to forward from the virtual machine to the application container. Structure is documented below.

The volumes block supports:

  • name - (Required) Unique name for the volume.

  • volumeType - (Required) Underlying volume type, e.g. 'tmpfs'.

  • sizeGb - (Required) Volume size in gigabytes.

The handlers block supports:

  • urlRegex - (Optional) URL prefix. Uses regular expression syntax, which means regexp special characters must be escaped, but should not contain groupings. All URLs that begin with this prefix are handled by this handler, using the portion of the URL after the prefix as part of the file path.

  • securityLevel - (Optional) Security (HTTPS) enforcement for this URL. Possible values are secureDefault, secureNever, secureOptional, and secureAlways.

  • login - (Optional) Methods to restrict access to a URL based on login status. Possible values are loginOptional, loginAdmin, and loginRequired.

  • authFailAction - (Optional) Actions to take when the user is not logged in. Possible values are authFailActionRedirect and authFailActionUnauthorized.

  • redirectHttpResponseCode - (Optional) 30x code to use when performing redirects for the secure field. Possible values are redirectHttpResponseCode301, redirectHttpResponseCode302, redirectHttpResponseCode303, and redirectHttpResponseCode307.

  • script - (Optional) Executes a script to handle the requests that match this URL pattern. Only the auto value is supported for Node.js in the App Engine standard environment, for example "script:" "auto". Structure is documented below.

  • staticFiles - (Optional) Files served directly to the user for a given URL, such as images, CSS stylesheets, or JavaScript source files. Static file handlers describe which files in the application directory are static files, and which URLs serve them. Structure is documented below.

The script block supports:

  • scriptPath - (Required) Path to the script from the application root directory.

The staticFiles block supports:

  • path - (Optional) Path to the static files matched by the URL pattern, from the application root directory. The path can refer to text matched in groupings in the URL pattern.

  • uploadPathRegex - (Optional) Regular expression that matches the file paths for all files that should be referenced by this handler.

  • httpHeaders - (Optional) HTTP headers to use for all responses from these URLs. An object containing a list of "key:value" value pairs.".

  • mimeType - (Optional) MIME type used to serve all files served by this handler. Defaults to file-specific MIME types, which are derived from each file's filename extension.

  • expiration - (Optional) Time a static file served by this handler should be cached by web proxies and browsers. A duration in seconds with up to nine fractional digits, terminated by 's'. Example "3.5s". Default is '0s'

  • requireMatchingFile - (Optional) Whether this handler should match the request if the file referenced by the handler does not exist.

  • applicationReadable - (Optional) Whether files should also be uploaded as code data. By default, files declared in static file handlers are uploaded as static data and are only served to end users; they cannot be read by the application. If enabled, uploads are charged against both your code and static data storage resource quotas.

The apiConfig block supports:

  • authFailAction - (Optional) Action to take when users access resources that require authentication. Default value is authFailActionRedirect. Possible values are authFailActionRedirect and authFailActionUnauthorized.

  • login - (Optional) Level of login required to access this resource. Default value is loginOptional. Possible values are loginOptional, loginAdmin, and loginRequired.

  • script - (Required) Path to the script from the application root directory.

  • securityLevel - (Optional) Security (HTTPS) enforcement for this URL. Possible values are secureDefault, secureNever, secureOptional, and secureAlways.

  • url - (Optional) URL to serve the endpoint at.

The deployment block supports:

  • zip - (Optional) Zip File Structure is documented below.

  • files - (Optional) Manifest of the files stored in Google Cloud Storage that are included as part of this version. All files must be readable using the credentials supplied with this call. Structure is documented below.

  • container - (Optional) The Docker image for the container that runs the version. Structure is documented below.

  • cloudBuildOptions - (Optional) Options for the build operations performed as a part of the version deployment. Only applicable when creating a version using source code directly. Structure is documented below.

The zip block supports:

  • sourceUrl - (Required) Source URL

  • filesCount - (Optional) files count

The files block supports:

  • name - (Required) The identifier for this object. Format specified above.

  • sha1Sum - (Optional) SHA1 checksum of the file

  • sourceUrl - (Required) Source URL

The container block supports:

  • image - (Required) URI to the hosted container image in Google Container Registry. The URI must be fully qualified and include a tag or digest. Examples: "gcr.io/my-project/image:tag" or "gcr.io/my-project/image@digest"

The cloudBuildOptions block supports:

  • appYamlPath - (Required) Path to the yaml file used in deployment, used to determine runtime configuration details.

  • cloudBuildTimeout - (Optional) The Cloud Build timeout used as part of any dependent builds performed by version creation. Defaults to 10 minutes. A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".

The endpointsApiService block supports:

  • name - (Required) Endpoints service name which is the name of the "service" resource in the Service Management API. For example "myapi.endpoints.myproject.cloud.goog"

  • configId - (Optional) Endpoints service configuration ID as specified by the Service Management API. For example "2016-09-19r1". By default, the rollout strategy for Endpoints is "FIXED". This means that Endpoints starts up with a particular configuration ID. When a new configuration is rolled out, Endpoints must be given the new configuration ID. The configId field is used to give the configuration ID and is required in this case. Endpoints also has a rollout strategy called "MANAGED". When using this, Endpoints fetches the latest configuration and does not need the configuration ID. In this case, configId must be omitted.

  • rolloutStrategy - (Optional) Endpoints rollout strategy. If FIXED, configId must be specified. If MANAGED, configId must be omitted. Default value is fixed. Possible values are fixed and managed.

  • disableTraceSampling - (Optional) Enable or disable trace sampling. By default, this is set to false for enabled.

The entrypoint block supports:

  • shell - (Required) The format should be a shell command that can be fed to bash -c.

The vpcAccessConnector block supports:

  • name - (Required) Full Serverless VPC Access Connector name e.g. /projects/my-project/locations/us-central1/connectors/c1.

The automaticScaling block supports:

  • coolDownPeriod - (Optional) The time period that the Autoscaler should wait before it starts collecting information from a new instance. This prevents the autoscaler from collecting information when the instance is initializing, during which the collected usage would not be reliable. Default: 120s

  • cpuUtilization - (Required) Target scaling by CPU usage. Structure is documented below.

  • maxConcurrentRequests - (Optional) Number of concurrent requests an automatic scaling instance can accept before the scheduler spawns a new instance. Defaults to a runtime-specific value.

  • maxIdleInstances - (Optional) Maximum number of idle instances that should be maintained for this version.

  • maxTotalInstances - (Optional) Maximum number of instances that should be started to handle requests for this version. Default: 20

  • maxPendingLatency - (Optional) Maximum amount of time that a request should wait in the pending queue before starting a new instance to handle it.

  • minIdleInstances - (Optional) Minimum number of idle instances that should be maintained for this version. Only applicable for the default version of a service.

  • minTotalInstances - (Optional) Minimum number of running instances that should be maintained for this version. Default: 2

  • minPendingLatency - (Optional) Minimum amount of time a request should wait in the pending queue before starting a new instance to handle it.

  • requestUtilization - (Optional) Target scaling by request utilization. Structure is documented below.

  • diskUtilization - (Optional) Target scaling by disk usage. Structure is documented below.

  • networkUtilization - (Optional) Target scaling by network usage. Structure is documented below.

The cpuUtilization block supports:

  • aggregationWindowLength - (Optional) Period of time over which CPU utilization is calculated.

  • targetUtilization - (Required) Target CPU utilization ratio to maintain when scaling. Must be between 0 and 1.

The requestUtilization block supports:

  • targetRequestCountPerSecond - (Optional) Target requests per second.

  • targetConcurrentRequests - (Optional) Target number of concurrent requests.

The diskUtilization block supports:

  • targetWriteBytesPerSecond - (Optional) Target bytes written per second.

  • targetWriteOpsPerSecond - (Optional) Target ops written per second.

  • targetReadBytesPerSecond - (Optional) Target bytes read per second.

  • targetReadOpsPerSecond - (Optional) Target ops read per seconds.

The networkUtilization block supports:

  • targetSentBytesPerSecond - (Optional) Target bytes sent per second.

  • targetSentPacketsPerSecond - (Optional) Target packets sent per second.

  • targetReceivedBytesPerSecond - (Optional) Target bytes received per second.

  • targetReceivedPacketsPerSecond - (Optional) Target packets received per second.

The manualScaling block supports:

  • instances - (Required) Number of instances to assign to the service at the start. Note: When managing the number of instances at runtime through the App Engine Admin API or the (now deprecated) Python 2 Modules API set_num_instances() you must use lifecycleIgnoreChanges = ["manualScaling"[0]Instances] to prevent drift detection.

Attributes Reference

In addition to the arguments listed above, the following computed attributes are exported:

  • id - an identifier for the resource with format apps/{{project}}/services/{{service}}/versions/{{versionId}}

  • name - Full path to the Version resource in the API. Example, "v1".

Timeouts

This resource provides the following Timeouts configuration options:

  • create - Default is 20 minutes.
  • update - Default is 20 minutes.
  • delete - Default is 20 minutes.

Import

FlexibleAppVersion can be imported using any of these accepted formats:

$ terraform import google_app_engine_flexible_app_version.default apps/{{project}}/services/{{service}}/versions/{{version_id}}
$ terraform import google_app_engine_flexible_app_version.default {{project}}/{{service}}/{{version_id}}
$ terraform import google_app_engine_flexible_app_version.default {{service}}/{{version_id}}

User Project Overrides

This resource supports User Project Overrides.