Provision a Backup via Terraform

Provision a Backup via Terraform

This section provides a clear, step-by-step guide to automating the creation of a MongoDB node backup on 123cluster using Terraform and the Mastercard/restapi provider. You’ll learn how to copy the REST API command from the UI, convert it to parameterized Terraform code, and integrate it into your CI/CD workflow for repeatable, auditable backup automation.

Step 1: Copy the curl Command from the UI
On the Create backup page for your MongoDB node, click { REST API }. You’ll copy a command such as:

curl -v \
  -H "Authorization: Bearer <YOUR_JWT_TOKEN>" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "node_id":     "<MONGO_HOST_ADDRESS>:<MONGO_HOST_PORT>",
    "schedule":    false,
    "compress":    false,
    "backup_path": "<BACKUP_PATH>",
    "keep_days":   3,
    "rest_api":    true
  }' \
  <API_BASE_URL>/backup_mongo_node/

Step 2: Parse the curl Command

  • Authorization header: Extract the JWT token after Bearer.
  • Content-Type & Accept: Both must be application/json.
  • Payload fields:
    • node_id (format: <host>:<port>)
    • schedule (boolean)
    • compress (boolean)
    • backup_path (string, absolute server path)
    • keep_days (integer)
    • rest_api (boolean)
  • Endpoint:
    • Base URI: <API_BASE_URL>
    • Resource path: /backup_mongo_node/

Step 3: Translate into Terraform

  • Create directory & file:
integration/
└── terraform/
    └── create_database/
        └── main.tf
  • Provider block
// Terraform configuration for automating MongoDB node backup on 123cluster
terraform {
  required_providers {
    restapi = {
      source  = "Mastercard/restapi"
      version = "1.19.1" // Lock provider version for consistency
    }
  }
}

/*
  REST API provider configuration:
  - uri: Base API endpoint for 123cluster.
  - headers: Set JWT and content type.
  - write_returns_object: Output as object.
  - debug: Enables request/response logging.
  - HTTP methods: POST for all actions.
*/
provider "restapi" {
  uri                  = "<API_BASE_URL>"
  write_returns_object = true
  debug                = true
  headers = {
    Authorization = "Bearer <YOUR_JWT_TOKEN>" // Use a valid, secure JWT token
    Content-Type  = "application/json"
    Accept        = "application/json"
  }
  create_method  = "POST"
  update_method  = "POST"
  destroy_method = "POST"
}
  • Variable declarations
/*
  Use variables for all inputs to keep the configuration reusable, portable, and CI/CD-ready.
*/

variable "mongo_host_address" {
  description = "Address (IP or FQDN) of the MongoDB host"
  type        = string
  default     = "<MONGO_HOST_ADDRESS>"
}

variable "mongo_host_port" {
  description = "Port on which MongoDB is listening"
  type        = string
  default     = "<MONGO_HOST_PORT>"
}

variable "backup_path" {
  description = "Path on the server to store backup files"
  type        = string
  default     = "/backups/mongo/backups"
}

variable "schedule" {
  description = "Whether to schedule the backup"
  type        = bool
  default     = false
}

variable "compress" {
  description = "Whether to compress the backup"
  type        = bool
  default     = false
}

variable "keep_days" {
  description = "Number of days to keep the backup"
  type        = number
  default     = 3
}
  • Resource definition
/*
  Resource for triggering MongoDB node backup via REST API.
  - All fields are parameterized for flexibility and automation.
*/
resource "restapi_object" "create_backup" {
  path = "/backup_mongo_node/"
  data = jsonencode({
    node_id     = "${var.mongo_host_address}:${var.mongo_host_port}"
    schedule    = var.schedule
    compress    = var.compress
    backup_path = var.backup_path
    keep_days   = var.keep_days
    rest_api    = true
  })
}
  • Output block
/*
  Output the full API JSON response after backup creation.
  Useful for CI/CD logs, monitoring, or chaining further automation.
*/
output "backup_response" {
  description = "Raw JSON response from backup_mongo_node"
  value       = restapi_object.create_backup.data
}

Step 4: Initialize & Apply

cd integration/terraform/create_backup

# Initialize the Terraform working directory and download necessary providers
terraform init

# Apply the configuration, review the planned actions, and confirm execution
terraform apply

# Output the API response for logging or integration with other tools
terraform output backup_response


Additional Guidance & Best Practices

  • Parameterization: Expose all user- and environment-specific values as Terraform variables for portable, reusable code across clusters and projects.
  • Security: Store sensitive values (API tokens, credentials) securely—prefer environment variables, secret managers, or the sensitive attribute in Terraform.
  • CI/CD Integration: Embed this workflow into your CI/CD pipeline for automated, traceable, and consistent backup operations.
  • API Versioning: Always validate endpoints and payload structures against the current 123cluster API documentation for compatibility.
  • Logging & Outputs: Use Terraform outputs to capture and log API responses, providing audit trails and integration points for further automation.
  • Environment Isolation: Use Terraform workspaces to safely separate development, staging, and production operations.
  • Error Handling: Implement error detection in your pipeline to manage API failures and trigger alerts if backups do not complete as expected.