Use Terraform to create storage buckets and upload objects

In this quickstart guide, you'll create aTerraform configuration file that provisions a storage bucket anduploads asample_file.txt object to the bucket. To complete this quickstart,you'll use your local shell and terminal or the Cloud Shell Editor andCloud Shell terminal. You'll also use theTerraform CLI, which is preinstalled in Cloud Shell.

Before you begin

To set up a project for this quickstart, complete the following steps:

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Storage API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Storage API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

Create the folder structure and Terraform configuration file

To create the Terraform configuration file and the file you'll upload as anobject to Cloud Storage, complete the following steps:

Cloud Shell

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  1. Set the default Google Cloud project where you want to apply your Terraform configuration:
    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
  2. In the Cloud Shell terminal, set the home directory as the active directory:
    cd
  3. Create a new folder namedterraform:
    mkdir terraform
  4. Launch the Cloud Shell Editor by clickingOpen Editor on the toolbar of the Cloud Shell window.
  5. In theExplorer pane, right-click theterraform folder and then clickNew File.
  6. Entermain.tf as the file name and then clickOK.
  7. In theExplorer pane, right-click theterraform folder and then clickNew File.
  8. Entersample_file.txt as the file name and then clickOK.

Local shell

  1. If you haven't already,install and configure Terraform. Make sure youinstall andinitialize the Google Cloud CLI.

    By default, Terraform reads the configuration created by Google Cloud CLI and deploys the resources you later specify into your active Google Cloud CLI project.

  2. In your terminal, set the home directory as the active directory:
    cd
  3. Create a new folder namedterraform:
    mkdir terraform
  4. In your text editor of choice, create a new file namedmain.tf in yourterraform folder.
  5. In your text editor of choice, create a new file namedsample_file.txt in yourterraform folder.

Define the infrastructure in the Terraform configuration file

To define the infrastructure you want to provision in your Terraformconfiguration file, complete the following steps:

  1. Open themain.tf file.

  2. Copy the following sample to themain.tf file.

    # Create new storage bucket in the US# location with Standard Storageresource"google_storage_bucket""static"{name="BUCKET_NAME"location="US"storage_class="STANDARD"uniform_bucket_level_access=true}# Upload a text file as an object# to the storage bucketresource"google_storage_bucket_object""default"{name="OBJECT_NAME"source="OBJECT_PATH"content_type="text/plain"bucket=google_storage_bucket.static.id}

    Replace:

    • BUCKET_NAME with the name of the bucket you want to create.For example,my-bucket.

      See bucket naming requirements.
      • Bucket names can only contain lowercase letters, numeric characters, dashes (-), underscores (_), and dots (.). Spaces are not allowed. Names containing dots requireverification.
      • Bucket names must start and end with a number or letter.
      • Bucket names must contain 3-63 characters. Names containing dots can contain up to 222 characters, but each dot-separated component can be no longer than 63 characters.
      • Bucket names cannot be represented as an IP address in dotted-decimal notation (for example, 192.168.5.4).
      • Bucket names cannot begin with the "goog" prefix.
      • Bucket names cannot contain "google" or close misspellings, such as "g00gle".
    • OBJECT_NAME with the name of the object you want to upload.For this quickstart, enter the namesample_file.txt.

    • OBJECT_PATH with the path to the object you want to upload.For this quickstart, enter the path~/terraform/sample_file.txt.

  3. Save themain.tf file.

Initialize the working directory containing the Terraform configuration file

To initialize Terraform and the directory containing yourTerraform configuration file, complete the following steps:

  1. In your terminal, set theterraform folder as the current workingdirectory:

    cd~/terraform
  2. Initialize Terraform:

    terraforminit
  3. If you're using the Cloud Shell and you're prompted to authorizeCloud Shell, clickAuthorize.

    Terraform initializes the working directory. If it successfullyinitializes the working directory, Terraform returns output similarto the following:

    Terraformhasbeensuccessfullyinitialized!YoumaynowbeginworkingwithTerraform.Tryrunning"terraform plan"toseeanychangesthatarerequiredforyourinfrastructure.AllTerraformcommandsshouldnowwork.IfyoueversetorchangemodulesorbackendconfigurationforTerraform,rerunthiscommandtoreinitializeyourworkingdirectory.Ifyouforget,othercommandswilldetectitandremindyoutodosoifnecessary.

Preview the execution plan

The Terraform execution plan is based on the Terraformconfiguration and indicates the changes that Terraform plans to make tothe Cloud Storage infrastructure and services.

View the Terraform execution plan:

terraformplan

Example output:

Terraformusedtheselectedproviderstogeneratethefollowingexecutionplan.Resourceactionsareindicatedwiththefollowingsymbols:+createTerraformwillperformthefollowingactions:  # google_storage_bucket.static will be created+resource"google_storage_bucket""static"{+force_destroy=false+id=(knownafterapply)+location="US"+name="my-bucket"+project="my-project"+public_access_prevention=(knownafterapply)+self_link=(knownafterapply)+storage_class="STANDARD"+uniform_bucket_level_access=true+url=(knownafterapply)+versioning{+enabled=(knownafterapply)}+website{+main_page_suffix=(knownafterapply)+not_found_page=(knownafterapply)}}  # google_storage_bucket_object.default will be created+resource"google_storage_bucket_object""default"{+bucket=(knownafterapply)+content_type="text/plain"+crc32c=(knownafterapply)+detect_md5hash="different hash"+id=(knownafterapply)+kms_key_name=(knownafterapply)+md5hash=(knownafterapply)+media_link=(knownafterapply)+name="sample_file.txt"+output_name=(knownafterapply)+self_link=(knownafterapply)+source="sample_file.txt"+storage_class=(knownafterapply)}Plan:2toadd,0tochange,0todestroy.

