Skip to content

A Terraform module to deploy and manage highly scalable, containerized applications in Google Cloud Run, a fully managed serverless platform in Google Cloud https://cloud.google.com/run

License

Notifications You must be signed in to change notification settings

mineiros-io/terraform-google-cloud-run

Repository files navigation

Build Status GitHub tag (latest SemVer) Terraform Version Google Provider Version Join Slack

terraform-google-cloud-run

A Terraform module for creating and managing Google Cloud Run with optional Custom Domain Mapping.

This module supports Terraform version 1 and is compatible with the Terraform Google Provider version 4.

This module is part of our Infrastructure as Code (IaC) framework that enables our users and customers to easily deploy and manage reusable, secure, and production-grade cloud infrastructure.

Module Features

This module implements the following Terraform resources

  • google_cloud_run_service
  • google_cloud_run_domain_mapping

and supports additional features of the following modules:

Getting Started

Most common usage of the module:

module "terraform-google-cloud-run" {
  source = "github.com/mineiros-io/terraform-google-cloud-run?ref=v0.2.1"

  name     = "example-name"
  location = "us-central1"

  template = {
    spec = {
      containers = [
        {
          image = "gcr.io/cloudrun/hello:latest"
        }
      ]
    }
  }
}

Module Argument Reference

See variables.tf and examples/ for details and use-cases.

