This topic describes how to create a bucket and configure the properties of the bucket by using Terraform.

Prerequisites

Before you begin, ensure that you have completed the following operations:

Procedure

  1. Create a bucket.
    1. Create the terraform.tf file, enter the following content, and save the file to the current working directory.
      Note You must create an independent working directory for each Terraform project.
      provider "alicloud" {
        alias  = "bj-prod"
        region = "cn-beijing"
      }
      
      resource "alicloud_oss_bucket" "bucket-new" {
        provider = alicloud.bj-prod
      
        bucket = "bucket-20200310-1"
        acl    = "public-read"
      }
    2. Run the terraform apply command to create the bucket. If log entries similar to the following ones are displayed, the bucket is created.
      alicloud_oss_bucket.bucket-new: Creating...
      alicloud_oss_bucket.bucket-new: Creation complete after 2s [id=bucket-20200310-1]
      
      Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
  2. Configure the properties of the bucket.
    1. Create the resource.tf file, enter the following content, and save the file to the current working directory.
      Note Terraform will automatically load all of the .tf files in the directory. You can write configuration information to different files as needed.
      resource "alicloud_oss_bucket" "bucket-attr" {
        provider = alicloud.bj-prod
      
        bucket = "bucket-20200310-2"
        # Default homepage and 404 page of the static website
        website {
          index_document = "index.html"
          error_document = "error.html"
        }
        # Path where access logs are stored
        logging {
          target_bucket = alicloud_oss_bucket.bucket-new.id
          target_prefix = "log/"
        }
        # Object lifecycle rule
        lifecycle_rule {
          id      = "expirationByDays"
          prefix  = "path/expirationByDays"
          enabled = true
      
          expiration {
            days = 365
          }
        }
      
        lifecycle_rule {
          id      = 365
          prefix  = "path/365"
          enabled = true
      
          expiration {
            date = "2021-04-10"
          }
        }
        # Hotlink protection settings
        referer_config {
          allow_empty = true
          referers    = ["http://www.aliyun.com", "https://www.aliyun.com", "http://?.aliyun.com"]
        }
      }
    2. Run the terraform apply command to configure the properties of the bucket. If log entries similar to the following ones are displayed, the properties are configured.
      alicloud_oss_bucket.bucket-attr: Creating...
      alicloud_oss_bucket.bucket-attr: Creation complete after 2s [id=bucket-20200310-2]
      
      Apply complete! Resources: 1 added, 0 changed, 0 destroyed.