How to create a Digitalocean Managed Database cluster using terraform

Terraform is an open-source, infrastructure as code, software tool created by HashiCorp. Users define and provide data center infrastructure using a declarative configuration language known as HashiCorp Configuration Language, or optionally JSON.

Terraform codifies cloud APIs into declarative configuration files. It allows you to compose infrastructure as code in a Terraform file using HCL to provision resources from any infrastructure provider.

Digital Ocean offers Managed Database Services which allow you to easily create new database clusters and use them quickly without needing the effort to set them up or to manage the availability and scaling of the clusters, you can create the clusters using the Digital Ocean cloud console or by writing terraform code that will manage the creation, update and deletion of the clusters for you.

In this guide, we will learn how to create a managed database in Digital ocean using terraform.

Related content:

# Installing terraform

You can install terraform from this page according to your OS.

I am using Mac, so these are the commands to have terraform installed on my machine.

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Confirm the installation by checking the version installed:

➜ terraform version
Terraform v1.2.6
on darwin_arm64

# Configure Terraform for DigitalOcean

To use the DigitalOcean provider with Terraform, you have to configure the plugin using a provider file. This file tells Terraform which provider you’re using (DigitalOcean) and where to find the necessary credentials (your DigitalOcean API token).

Create and move into a directory from which you will configure and deploy your infrastructure. This is also where you create the provider file.

mkdir do-database
cd do-database

Create a new file in the working directory called provider.tf and then open it with your preferred text editor. Add the following content:

terraform {
  required_providers {
    digitalocean = {
      source  = "digitalocean/digitalocean"
      version = "2.21.0"
    }
  }
}

variable "do_token" {
  type = string
}

provider "digitalocean" {
  token = var.do_token
}

# Create Terraform Configuration Files

Once you have configured Terraform to access your DigitalOcean account, you can begin developing Terraform files that describe and declare the DigitalOcean resources that you want to deploy into your account. Terraform configuration files are text files stored with .tf extensions.

To create our database cluster

resource "random_string" "cluster-suffix" {
  length           = 4
  min_lower        = 2
  min_numeric      = 2
  special          = false
  override_special = "/@\\ "
}

resource "digitalocean_database_cluster" "postgres" {
  name       = "live-citizix-${random_string.cluster-suffix.result}"
  engine     = "pg"
  version    = "14"
  size       = "db-s-1vcpu-1gb"
  region     = "lon1"
  node_count = 1
  tags       = ["env:live"]

  maintenance_window {
    day  = 6
    hour = 10
  }
}

Create database

resource "digitalocean_database_db" "main" {
  cluster_id = digitalocean_database_cluster.postgres.id
  name       = "citizix"
}

Output values make information about your infrastructure available on the command line, and can expose information for other Terraform configurations to use. Output values are similar to return values in programming languages.

Let us define some outputs for our cluster

output "postgres-id" {
  value = digitalocean_database_cluster.postgres.id
}

output "postgres-private_host" {
  value = digitalocean_database_cluster.postgres.private_host
}

output "postgres-host" {
  value = digitalocean_database_cluster.postgres.host
}

output "postgres-database" {
  value = digitalocean_database_cluster.postgres.database
}

output "postgres-user" {
  value = digitalocean_database_cluster.postgres.user
}

output "postgres-password" {
  value     = digitalocean_database_cluster.postgres.password
  sensitive = true
}

# Execute Terraform

Once you have configured your Terraform files, you can deploy all of the resources you have configured from the command line. Terraform requires three steps for deployment: initializing the directory, reviewing an execution plan, and applying (executing) the Terraform plan.

Initialization prepares the working directory for use by accounting for any changes in Terraform’s backend configuration. The planning step provides you a detailed manifest of the resources for you to review before execution. Lastly, the terraform apply command executes the deployment of the resources into your account.

To initialize the working directory:

➜ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding digitalocean/digitalocean versions matching "2.21.0"...
- Installing digitalocean/digitalocean v2.21.0...
- Installed digitalocean/digitalocean v2.21.0 (signed by a HashiCorp partner, key ID F82037E524B9C0E8)

Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/cli/plugins/signing.html

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

If Terraform was successful in initializing the directory, you receive the message Terraform has been successfully initialized!.

Next, you need to create and view your Terrafrom plan. To create your Terraform plan:

export DO_PAT="<token here>"
terraform plan \
  -var "do_token=${DO_PAT}"

Output

