Skip to content

googleStorageBucket

Creates a new bucket in Google cloud storage service (GCS). Once a bucket has been created, its location can't be changed.

For more information see the official documentation and API.

Note: If the project id is not set on the resource or in the provider block it will be dynamically determined which will require enabling the compute api.

Example Usage - creating a private bucket in standard storage, in the EU region. Bucket configured as static website and CORS configurations

/*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.*/
new google.storageBucket.StorageBucket(this, "static-site", {
  cors: [
    {
      max_age_seconds: 3600,
      method: ["GET", "HEAD", "PUT", "POST", "DELETE"],
      origin: ["http://image-store.com"],
      response_header: ["*"],
    },
  ],
  force_destroy: true,
  location: "EU",
  name: "image-store.com",
  uniform_bucket_level_access: true,
  website: [
    {
      main_page_suffix: "index.html",
      not_found_page: "404.html",
    },
  ],
});

Example Usage - Life cycle settings for storage bucket objects

/*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.*/
new google.storageBucket.StorageBucket(this, "auto-expire", {
  force_destroy: true,
  lifecycle_rule: [
    {
      action: [
        {
          type: "Delete",
        },
      ],
      condition: [
        {
          age: 3,
        },
      ],
    },
    {
      action: [
        {
          type: "AbortIncompleteMultipartUpload",
        },
      ],
      condition: [
        {
          age: 1,
        },
      ],
    },
  ],
  location: "US",
  name: "auto-expiring-bucket",
});

Example Usage - Enabling public access prevention

/*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.*/
new google.storageBucket.StorageBucket(this, "auto-expire", {
  force_destroy: true,
  location: "US",
  name: "no-public-access-bucket",
  public_access_prevention: "enforced",
});

Argument Reference

The following arguments are supported:

  • name - (Required) The name of the bucket.

  • location - (Required) The GCS location.


  • forceDestroy - (Optional, Default: false) When deleting a bucket, this boolean option will delete all contained objects. If you try to delete a bucket that contains objects, Terraform will fail that run.

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

  • storageClass - (Optional, Default: 'STANDARD') The Storage Class of the new bucket. Supported values include: standard, multiRegional, regional, nearline, coldline, archive.

  • autoclass - (Optional) The bucket's Autoclass configuration. Structure is documented below.

  • lifecycleRule - (Optional) The bucket's Lifecycle Rules configuration. Multiple blocks of this type are permitted. Structure is documented below.

  • versioning - (Optional) The bucket's Versioning configuration. Structure is documented below.

  • website - (Optional) Configuration if the bucket acts as a website. Structure is documented below.

  • cors - (Optional) The bucket's Cross-Origin Resource Sharing (CORS) configuration. Multiple blocks of this type are permitted. Structure is documented below.

  • defaultEventBasedHold - (Optional) Whether or not to automatically apply an eventBasedHold to new objects added to the bucket.

  • retentionPolicy - (Optional) Configuration of the bucket's data retention policy for how long objects in the bucket should be retained. Structure is documented below.

  • labels - (Optional) A map of key/value label pairs to assign to the bucket.

  • logging - (Optional) The bucket's Access & Storage Logs configuration. Structure is documented below.

  • encryption - (Optional) The bucket's encryption configuration. Structure is documented below.

  • requesterPays - (Optional, Default: false) Enables Requester Pays on a storage bucket.

  • uniformBucketLevelAccess - (Optional, Default: false) Enables Uniform bucket-level access access to a bucket.

  • publicAccessPrevention - (Optional) Prevents public access to a bucket. Acceptable values are "inherited" or "enforced". If "inherited", the bucket uses public access prevention. only if the bucket is subject to the public access prevention organization policy constraint. Defaults to "inherited".

  • customPlacementConfig - (Optional) The bucket's custom location configuration, which specifies the individual regions that comprise a dual-region bucket. If the bucket is designated a single or multi-region, the parameters are empty. Structure is documented below.

The lifecycleRule block supports:

  • action - (Required) The Lifecycle Rule's action configuration. A single block of this type is supported. Structure is documented below.

  • condition - (Required) The Lifecycle Rule's condition configuration. A single block of this type is supported. Structure is documented below.

The action block supports:

  • type - The type of the action of this Lifecycle Rule. Supported values include: delete, setStorageClass and abortIncompleteMultipartUpload.

  • storageClass - (Required if action type is setStorageClass) The target Storage Class of objects affected by this Lifecycle Rule. Supported values include: standard, multiRegional, regional, nearline, coldline, archive.