Apply the changes proposed in the execution plan

To apply the changes in your Terraform configuration file, completethe following steps:

  1. Apply the changes from the execution plan to theCloud Storage infrastructure with the following command. When youapply the changes, Terraform creates a storage bucket and uploadssample_file.txt to the bucket.

    terraformapply

    Example output:

    Terraformusedtheselectedproviderstogeneratethefollowingexecutionplan.Resourceactionsareindicatedwiththefollowingsymbols:+createTerraformwillperformthefollowingactions:  # google_storage_bucket.static will be created+resource"google_storage_bucket""static"{+force_destroy=false+id=(knownafterapply)+location="US"+name="my-bucket"+project="my-project"+public_access_prevention=(knownafterapply)+self_link=(knownafterapply)+storage_class="STANDARD"+uniform_bucket_level_access=true+url=(knownafterapply)+versioning{+enabled=(knownafterapply)}+website{+main_page_suffix=(knownafterapply)+not_found_page=(knownafterapply)}}  # google_storage_bucket_object.default will be created+resource"google_storage_bucket_object""default"{+bucket=(knownafterapply)+content_type="text/plain"+crc32c=(knownafterapply)+detect_md5hash="different hash"+id=(knownafterapply)+kms_key_name=(knownafterapply)+md5hash=(knownafterapply)+media_link=(knownafterapply)+name="sample_file.txt"+output_name=(knownafterapply)+self_link=(knownafterapply)+source="sample_file.txt"+storage_class=(knownafterapply)}Plan:2toadd,0tochange,0todestroy.Doyouwanttoperformtheseactions?Terraformwillperformtheactionsdescribedabove.Only'yes'willbeacceptedtoapprove.Enteravalue:
  2. Typeyes and pressEnter.

    If successful, Terraform returns output similar to the following:

    Applycomplete!Resources:2added,0changed,0destroyed.

View your storage bucket and uploaded object

In the Google Cloud console, go to the Cloud StorageBuckets page.

Go to Buckets

The new bucket appears, containing thesample_file.txt object. Note that theresources might take a few minutes to get provisioned after you runterraform apply.

Clean up your project

In order to avoid incurring unexpected charges from the Google Cloud resourcesyou created during this quickstart, complete the following steps to clean up theresources:

  1. In your terminal, set theterraform folder as the current workingdirectory:

    cd~/terraform
  2. Delete the Cloud Storage resources that you created based on yourTerraform configuration file:

    terraformdestroy
  3. If successful, Terraform returns output similar to the following:

    Terraformusedtheselectedproviderstogeneratethefollowingexecutionplan.Resourceactionsareindicatedwiththefollowingsymbols:-destroyTerraformwillperformthefollowingactions:  # google_storage_bucket.static will be destroyed-resource"google_storage_bucket""static"{-default_event_based_hold=false->null-force_destroy=false->null-id="my-bucket"->null-labels={}->null-location="US"->null-name=""->null-project="example-project"->null-public_access_prevention="inherited"->null-requester_pays=false->null-self_link="https://www.googleapis.com/storage/v1/b/cbonnie-bucket-9"->null-storage_class="STANDARD"->null-uniform_bucket_level_access=true->null-url="gs://BUCKET_NAME"->null}  # google_storage_bucket_object.default will be destroyed-resource"google_storage_bucket_object""default"{-bucket="my-bucket"->null-content_type="text/plain"->null-crc32c="yZRlqg=="->null-detect_md5hash="XrY7u+Ae7tCTyyK7j1rNww=="->null-event_based_hold=false->null-id="my-bucket-sample_file.txt"->null-md5hash="XrY7u+Ae7tCTyyK7j1rNww=="->null-media_link="https://storage.googleapis.com/download/storage/v1/b/BUCKET_NAME/o/sample_file.txt?generation=1675800386233102&alt=media"->null-metadata={}->null-name="sample_file.txt"->null-output_name="sample_file.txt"->null-self_link="https://www.googleapis.com/storage/v1/b/BUCKET_NAME/o/sample_file.txt"->null-source="sample_file.txt"->null-storage_class="STANDARD"->null-temporary_hold=false->null}Plan:0toadd,0tochange,2todestroy.Doyoureallywanttodestroyallresources?Terraformwilldestroyallyourmanagedinfrastructure,asshownabove.Thereisnoundo.Only'yes'willbeacceptedtoconfirm.Enteravalue:
  4. Typeyes and pressEnter. If successful, Terraform returnsoutput similar to the following:

    Destroycomplete!Resources:2destroyed.
  5. In your terminal, delete theterraform folder.

    rm-rf~/terraform
  6. To verify that the bucket and object were deleted, go to theBuckets pagein the Google Cloud console.

    Go to Buckets

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.