Terraform used the selected providers to generate the following execution plan. Resource actions are
indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # digitalocean_database_cluster.postgres will be created
  + resource "digitalocean_database_cluster" "postgres" {
      + database             = (known after apply)
      + engine               = "pg"
      + host                 = (known after apply)
      + id                   = (known after apply)
      + name                 = "live-citizix-cluster"
      + node_count           = 1
      + password             = (sensitive value)
      + port                 = (known after apply)
      + private_host         = (known after apply)
      + private_network_uuid = (known after apply)
      + private_uri          = (sensitive value)
      + region               = "lon1"
      + size                 = "db-s-1vcpu-1gb"
      + tags                 = [
          + "env:live",
        ]
      + uri                  = (sensitive value)
      + urn                  = (known after apply)
      + user                 = (known after apply)
      + version              = "14"

      + maintenance_window {
          + day  = "6"
          + hour = "10"
        }
    }

  # digitalocean_database_db.main will be created
  + resource "digitalocean_database_db" "main" {
      + cluster_id = (known after apply)
      + id         = (known after apply)
      + name       = "citizix"
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Terraform returns a manifest of resources it will deploy when you apply the plan. It also creates an infra.out file with the manifest inside of it. Terraform uses the infra.out file to deploy the resources into your account.

After reviewing the plan, you can apply it and deploy the resources to your account. To execute the plan:

terraform apply \
  -var "do_token=${DO_PAT}"

Terraform deploys the resources into your account. You can open the DigitalOcean Control Panel to view their creation.

# Destroying Your Infrastructure

Although not commonly used in production environments, Terraform can also destroy infrastructure that it created. This is mainly useful in development environments that are deployed and destroyed multiple times.

First, create an execution plan to destroy the infrastructure by using terraform plan -destroy:

terraform plan \
  -var "do_token=${DO_PAT}" \
  --destroy

Output

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # digitalocean_database_cluster.postgres will be destroyed
  - resource "digitalocean_database_cluster" "postgres" {
      - database             = "defaultdb" -> null
      - engine               = "pg" -> null
      - host                 = "live-citizix-6xc2-do-user-9702479-0.b.db.ondigitalocean.com" -> null
      - id                   = "eb1a80d7-08b8-47f1-ac06-6475b5208884" -> null
      - name                 = "live-citizix-6xc2" -> null
      - node_count           = 1 -> null
      - password             = (sensitive value)
      - port                 = 25060 -> null
      - private_host         = "private-live-citizix-6xc2-do-user-9702479-0.b.db.ondigitalocean.com" -> null
      - private_network_uuid = "de5bc948-bc39-4255-8396-c102be57183a" -> null
      - private_uri          = (sensitive value)
      - region               = "lon1" -> null
      - size                 = "db-s-1vcpu-1gb" -> null
      - tags                 = [
          - "env:live",
        ] -> null
      - uri                  = (sensitive value)
      - urn                  = "do:dbaas:eb1a80d7-08b8-47f1-ac06-6475b5208884" -> null
      - user                 = "doadmin" -> null
      - version              = "14" -> null

      - maintenance_window {
          - day  = "saturday" -> null
          - hour = "06:31:57" -> null
        }
    }

  # random_string.cluster-suffix will be destroyed
  - resource "random_string" "cluster-suffix" {
      - id               = "6xc2" -> null
      - length           = 4 -> null
      - lower            = true -> null
      - min_lower        = 2 -> null
      - min_numeric      = 2 -> null
      - min_special      = 0 -> null
      - min_upper        = 0 -> null
      - number           = true -> null
      - numeric          = true -> null
      - override_special = "/@\\ " -> null
      - result           = "6xc2" -> null
      - special          = false -> null
      - upper            = true -> null
    }

Plan: 0 to add, 0 to change, 2 to destroy.

Terraform will output a plan with resources marked in red, and prefixed with a minus sign, indicating that it will delete the resources in your infrastructure.

Then, use terraform apply to run the plan if you had it in a file or do terraform destroy:

terraform apply terraform.tfplan

terraform destroy \
  -var "do_token=${DO_PAT}"

Terraform will proceed to destroy the resources, as indicated in the generated plan.

# Conclusion

In this tutorial, we used terraform to create a managed digital ocean database instance. We learnt how to create and destroy digital ocean resources. Now that you understand how Terraform works, you can create configuration files that describe a server infrastructure for your own projects.

comments powered by Disqus
Citizix Ltd
Built with Hugo
Theme Stack designed by Jimmy