# Copyright 2024 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

---
name: 'Disk'
kind: 'compute#disk'
description: |
  Persistent disks are durable storage devices that function similarly to
  the physical disks in a desktop or a server. Compute Engine manages the
  hardware behind these devices to ensure data redundancy and optimize
  performance for you. Persistent disks are available as either standard
  hard disk drives (HDD) or solid-state drives (SSD).

  Persistent disks are located independently from your virtual machine
  instances, so you can detach or move persistent disks to keep your data
  even after you delete your instances. Persistent disk performance scales
  automatically with size, so you can resize your existing persistent disks
  or add more persistent disks to an instance to meet your performance and
  storage space requirements.

  Add a persistent disk to your instance when you need reliable and
  affordable storage with consistent performance characteristics.
references:
  guides:
    'Adding a persistent disk': 'https://cloud.google.com/compute/docs/disks/add-persistent-disk'
  api: 'https://cloud.google.com/compute/docs/reference/v1/disks'
docs:
base_url: 'projects/{{project}}/zones/{{zone}}/disks'
has_self_link: true
immutable: true
timeouts:
  insert_minutes: 20
  update_minutes: 20
  delete_minutes: 20
async:
  actions: ['create', 'delete', 'update']
  type: 'OpAsync'
  operation:
    base_url: '{{op_id}}'
  result:
    resource_inside_response: false
collection_url_key: 'items'
iam_policy:
  parent_resource_attribute: 'name'
  base_url: 'projects/{{project}}/zones/{{zone}}/disks/{{name}}'
  example_config_body: 'templates/terraform/iam/iam_attributes.go.tmpl'
  import_format:
    - 'projects/{{project}}/zones/{{zone}}/disks/{{name}}'
    - '{{name}}'
custom_code:
  constants: 'templates/terraform/constants/disk.tmpl'
  encoder: 'templates/terraform/encoders/disk.tmpl'
  update_encoder: 'templates/terraform/update_encoder/hyper_disk.go.tmpl'
  decoder: 'templates/terraform/decoders/disk.tmpl'
  pre_delete: 'templates/terraform/pre_delete/detach_disk.tmpl'
custom_diff:
  - 'customdiff.ForceNewIfChange("size", IsDiskShrinkage)'
  - 'hyperDiskIopsUpdateDiffSuppress'
examples:
  - name: 'disk_basic'
    primary_resource_id: 'default'
    primary_resource_name: 'fmt.Sprintf("tf-test-test-disk%s", context["random_suffix"])'
    vars:
      disk_name: 'test-disk'
  - name: 'disk_async'
    primary_resource_id: 'primary'
    primary_resource_name: 'fmt.Sprintf("tf-test-test-disk%s", context["random_suffix"])'
    vars:
      disk_name: 'async-test-disk'
      secondary_disk_name: 'async-secondary-test-disk'
  - name: 'disk_features'
    primary_resource_id: 'default'
    primary_resource_name: 'fmt.Sprintf("tf-test-test-disk%s", context["random_suffix"])'
    vars:
      disk_name: 'test-disk-features'
parameters:
  - name: 'zone'
    type: ResourceRef
    description: 'A reference to the zone where the disk resides.'
    required: false
    default_from_api: true
    custom_flatten: 'templates/terraform/custom_flatten/name_from_self_link.tmpl'
    custom_expand: 'templates/terraform/custom_expand/resourceref_with_validation.go.tmpl'
    resource: 'Zone'
    imports: 'name'
  - name: 'snapshot'
    type: ResourceRef
    description: |
      The source snapshot used to create this disk. You can provide this as
      a partial or full URL to the resource. If the snapshot is in another
      project than this disk, you must supply a full URL. For example, the
      following are valid values:

      * `https://www.googleapis.com/compute/v1/projects/project/global/snapshots/snapshot`
      * `projects/project/global/snapshots/snapshot`
      * `global/snapshots/snapshot`
      * `snapshot`
    api_name: sourceSnapshot
    custom_expand: 'templates/terraform/custom_expand/resourceref_with_validation.go.tmpl'
    resource: 'Snapshot'
    imports: 'selfLink'
