Skip to content

googleCloudfunctionsFunction

Creates a new Cloud Function. For more information see:

\~> Warning: As of November 1, 2019, newly created Functions are private-by-default and will require appropriate IAM permissions to be invoked. See below examples for how to set up the appropriate permissions, or view the Cloud Functions IAM resources for Cloud Functions.

Example Usage - Public Function

/*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 googleStorageBucketBucket = new google.storageBucket.StorageBucket(
  this,
  "bucket",
  {
    location: "US",
    name: "test-bucket",
  }
);
const googleStorageBucketObjectArchive =
  new google.storageBucketObject.StorageBucketObject(this, "archive", {
    bucket: googleStorageBucketBucket.name,
    name: "index.zip",
    source: "./path/to/zip/file/which/contains/code",
  });
const googleCloudfunctionsFunctionFunction =
  new google.cloudfunctionsFunction.CloudfunctionsFunction(this, "function", {
    available_memory_mb: 128,
    description: "My function",
    entry_point: "helloGET",
    name: "function-test",
    runtime: "nodejs16",
    source_archive_bucket: googleStorageBucketBucket.name,
    source_archive_object: googleStorageBucketObjectArchive.name,
    trigger_http: true,
  });
new google.cloudfunctionsFunctionIamMember.CloudfunctionsFunctionIamMember(
  this,
  "invoker",
  {
    cloud_function: googleCloudfunctionsFunctionFunction.name,
    member: "allUsers",
    project: googleCloudfunctionsFunctionFunction.project,
    region: googleCloudfunctionsFunctionFunction.region,
    role: "roles/cloudfunctions.invoker",
  }
);

Example Usage - Single User

/*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 googleStorageBucketBucket = new google.storageBucket.StorageBucket(
  this,
  "bucket",
  {
    location: "US",
    name: "test-bucket",
  }
);
const googleStorageBucketObjectArchive =
  new google.storageBucketObject.StorageBucketObject(this, "archive", {
    bucket: googleStorageBucketBucket.name,
    name: "index.zip",
    source: "./path/to/zip/file/which/contains/code",
  });
const googleCloudfunctionsFunctionFunction =
  new google.cloudfunctionsFunction.CloudfunctionsFunction(this, "function", {
    available_memory_mb: 128,
    description: "My function",
    entry_point: "helloGET",
    environment_variables: [
      {
        MY_ENV_VAR: "my-env-var-value",
      },
    ],
    https_trigger_security_level: "SECURE_ALWAYS",
    labels: [
      {
        "my-label": "my-label-value",
      },
    ],
    name: "function-test",
    runtime: "nodejs16",
    source_archive_bucket: googleStorageBucketBucket.name,
    source_archive_object: googleStorageBucketObjectArchive.name,
    timeout: 60,
    trigger_http: true,
  });
new google.cloudfunctionsFunctionIamMember.CloudfunctionsFunctionIamMember(
  this,
  "invoker",
  {
    cloud_function: googleCloudfunctionsFunctionFunction.name,
    member: "user:myFunctionInvoker@example.com",
    project: googleCloudfunctionsFunctionFunction.project,
    region: googleCloudfunctionsFunctionFunction.region,
    role: "roles/cloudfunctions.invoker",
  }
);

Argument Reference

The following arguments are supported:

  • name - (Required) A user-defined name of the function. Function names must be unique globally.

  • runtime - (Required) The runtime in which the function is going to run. Eg. "nodejs16", "python39", "dotnet3", "go116", "java11", "ruby30", "php74", etc. Check the official doc for the up-to-date list.


  • description - (Optional) Description of the function.

  • availableMemoryMb - (Optional) Memory (in MB), available to the function. Default value is 256. Possible values include 128, 256, 512, 1024, etc.

  • timeout - (Optional) Timeout (in seconds) for the function. Default value is 60 seconds. Cannot be more than 540 seconds.

  • entryPoint - (Optional) Name of the function that will be executed when the Google Cloud Function is triggered.

  • eventTrigger - (Optional) A source that fires events in response to a condition in another service. Structure is documented below. Cannot be used with triggerHttp.

  • triggerHttp - (Optional) Boolean variable. Any HTTP request (of a supported type) to the endpoint will trigger function execution. Supported HTTP request types are: POST, PUT, GET, DELETE, and OPTIONS. Endpoint is returned as httpsTriggerUrl. Cannot be used with eventTrigger.

  • httpsTriggerSecurityLevel - (Optional) The security level for the function. The following options are available:

    • secureAlways Requests for a URL that match this handler that do not use HTTPS are automatically redirected to the HTTPS URL with the same path. Query parameters are reserved for the redirect.
    • secureOptional Both HTTP and HTTPS requests with URLs that match the handler succeed without redirects. The application can examine the request to determine which protocol was used and respond accordingly.
  • ingressSettings - (Optional) String value that controls what traffic can reach the function. Allowed values are allowAll, allowInternalAndGclb and allowInternalOnly. Check ingress documentation to see the impact of each settings value. Changes to this field will recreate the cloud function.

  • labels - (Optional) A set of key/value label pairs to assign to the function. Label keys must follow the requirements at https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements.

  • serviceAccountEmail - (Optional) If provided, the self-provided service account to run the function with.

  • environmentVariables - (Optional) A set of key/value environment variable pairs to assign to the function.

  • buildEnvironmentVariables - (Optional) A set of key/value environment variable pairs available during build time.

  • vpcConnector - (Optional) The VPC Network Connector that this cloud function can connect to. It should be set up as fully-qualified URI. The format of this field is projects/*/locations/*/connectors/*.

  • vpcConnectorEgressSettings - (Optional) The egress settings for the connector, controlling what traffic is diverted through it. Allowed values are allTraffic and privateRangesOnly. Defaults to privateRangesOnly. If unset, this field preserves the previously set value.

  • sourceArchiveBucket - (Optional) The GCS bucket containing the zip archive which contains the function.

  • sourceArchiveObject - (Optional) The source archive object (file) in archive bucket.

  • sourceRepository - (Optional) Represents parameters related to source repository where a function is hosted. Cannot be set alongside sourceArchiveBucket or sourceArchiveObject. Structure is documented below. It must match the pattern projects/{project}/locations/{location}/repositories/{repository}.*

  • dockerRegistry - (Optional) Docker Registry to use for storing the function's Docker images. Allowed values are CONTAINER_REGISTRY (default) and ARTIFACT_REGISTRY.

  • dockerRepository - (Optional) User managed repository created in Artifact Registry optionally with a customer managed encryption key. If specified, deployments will use Artifact Registry. This is the repository to which the function docker image will be pushed after it is built by Cloud Build. If unspecified, Container Registry will be used by default, unless specified otherwise by other means.

  • kmsKeyName - (Optional) Resource name of a KMS crypto key (managed by the user) used to encrypt/decrypt function resources. It must match the pattern projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}. If specified, you must also provide an artifact registry repository using the dockerRepository field that was created with the same KMS crypto key. Before deploying, please complete all pre-requisites described in https://cloud.google.com/functions/docs/securing/cmek#granting_service_accounts_access_to_the_key

  • maxInstances - (Optional) The limit on the maximum number of function instances that may coexist at a given time.

  • minInstances - (Optional) The limit on the minimum number of function instances that may coexist at a given time.

  • secretEnvironmentVariables - (Optional) Secret environment variables configuration. Structure is documented below.

  • secretVolumes - (Optional) Secret volumes configuration. Structure is documented below.

The eventTrigger block supports:

  • eventType - (Required) The type of event to observe. For example: "googleStorageObjectFinalize". See the documentation on calling Cloud Functions for a full reference of accepted triggers.

  • resource - (Required) Required. The name or partial URI of the resource from which to observe events. For example, "myBucket" or "projects/myProject/topics/myTopic"

  • failurePolicy - (Optional) Specifies policy for failed executions. Structure is documented below.

The failurePolicy block supports:

  • retry - (Required) Whether the function should be retried on failure. Defaults to false.

The sourceRepository block supports:

  • url - (Required) The URL pointing to the hosted repository where the function is defined. There are supported Cloud Source Repository URLs in the following formats:

    • To refer to a specific commit: https://sourceDevelopersGoogleCom/projects/*/repos/*/revisions/*/paths/*
    • To refer to a moveable alias (branch): https://sourceDevelopersGoogleCom/projects/*/repos/*/moveableAliases/*/paths/*. To refer to HEAD, use the master moveable alias.
    • To refer to a specific fixed alias (tag): https://sourceDevelopersGoogleCom/projects/*/repos/*/fixedAliases/*/paths/*

The secretEnvironmentVariables block supports:

  • key - (Required) Name of the environment variable.

  • projectId - (Optional) Project identifier (due to a known limitation, only project number is supported by this field) of the project that contains the secret. If not set, it will be populated with the function's project, assuming that the secret exists in the same project as of the function.

  • secret - (Required) ID of the secret in secret manager (not the full resource name).

  • version - (Required) Version of the secret (version number or the string "latest"). It is recommended to use a numeric version for secret environment variables as any updates to the secret value is not reflected until new clones start.

The secretVolumes block supports:

  • mountPath - (Required) The path within the container to mount the secret volume. For example, setting the mount_path as "/etc/secrets" would mount the secret value files under the "/etc/secrets" directory. This directory will also be completely shadowed and unavailable to mount any other secrets. Recommended mount paths: "/etc/secrets" Restricted mount paths: "/cloudsql", "/dev/log", "/pod", "/proc", "/var/log".

  • projectId - (Optional) Project identifier (due to a known limitation, only project number is supported by this field) of the project that contains the secret. If not set, it will be populated with the function's project, assuming that the secret exists in the same project as of the function.

  • secret - (Required) ID of the secret in secret manager (not the full resource name).

  • versions - (Optional) List of secret versions to mount for this secret. If empty, the "latest" version of the secret will be made available in a file named after the secret under the mount point. Structure is documented below.

The versions block supports:

  • path - (Required) Relative path of the file under the mount path where the secret value for this version will be fetched and made available. For example, setting the mount_path as "/etc/secrets" and path as "/secret_foo" would mount the secret value file at "/etc/secrets/secret_foo".

  • version - (Required) Version of the secret (version number or the string "latest"). It is preferable to use "latest" version with secret volumes as secret value changes are reflected immediately.

Attributes Reference

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

  • id - an identifier for the resource with format {{name}}

  • httpsTriggerUrl - URL which triggers function execution. Returned only if triggerHttp is used.

  • sourceRepository0DeployedUrl - The URL pointing to the hosted repository where the function was defined at the time of deployment.

  • project - Project of the function. If it is not provided, the provider project is used.

  • region - Region of function. If it is not provided, the provider region is used.

Timeouts

This resource provides the following Timeouts configuration options: configuration options:

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

Import

Functions can be imported using the name or {{project}}/{{region}}/name, e.g.

$ terraform import google_cloudfunctions_function.default function-test
$ terraform import google_cloudfunctions_function.default {{project}}/{{region}}/function-test