Main Resource Configuration

  • name: (Required string)

    Name must be unique within a namespace, within a Cloud Run region. Is required when creating resources. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated.

  • location: (Required string)

    The location of the cloud run instance. eg us-central1.

  • project: (Optional string)

    The ID of the project in which the resource belongs. If it is not provided, the provider project is used.

  • autogenerate_revision_name: (Optional bool)

    If set to true, the revision name (template.metadata.name) will be omitted and autogenerated by Cloud Run. This cannot be set to true while template.metadata.name is also set. (For legacy support, if template.metadata.name is unset in state while this field is set to false, the revision name will still autogenerate.).

  • template: (Optional object(template))

    A template holds the latest specification for the Revision to be stamped out. The template references the container image, and may also include labels and annotations that should be attached to the Revision. To correlate a Revision, and/or to force a Revision to be created when the spec doesn't otherwise change, a nonce label may be provided in the template metadata.

    Default is {}.

    The template object accepts the following attributes:

    • metadata: (Optional object(metadata))

      Optional metadata for this Revision, including labels and annotations. Name will be generated by the Configuration. To set minimum instances for this revision, use the autoscaling.knative.dev/minScale annotation key. To set maximum instances for this revision, use the autoscaling.knative.dev/maxScale annotation key. To set Cloud SQL connections for the revision, use the run.googleapis.com/cloudsql-instances annotation key.

      Default is {}.

      The metadata object accepts the following attributes:

      • name: (Optional string)

        Name must be unique within a namespace, within a Cloud Run region. Is required when creating resources. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names

      • namespace: (Optional string)

        In Cloud Run the namespace must be equal to either the project ID or project number. It will default to the resource's project.

      • labels: (Optional map(string))

        Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and routes. More info: http://kubernetes.io/docs/user-guide/labels

      • annotations: (Optional map(string))

        Annotations is a key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. More info: http://kubernetes.io/docs/user-guide/annotations Note: The Cloud Run API may add additional annotations that were not provided in your config. If terraform plan shows a diff where a server-side annotation is added, you can add it to your config or apply the lifecycle.ignore_changes rule to the metadata.0.annotations field.

    • spec: (Required object(spec))

      RevisionSpec holds the desired state of the Revision (from the client).

      The spec object accepts the following attributes:

      • container_concurrency: (Optional number)

        ContainerConcurrency specifies the maximum allowed in-flight (concurrent) requests per container of the Revision. Values are:

        • 0 thread-safe, the system should manage the max concurrency. This is the default value.
        • 1 not-thread-safe. Single concurrency
        • 2-N thread-safe, max concurrency of N
      • timeout_seconds: (Optional number)

        TimeoutSeconds holds the max duration the instance is allowed for responding to a request.

      • service_account_name: (Optional string)

        Email address of the IAM service account associated with the revision of the service. The service account represents the identity of the running revision, and determines what permissions the revision has. If not provided, the revision will use the project's default service account.

      • containers: (Required list(container))

        Container defines the unit of execution for this Revision. In the context of a Revision, we disallow a number of the fields of this Container, including: name, ports, and volumeMounts. The runtime contract is documented here: https://github.com/knative/serving/blob/master/docs/runtime-contract.md

        Each container object in the list accepts the following attributes:

        • args: (Optional list(string))

          Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

        • image: (Required string)

          Docker image name. This is most often a reference to a container located in the container registry, such as gcr.io/cloudrun/helloMore info: https://kubernetes.io/docs/concepts/containers/images

        • command: (Optional list(string))

          Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell

        • env: (Optional object(env))

          List of environment variables to set in the container.

          Default is {}.

          The env object accepts the following attributes:

          • name: (Optional string)

            Name of the environment variable.

          • value: (Optional string)

            Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any route environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not.

          • value_from: (Optional object(value_from))

            Source for the environment variable's value. Only supports secret_key_ref.

            The value_from object accepts the following attributes:

            • secret_key_ref: (Required object(secret_key_ref))

              Selects a key (version) of a secret in Secret Manager.

              The secret_key_ref object accepts the following attributes:

              • key: (Optional string)

                A Cloud Secret Manager secret version. Must be "latest" for the latest version or an integer for a specific version.

              • name: (Optional string)

                The name of the secret in Cloud Secret Manager. By default, the secret is assumed to be in the same project. If the secret is in another project, you must define an alias. You set the in this field, and create an annotation with the following structure "run.googleapis.com/secrets" = ":projects//secrets/". If multiple alias definitions are needed, they must be separated by commas in the annotation field.

        • ports: (Optional list(port))

          List of open ports in the container. More Info: https://cloud.google.com/run/docs/reference/rest/v1/RevisionSpec#ContainerPort

          Default is [].

          Each port object in the list accepts the following attributes:

          • name: (Optional string)

            Name of the port.

          • protocol: (Optional string)

            Protocol used on port.

          • container_port: (Required number)

            Port number.

        • resources: (Optional object(resource))

          Compute Resources required by this container. Used to set values such as max memory More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#requests-and-limits

          Default is {}.

          The resource object accepts the following attributes:

  • traffic: (Optional list(traffic))

    A list of traffic specifies how to distribute traffic over a collection of Knative Revisions and Configurations Structure.

    Default is [].

    Each traffic object in the list accepts the following attributes:

    • revision_name: (Optional string)

      RevisionName of a specific revision to which to send this portion of traffic.

    • percent: (Required number)

      Percent specifies percent of the traffic to this Revision or Configuration.

    • latest_revision: (Optional bool)

      LatestRevision may be optionally provided to indicate that the latest ready Revision of the Configuration should be used for this traffic target. When provided LatestRevision must be true if RevisionName is empty; it must be false when RevisionName is non-empty.

  • metadata: (Optional object(metadata))

    Optional metadata for this Revision, including labels and annotations. Name will be generated by the Configuration. To set minimum instances for this revision, use the autoscaling.knative.dev/minScale annotation key. To set maximum instances for this revision, use the autoscaling.knative.dev/maxScale annotation key. To set Cloud SQL connections for the revision, use the run.googleapis.com/cloudsql-instances annotation key.

    Default is {}.

    The metadata object accepts the following attributes:

    • namespace: (Optional string)

      In Cloud Run the namespace must be equal to either the project ID or project number. It will default to the resource's project.

    • labels: (Optional map(string))

      Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and routes. More info: http://kubernetes.io/docs/user-guide/labels

    • generation: (Optional number)

      A sequence number representing a specific generation of the desired state.

    • resource_version: (Optional string)

      An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. They may only be valid for a particular resource or set of resources. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency

    • self_link: (Optional string)

      SelfLink is a URL representing this object.

    • uid: (Optional string)

      UID is a unique id generated by the server on successful creation of a resource and is not allowed to change on PUT operations. More info: http://kubernetes.io/docs/user-guide/identifiers#uids

    • annotations: (Optional map(string))

      Annotations is a key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. More info: http://kubernetes.io/docs/user-guide/annotations Note: The Cloud Run API may add additional annotations that were not provided in your config. If terraform plan shows a diff where a server-side annotation is added, you can add it to your config or apply the lifecycle.ignore_changes rule to the metadata.0.annotations field.

  • domain_mapping: (Optional object(domain_mapping))

    An Object that holds the state and status of a user's domain mapping.

    The domain_mapping object accepts the following attributes:

    • spec: (Optional object(spec))

      RevisionSpec holds the desired state of the Revision (from the client).

      Default is {}.

      The spec object accepts the following attributes:

      • force_override: (Optional bool)

        If set, the mapping will override any mapping set before this spec was set. It is recommended that the user leaves this empty to receive an error warning about a potential conflict and only set it once the respective UI has given such a warning.

      • certificate_mode: (Optional string)

        The mode of the certificate. Possible values are NONE and AUTOMATIC.

        Default is "AUTOMATIC".

    • metadata: (Optional object(metadata))

      Optional metadata for this Revision, including labels and annotations. Name will be generated by the Configuration. To set minimum instances for this revision, use the autoscaling.knative.dev/minScale annotation key. To set maximum instances for this revision, use the autoscaling.knative.dev/maxScale annotation key. To set Cloud SQL connections for the revision, use the run.googleapis.com/cloudsql-instances annotation key.

      Default is {}.

      The metadata object accepts the following attributes:

      • namespace: (Optional string)

        In Cloud Run the namespace must be equal to either the project ID or project number. It will default to the resource's project.

      • labels: (Optional map(string))

        Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and routes. More info: http://kubernetes.io/docs/user-guide/labels

      • generation: (Optional number)

        A sequence number representing a specific generation of the desired state.

      • resource_version: (Optional string)

        An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. They may only be valid for a particular resource or set of resources. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency

      • self_link: (Optional string)

        SelfLink is a URL representing this object.

      • uid: (Optional string)

        UID is a unique id generated by the server on successful creation of a resource and is not allowed to change on PUT operations. More info: http://kubernetes.io/docs/user-guide/identifiers#uids

      • annotations: (Optional map(string))

        Annotations is a key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. More info: http://kubernetes.io/docs/user-guide/annotations Note: The Cloud Run API may add additional annotations that were not provided in your config. If terraform plan shows a diff where a server-side annotation is added, you can add it to your config or apply the lifecycle.ignore_changes rule to the metadata.0.annotations field.