The condition block supports the following elements, and requires at least one to be defined. If you specify multiple conditions in a rule, an object has to match all of the conditions for the action to be taken:

  • age - (Optional) Minimum age of an object in days to satisfy this condition.

  • createdBefore - (Optional) A date in the RFC 3339 format YYYY-MM-DD. This condition is satisfied when an object is created before midnight of the specified date in UTC.

  • withState - (Optional) Match to live and/or archived objects. Unversioned buckets have only live objects. Supported values include: "live", "archived", "any".

  • matchesStorageClass - (Optional) Storage Class of objects to satisfy this condition. Supported values include: standard, multiRegional, regional, nearline, coldline, archive, durableReducedAvailability.

  • matchesPrefix - (Optional) One or more matching name prefixes to satisfy this condition.

  • matchesSuffix - (Optional) One or more matching name suffixes to satisfy this condition.

  • numNewerVersions - (Optional) Relevant only for versioned objects. The number of newer versions of an object to satisfy this condition.

  • customTimeBefore - (Optional) A date in the RFC 3339 format YYYY-MM-DD. This condition is satisfied when the customTime metadata for the object is set to an earlier date than the date used in this lifecycle condition.

  • daysSinceCustomTime - (Optional) Days since the date set in the customTime metadata for the object. This condition is satisfied when the current date and time is at least the specified number of days after the customTime.

  • daysSinceNoncurrentTime - (Optional) Relevant only for versioned objects. Number of days elapsed since the noncurrent timestamp of an object.

  • noncurrentTimeBefore - (Optional) Relevant only for versioned objects. The date in RFC 3339 (e.g. 20170613) when the object became nonconcurrent.

The autoclass block supports:

  • enabled - (Required) While set to true, autoclass automatically transitions objects in your bucket to appropriate storage classes based on each object's access pattern.

The versioning block supports:

  • enabled - (Required) While set to true, versioning is fully enabled for this bucket.

The website block supports the following elements, and requires at least one to be defined:

  • mainPageSuffix - (Optional) Behaves as the bucket's directory index where missing objects are treated as potential directories.

  • notFoundPage - (Optional) The custom object to return when a requested resource is not found.

The cors block supports:

  • origin - (Optional) The list of Origins eligible to receive CORS response headers. Note: "*" is permitted in the list of origins, and means "any Origin".

  • method - (Optional) The list of HTTP methods on which to include CORS response headers, (GET, OPTIONS, POST, etc) Note: "*" is permitted in the list of methods, and means "any method".

  • responseHeader - (Optional) The list of HTTP headers other than the simple response headers to give permission for the user-agent to share across domains.

  • maxAgeSeconds - (Optional) The value, in seconds, to return in the Access-Control-Max-Age header used in preflight responses.

The retentionPolicy block supports:

  • isLocked - (Optional) If set to true, the bucket will be locked and permanently restrict edits to the bucket's retention policy. Caution: Locking a bucket is an irreversible action.

  • retentionPeriod - (Required) The period of time, in seconds, that objects in the bucket must be retained and cannot be deleted, overwritten, or archived. The value must be less than 2,147,483,647 seconds.

The logging block supports:

  • logBucket - (Required) The bucket that will receive log objects.

  • logObjectPrefix - (Optional, Computed) The object prefix for log objects. If it's not provided, by default GCS sets this to this bucket's name.

The encryption block supports:

  • defaultKmsKeyName: The id of a Cloud KMS key that will be used to encrypt objects inserted into this bucket, if no encryption method is specified. You must pay attention to whether the crypto key is available in the location that this bucket is created in. See the docs for more details.

-> As per the docs for customer-managed encryption keys, the IAM policy for the specified key must permit the automatic Google Cloud Storage service account for the bucket's project to use the specified key for encryption and decryption operations. Although the service account email address follows a well-known format, the service account is created on-demand and may not necessarily exist for your project until a relevant action has occurred which triggers its creation. You should use the googleStorageProjectServiceAccount data source to obtain the email address for the service account when configuring IAM policy on the Cloud KMS key. This data source calls an API which creates the account if required, ensuring your Terraform applies cleanly and repeatedly irrespective of the state of the project. You should take care for race conditions when the same Terraform manages IAM policy on the Cloud KMS crypto key. See the data source page for more details.

The customPlacementConfig block supports:

Attributes Reference

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

  • selfLink - The URI of the created resource.

  • url - The base URL of the bucket, in the format gs://<bucketName>.

Timeouts

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

  • create - Default is 4 minutes.
  • update - Default is 4 minutes.
  • read - Default is 4 minutes.

Import

Storage buckets can be imported using the name or project/name. If the project is not passed to the import command it will be inferred from the provider block or environment variables. If it cannot be inferred it will be queried from the Compute API (this will fail if the API is not enabled).

e.g.

$ terraform import google_storage_bucket.image-store image-store-bucket
$ terraform import google_storage_bucket.image-store tf-test-project/image-store-bucket

\~> Note: Terraform will import this resource with forceDestroy set to false in state. If you've set it to true in config, run terraformApply to update the value set in state. If you delete this resource before updating the value, objects in the bucket will not be destroyed.