properties:
  - name: 'sourceImageEncryptionKey'
    type: NestedObject
    description: |
      The customer-supplied encryption key of the source image. Required if
      the source image is protected by a customer-supplied encryption key.
    immutable: true
    properties:
      - name: 'rawKey'
        type: String
        description: |
          Specifies a 256-bit customer-supplied encryption key, encoded in
          RFC 4648 base64 to either encrypt or decrypt this resource.
      - name: 'sha256'
        type: String
        description: |
          The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied
          encryption key that protects this resource.
        output: true
        # TODO(chrisst) Change to ResourceRef once KMS is in Magic Modules
      - name: 'kmsKeySelfLink'
        type: String
        description: |
          The self link of the encryption key used to encrypt the disk. Also called KmsKeyName
          in the cloud console. Your project's Compute Engine System service account
          (`service-{{PROJECT_NUMBER}}@compute-system.iam.gserviceaccount.com`) must have
          `roles/cloudkms.cryptoKeyEncrypterDecrypter` to use this feature.
          See https://cloud.google.com/compute/docs/disks/customer-managed-encryption#encrypt_a_new_persistent_disk_with_your_own_keys
        api_name: kmsKeyName
        diff_suppress_func: 'tpgresource.CompareSelfLinkRelativePaths'
      - name: 'kmsKeyServiceAccount'
        type: String
        description: |
          The service account used for the encryption request for the given KMS key.
          If absent, the Compute Engine Service Agent service account is used.
  - name: 'sourceInstantSnapshot'
    type: String
    description: |
      The source instant snapshot used to create this disk. You can provide this as a partial or full URL to the resource.
      For example, the following are valid values:

      * `https://www.googleapis.com/compute/v1/projects/project/zones/zone/instantSnapshots/instantSnapshot`
      * `projects/project/zones/zone/instantSnapshots/instantSnapshot`
      * `zones/zone/instantSnapshots/instantSnapshot`
    resource: 'Snapshot'
    imports: 'selfLink'
    diff_suppress_func: 'tpgresource.CompareSelfLinkOrResourceName'
  - name: 'sourceInstantSnapshotId'
    type: String
    description: |
      The unique ID of the instant snapshot used to create this disk. This value identifies
      the exact instant snapshot that was used to create this persistent disk.
      For example, if you created the persistent disk from an instant snapshot that was later
      deleted and recreated under the same name, the source instant snapshot ID would identify
      the exact version of the instant snapshot that was used.
    output: true
  - name: 'sourceImageId'
    type: String
    description: |
      The ID value of the image used to create this disk. This value
      identifies the exact image that was used to create this persistent
      disk. For example, if you created the persistent disk from an image
      that was later deleted and recreated under the same name, the source
      image ID would identify the exact version of the image that was used.
    output: true
  - name: 'diskEncryptionKey'
    type: NestedObject
    description: |
      Encrypts the disk using a customer-supplied encryption key.

      After you encrypt a disk with a customer-supplied key, you must
      provide the same key if you use the disk later (e.g. to create a disk
      snapshot or an image, or to attach the disk to a virtual machine).

      Customer-supplied encryption keys do not protect access to metadata of
      the disk.

      If you do not provide an encryption key when creating the disk, then
      the disk will be encrypted using an automatically generated key and
      you do not need to provide a key to use the disk later.
    immutable: true
    properties:
      - name: 'rawKey'
        type: String
        description: |
          Specifies a 256-bit customer-supplied encryption key, encoded in
          RFC 4648 base64 to either encrypt or decrypt this resource.
        sensitive: true
      - name: 'rsaEncryptedKey'
        type: String
        description: |
          Specifies an RFC 4648 base64 encoded, RSA-wrapped 2048-bit
          customer-supplied encryption key to either encrypt or decrypt
          this resource. You can provide either the rawKey or the rsaEncryptedKey.
        sensitive: true
      - name: 'sha256'
        type: String
        description: |
          The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied
          encryption key that protects this resource.
        output: true
      - name: 'kmsKeySelfLink'
        type: String
        description: |
          The self link of the encryption key used to encrypt the disk. Also called KmsKeyName
          in the cloud console. Your project's Compute Engine System service account
          (`service-{{PROJECT_NUMBER}}@compute-system.iam.gserviceaccount.com`) must have
          `roles/cloudkms.cryptoKeyEncrypterDecrypter` to use this feature.
          See https://cloud.google.com/compute/docs/disks/customer-managed-encryption#encrypt_a_new_persistent_disk_with_your_own_keys
        api_name: kmsKeyName
        diff_suppress_func: 'tpgresource.CompareSelfLinkRelativePaths'
      - name: 'kmsKeyServiceAccount'
        type: String
        description: |
          The service account used for the encryption request for the given KMS key.
          If absent, the Compute Engine Service Agent service account is used.
  - name: 'sourceSnapshotEncryptionKey'
    type: NestedObject
    description: |
      The customer-supplied encryption key of the source snapshot. Required
      if the source snapshot is protected by a customer-supplied encryption
      key.
    immutable: true
    properties:
      - name: 'rawKey'
        type: String
        description: |
          Specifies a 256-bit customer-supplied encryption key, encoded in
          RFC 4648 base64 to either encrypt or decrypt this resource.
        # TODO(chrisst) Change to ResourceRef once KMS is in Magic Modules
      - name: 'kmsKeySelfLink'
        type: String
        description: |
          The self link of the encryption key used to encrypt the disk. Also called KmsKeyName
          in the cloud console. Your project's Compute Engine System service account
          (`service-{{PROJECT_NUMBER}}@compute-system.iam.gserviceaccount.com`) must have
          `roles/cloudkms.cryptoKeyEncrypterDecrypter` to use this feature.
          See https://cloud.google.com/compute/docs/disks/customer-managed-encryption#encrypt_a_new_persistent_disk_with_your_own_keys
        api_name: kmsKeyName
        diff_suppress_func: 'tpgresource.CompareSelfLinkRelativePaths'
      - name: 'sha256'
        type: String
        description: |
          The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied
          encryption key that protects this resource.
        output: true
      - name: 'kmsKeyServiceAccount'
        type: String
        description: |
          The service account used for the encryption request for the given KMS key.
          If absent, the Compute Engine Service Agent service account is used.
  - name: 'sourceSnapshotId'
    type: String
    description: |
      The unique ID of the snapshot used to create this disk. This value
      identifies the exact snapshot that was used to create this persistent
      disk. For example, if you created the persistent disk from a snapshot
      that was later deleted and recreated under the same name, the source
      snapshot ID would identify the exact version of the snapshot that was
      used.
    output: true
  - name: 'sourceStorageObject'
    type: String
    description: |
      The full Google Cloud Storage URI where the disk image is stored.
      This file must be a gzip-compressed tarball whose name ends in .tar.gz or virtual machine disk whose name ends in vmdk.
      Valid URIs may start with gs:// or https://storage.googleapis.com/.
      This flag is not optimized for creating multiple disks from a source storage object.
      To create many disks from a source storage object, use gcloud compute images import instead.
    ignore_read: true
  - name: 'labelFingerprint'
    type: Fingerprint
    description: |
      The fingerprint used for optimistic locking of this resource.  Used
      internally during updates.
    output: true
    update_url: 'projects/{{project}}/zones/{{zone}}/disks/{{name}}/setLabels'
    update_verb: 'POST'
    key_expander: ''
  - name: 'creationTimestamp'
    type: Time
    description: 'Creation timestamp in RFC3339 text format.'
    output: true
  - name: 'description'
    type: String
    description: |
      An optional description of this resource. Provide this property when
      you create the resource.
  - name: 'lastAttachTimestamp'
    type: Time
    description: 'Last attach timestamp in RFC3339 text format.'
    output: true
  - name: 'lastDetachTimestamp'
    type: Time
    description: 'Last detach timestamp in RFC3339 text format.'
    output: true
  - name: 'labels'
    type: KeyValueLabels
    description: |
      Labels to apply to this disk.  A list of key->value pairs.
    update_url: 'projects/{{project}}/zones/{{zone}}/disks/{{name}}/setLabels'
    update_verb: 'POST'
  - name: 'name'
    type: String
    description: |
      Name of the resource. Provided by the client when the resource is
      created. The name must be 1-63 characters long, and comply with
      RFC1035. Specifically, the name must be 1-63 characters long and match
      the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the
      first character must be a lowercase letter, and all following
      characters must be a dash, lowercase letter, or digit, except the last
      character, which cannot be a dash.
    required: true
    immutable: true
    validation:
      function: 'verify.ValidateGCEName'
  - name: 'size'
    type: Integer
    description: |
      Size of the persistent disk, specified in GB. You can specify this
      field when creating a persistent disk using the `image` or
      `snapshot` parameter, or specify it alone to create an empty
      persistent disk.

      If you specify this field along with `image` or `snapshot`,
      the value must not be less than the size of the image
      or the size of the snapshot.

      ~>**NOTE** If you change the size, Terraform updates the disk size
      if upsizing is detected but recreates the disk if downsizing is requested.
      You can add `lifecycle.prevent_destroy` in the config to prevent destroying
      and recreating.
    api_name: sizeGb
    default_from_api: true
    update_url: 'projects/{{project}}/zones/{{zone}}/disks/{{name}}/resize'
    update_verb: 'POST'
  - name: 'users'
    type: Array
    description: |
      Links to the users of the disk (attached instances) in form:
      project/zones/zone/instances/instance
    output: true
    custom_expand: 'templates/terraform/custom_expand/array_resourceref_with_validation.go.tmpl'
    item_type:
      name: 'user'
      type: ResourceRef
      description: 'A reference to a user of this disk'
      resource: 'Instance'
      imports: 'selfLink'
  - name: 'physicalBlockSizeBytes'
    type: Integer
    description: |
      Physical block size of the persistent disk, in bytes. If not present
      in a request, a default value is used. Currently supported sizes
      are 4096 and 16384, other sizes may be added in the future.
      If an unsupported value is requested, the error message will list
      the supported values for the caller's project.
    default_from_api: true
  - name: 'interface'
    type: String
    description: |
      Specifies the disk interface to use for attaching this disk, which is either SCSI or NVME. The default is SCSI.
    min_version: 'beta'
    # interface is removed using url_param_only to preserve schema definition
    # and prevent sending or reading in API requests
    url_param_only: true
    diff_suppress_func: 'AlwaysDiffSuppress'
    default_value: "SCSI"
    deprecation_message: '`interface` is deprecated and will be removed in a future major release. This field is no longer used and can be safely removed from your configurations; disk interfaces are automatically determined on attachment.'
  - name: 'sourceDisk'
    type: String
    description: |
      The source disk used to create this disk. You can provide this as a partial or full URL to the resource.
      For example, the following are valid values:

      * https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks/{disk}
      * https://www.googleapis.com/compute/v1/projects/{project}/regions/{region}/disks/{disk}
      * projects/{project}/zones/{zone}/disks/{disk}
      * projects/{project}/regions/{region}/disks/{disk}
      * zones/{zone}/disks/{disk}
      * regions/{region}/disks/{disk}
    diff_suppress_func: 'sourceDiskDiffSuppress'
  - name: 'sourceDiskId'
    type: String
    description: |
      The ID value of the disk used to create this image. This value may
      be used to determine whether the image was taken from the current
      or a previous instance of a given disk name.
    output: true
  - name: 'DiskId'
    type: String
    description: |
      The unique identifier for the resource. This identifier is defined by the server.
    api_name: id
    output: true
  - name: 'type'
    type: ResourceRef
    description: |
      URL of the disk type resource describing which disk type to use to
      create the disk. Provide this when creating the disk.
    diff_suppress_func: 'tpgresource.CompareResourceNames'
    custom_flatten: 'templates/terraform/custom_flatten/name_from_self_link.tmpl'
    custom_expand: 'templates/terraform/custom_expand/resourceref_with_validation.go.tmpl'
    default_value: "pd-standard"
    resource: 'DiskType'
    imports: 'selfLink'
  - name: 'image'
    type: String
    description: |
      The image from which to initialize this disk. This can be
      one of: the image's `self_link`, `projects/{project}/global/images/{image}`,
      `projects/{project}/global/images/family/{family}`, `global/images/{image}`,
      `global/images/family/{family}`, `family/{family}`, `{project}/{family}`,
      `{project}/{image}`, `{family}`, or `{image}`. If referred by family, the
      images names must include the family name. If they don't, use the
      [google_compute_image data source](/docs/providers/google/d/compute_image.html).
      For instance, the image `centos-6-v20180104` includes its family name `centos-6`.
      These images can be referred by family name here.
    api_name: sourceImage
    immutable: true
    diff_suppress_func: 'DiskImageDiffSuppress'
  - name: 'resourcePolicies'
    type: Array
    description: |
      Resource policies applied to this disk for automatic snapshot creations.

      ~>**NOTE** This value does not support updating the
      resource policy, as resource policies can not be updated more than
      one at a time. Use
      [`google_compute_disk_resource_policy_attachment`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_disk_resource_policy_attachment)
      to allow for updating the resource policy attached to the disk.
    min_version: 'beta'
    default_from_api: true
    custom_expand: 'templates/terraform/custom_expand/array_resourceref_with_validation.go.tmpl'
    item_type:
      name: 'resourcePolicy'
      type: ResourceRef
      description:
        'A resource policy applied to this disk for automatic snapshot
        creations.'
      resource: 'ResourcePolicy'
      imports: 'selfLink'
  - name: 'enableConfidentialCompute'
    type: Boolean
    description: |
      Whether this disk is using confidential compute mode.
      Note: Only supported on hyperdisk skus, disk_encryption_key is required when setting to true
    required: false
    default_from_api: true
  - name: 'multiWriter'
    type: Boolean
    description: |
      Indicates whether or not the disk can be read/write attached to more than one instance.
    min_version: 'beta'
  - name: 'provisionedIops'
    type: Integer
    description: |
      Indicates how many IOPS must be provisioned for the disk.
      Note: Updating currently is only supported by hyperdisk skus without the need to delete and recreate the disk, hyperdisk
      allows for an update of IOPS every 4 hours. To update your hyperdisk more frequently, you'll need to manually delete and recreate it
    required: false
    default_from_api: true
    update_url: 'projects/{{project}}/zones/{{zone}}/disks/{{name}}?paths=provisionedIops'
    update_verb: 'PATCH'
  - name: 'provisionedThroughput'
    type: Integer
    description: |
      Indicates how much Throughput must be provisioned for the disk.
      Note: Updating currently is only supported by hyperdisk skus without the need to delete and recreate the disk, hyperdisk
      allows for an update of Throughput every 4 hours. To update your hyperdisk more frequently, you'll need to manually delete and recreate it
    default_from_api: true
    update_url: 'projects/{{project}}/zones/{{zone}}/disks/{{name}}?paths=provisionedThroughput'
    update_verb: 'PATCH'
  - name: 'asyncPrimaryDisk'
    type: NestedObject
    diff_suppress_func: 'tpgresource.CompareSelfLinkRelativePaths'
    properties:
      - name: 'disk'
        type: String
        description: |
          Primary disk for asynchronous disk replication.
        required: true
  - name: 'architecture'
    ignore_read: true
    type: String
      The architecture of the disk.
    enum_values:
      - 'X86_64'
      - 'ARM64'
  - name: 'params'
    type: NestedObject
    ignore_read: true
    immutable: true
    description: |
     Additional params passed with the request, but not persisted as part of resource payload
    properties:
      - name: 'resourceManagerTags'
        type: KeyValuePairs
        description: |
          Resource manager tags to be bound to the disk. Tag keys and values have the
          same definition as resource manager tags. Keys must be in the format tagKeys/{tag_key_id},
          and values are in the format tagValues/456.
        api_name: resourceManagerTags
        ignore_read: true
  - name: 'guestOsFeatures'
    type: Array
    description: |
      A list of features to enable on the guest operating system.
      Applicable only for bootable disks.
    is_set: true
    default_from_api: true
    item_type:
      type: NestedObject
      properties:
        - name: 'type'
          type: String
          description: |
            The type of supported feature. Read [Enabling guest operating system features](https://cloud.google.com/compute/docs/images/create-delete-deprecate-private-images#guest-os-features) to see a list of available options.
          required: true
  - name: 'licenses'
    type: Array
    description: Any applicable license URI.
    immutable: true
    default_from_api: true
    custom_expand: 'templates/terraform/custom_expand/array_resourceref_with_validation.go.tmpl'
    item_type:
      name: 'license'
      type: ResourceRef
      description: 'An applicable license URI'
      resource: 'License'
      imports: 'selfLink'
  - name: 'storagePool'
    type: String
    description: |
      The URL or the name of the storage pool in which the new disk is created.
      For example:
      * https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/storagePools/{storagePool}
      * /projects/{project}/zones/{zone}/storagePools/{storagePool}
      * /zones/{zone}/storagePools/{storagePool}
      * /{storagePool}
    required: false
    immutable: true
    diff_suppress_func: 'tpgresource.CompareResourceNames'
    custom_flatten: 'templates/terraform/custom_flatten/name_from_self_link.tmpl'
    custom_expand: 'templates/terraform/custom_expand/storage_pool_full_url.tmpl'
  - name: 'accessMode'
    type: String
    description: |
      The accessMode of the disk.
      For example:
      * READ_WRITE_SINGLE
      * READ_WRITE_MANY
      * READ_ONLY_SINGLE
    required: false
    immutable: false
    default_from_api: true
    update_url: 'projects/{{project}}/zones/{{zone}}/disks/{{name}}?paths=accessMode'
    update_verb: 'PATCH'
virtual_fields:
  - name: 'create_snapshot_before_destroy'
    type: Boolean
    default_value: false
    description: |
      If set to true, a snapshot of the disk will be created before it is destroyed.
      If your disk is encrypted with customer managed encryption keys these will be reused for the snapshot creation.
      The name of the snapshot by default will be `{{disk-name}}-YYYYMMDD-HHmm`
  - name: 'create_snapshot_before_destroy_prefix'
    type: String
    description: |
      This will set a custom name prefix for the snapshot that's created when the disk is deleted.