Extended Resource Configuration

  • iam: (Optional list(iam))

    A list of IAM access to apply to the created secret.

    Default is [].

    Each iam object in the list accepts the following attributes:

    • role: (Optional string)

      The role that should be applied. Note that custom roles must be of the format [projects|organizations]/{parent-name}/roles/{role-name}.

    • members: (Optional set(string))

      Identities that will be granted the privilege in role. Each entry can have one of the following values:

      • allUsers: A special identifier that represents anyone who is on the internet; with or without a Google account.
      • allAuthenticatedUsers: A special identifier that represents anyone who is authenticated with a Google account or a service account.
      • user:{emailid}: An email address that represents a specific Google account. For example, alice@gmail.com or joe@example.com.
      • serviceAccount:{emailid}: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
      • group:{emailid}: An email address that represents a Google group. For example, admins@example.com.
      • domain:{domain}: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
      • projectOwner:projectid: Owners of the given project. For example, projectOwner:my-example-project
      • projectEditor:projectid: Editors of the given project. For example, projectEditor:my-example-project
      • projectViewer:projectid: Viewers of the given project. For example, projectViewer:my-example-project
    • authoritative: (Optional bool)

      Whether to exclusively set (authoritative mode) or add (non-authoritative/additive mode) members to the role.

      Default is true.

  • policy_bindings: (Optional list(policy_binding))

    A list of IAM policy bindings.

    Example:

    policy_bindings = [{
      role    = "roles/viewer"
      members = ["user:member@example.com"]
    }]

    Each policy_binding object in the list accepts the following attributes:

    • role: (Required string)

      The role that should be applied.

    • members: (Optional set(string))

      Identities that will be granted the privilege in role.

      Default is var.members.

    • condition: (Optional object(condition))

      An IAM Condition for a given binding.

      Example:

      condition = {
        expression = "request.time < timestamp(\"2022-01-01T00:00:00Z\")"
        title      = "expires_after_2021_12_31"
      }

      The condition object accepts the following attributes:

      • expression: (Required string)

        Textual representation of an expression in Common Expression Language syntax.

      • title: (Required string)

        A title for the expression, i.e. a short string describing its purpose.

      • description: (Optional string)

        An optional description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI.

