# state-backend / oci / t0 "Quick start"
#
# An Object Storage bucket to contain Terraform state, versioned and private.
# Terraform reaches it through Object Storage's S3-compatible API, using the
# same s3 backend it uses for AWS.
#
# Change the tenancy OCID and region below, then:
#   terraform init && terraform apply
#   terraform output backend_block
#
# The s3 backend signs in with a Customer Secret Key, which is a separate
# credential from your API key. Create one under your user in the console, then
# export it before using the printed block:
#   export AWS_ACCESS_KEY_ID=<access key>
#   export AWS_SECRET_ACCESS_KEY=<secret>
#
# This version is for a scratch tenancy. Empty the bucket, then terraform
# destroy removes it.

locals {
  tenancy_ocid = "ocid1.tenancy.oc1..change-me" # change me
  region       = "us-ashburn-1"                 # change me

  tags = {
    owner               = "platform-engineering"
    environment         = "prod"
    data_classification = "restricted"
    managed_by          = "terraform"
  }
}

terraform {
  required_version = ">= 1.10"
  required_providers {
    oci = {
      source  = "oracle/oci"
      version = "~> 9.0"
    }
  }
}

provider "oci" {
  region = local.region
}

data "oci_objectstorage_namespace" "this" {
  compartment_id = local.tenancy_ocid
}

resource "oci_objectstorage_bucket" "state" {
  compartment_id = local.tenancy_ocid
  namespace      = data.oci_objectstorage_namespace.this.namespace
  name           = "tfstate"
  access_type    = "NoPublicAccess"
  freeform_tags  = local.tags

  # Every write keeps the previous version, so a bad apply is one restore away.
  versioning = "Enabled"
}

output "bucket" {
  description = "Bucket containing state."
  value       = oci_objectstorage_bucket.state.name
}

output "backend_block" {
  description = "Paste into the terraform block of any folder that should keep its state here. Change the key per folder."
  value       = <<-EOT
    backend "s3" {
      bucket                      = "${oci_objectstorage_bucket.state.name}"
      key                         = "CHANGE-ME/terraform.tfstate"
      region                      = "${local.region}"
      endpoints                   = { s3 = "https://${data.oci_objectstorage_namespace.this.namespace}.compat.objectstorage.${local.region}.oraclecloud.com" }
      use_lockfile                = true
      use_path_style              = true
      skip_region_validation      = true
      skip_credentials_validation = true
      skip_requesting_account_id  = true
      skip_metadata_api_check     = true
      skip_s3_checksum            = true
    }
  EOT
}