Module Configuration

  • module_enabled: (Optional bool)

    Specifies whether resources in the module will be created.

    Default is true.

  • module_timeouts: (Optional object(module_timeouts))

    A map of timeout objects that is keyed by Terraform resource name defining timeouts for create, update and delete Terraform operations.

    Supported resources are: google_cloud_run_service, google_cloud_run_domain_mapping

    Default is {}.

    Example:

    module_timeouts = {
      null_resource = {
        create = "4m"
        update = "4m"
        delete = "4m"
      }
    }

    The module_timeouts object accepts the following attributes:

    • create: (Optional string)

      Timeout for create operations.

      Default is "6m".

    • update: (Optional string)

      Timeout for update operations.

      Default is "15m".

    • delete: (Optional string)

      Timeout for delete operations.

      Default is "4m".

  • module_depends_on: (Optional list(dependency))

    A list of dependencies. Any object can be assigned to this list to define a hidden external dependency.

    Default is [].

    Example:

    module_depends_on = [
      null_resource.name
    ]

Module Outputs

The following attributes are exported in the outputs of the module:

  • iam: (list(iam))

    The iam resource objects that define the access to the secret.

  • service: (object(service))

    All google_cloud_run_service resource attributes.

  • domain_mapping: (object(domain_mapping))

    All google_cloud_run_domain_mapping resource attributes.

  • module_enabled: (bool)

    Whether this module is enabled.

External Documentation

Google Documentation

Terraform GCP Provider Documentation

Module Versioning

This Module follows the principles of Semantic Versioning (SemVer).

Given a version number MAJOR.MINOR.PATCH, we increment the:

  1. MAJOR version when we make incompatible changes,
  2. MINOR version when we add functionality in a backwards compatible manner, and
  3. PATCH version when we make backwards compatible bug fixes.

Backwards compatibility in 0.0.z and 0.y.z version

  • Backwards compatibility in versions 0.0.z is not guaranteed when z is increased. (Initial development)
  • Backwards compatibility in versions 0.y.z is not guaranteed when y is increased. (Pre-release)

About Mineiros

Mineiros is a remote-first company headquartered in Berlin, Germany that solves development, automation and security challenges in cloud infrastructure.

Our vision is to massively reduce time and overhead for teams to manage and deploy production-grade and secure cloud infrastructure.

We offer commercial support for all of our modules and encourage you to reach out if you have any questions or need help. Feel free to email us at hello@mineiros.io or join our Community Slack channel.

Reporting Issues

We use GitHub Issues to track community reported issues and missing features.

Contributing

Contributions are always encouraged and welcome! For the process of accepting changes, we use Pull Requests. If you'd like more information, please see our Contribution Guidelines.

Makefile Targets

This repository comes with a handy Makefile. Run make help to see details on each available target.

License

license

This module is licensed under the Apache License Version 2.0, January 2004. Please see LICENSE for full details.

Copyright © 2020-2022 Mineiros GmbH

About

A Terraform module to deploy and manage highly scalable, containerized applications in Google Cloud Run, a fully managed serverless platform in Google Cloud https://cloud.google.com/run

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published