Back to articles
DevOps & Systems

Automating VPS Snapshot Backup and Shutdown for Green DevOps

This technical guide details how to build a Python script to automatically backup snapshots and power off all testing VPS instances on weekends, reducing cloud costs by up to 30%....

DPTCloud Engineering5 min read
Automating VPS Snapshot Backup and Shutdown for Green DevOps

Image credit: wikimedia

This technical guide details how to build a Python script to automatically backup snapshots and power off all testing VPS instances on weekends, reducing cloud costs by up to 30%. The script ensures data protection and rapid system recovery while minimizing operational expenses. It includes environment setup, Python code, cron configuration, and verification steps for stable execution.

Green DevOps and Cloud Cost Optimization

Green DevOps emphasizes resource efficiency and cost reduction alongside system performance and reliability. As cloud costs rise, powering down unused infrastructure—such as testing VPS instances during weekends—becomes a practical strategy. Testing VPS environments typically run all week but are only needed during work hours. Automating snapshot backups and shutdowns enables significant savings without impacting development workflows.

This guide uses Python to create a script that performs two key tasks: (1) backs up snapshots of all testing VPS instances before shutdown, and (2) powers off the instances on weekends. The script can be deployed on any machine with access to the VPS provider’s API (e.g., DigitalOcean, Linode, or similar platforms).

Environment Setup and Requirements

To implement this script, you need the following prerequisites:

  • Python 3.8 or higher
  • VPS provider API key (e.g., DigitalOcean, Linode)
  • Python libraries: `requests` for API calls and `schedule` for task scheduling
  • Access to a control server (VPS or personal computer)

Install the required libraries using pip:

pip install requests schedule

Create a Python file named auto_backup_shutdown.py to begin writing the script.

Writing the Python Automation Script

The script below uses DigitalOcean’s API as an example. Adjust the URL and API configuration for other platforms.

import requests\nimport time\nimport schedule\nfrom datetime import datetime, timedelta\n\n# API configuration\nAPI_KEY = 'your_digitalocean_api_key'\nBASE_URL = 'https://api.digitalocean.com/v2'\n\n# List of testing VPS IDs (can be IDs or names)\nTEST_VPS_IDS = ['vps-test-1', 'vps-test-2', 'vps-test-3']\n\n# Function to create snapshot\ndef backup_snapshot(vps_id):\n    url = f\"{BASE_URL}/droplets/{vps_id}/actions\"\n    headers = {\n        'Content-Type': 'application/json',\n        'Authorization': f'Bearer {API_KEY}'\n    }\n    data = {\n        'type': 'snapshot',\n        'name': f'snapshot-{vps_id}-{datetime.now().strftime(\"%Y%m%d\")}'\n    }\n    response = requests.post(url, headers=headers, json=data)\n    if response.status_code == 201:\n        print(f\"Snapshot created for VPS {vps_id}\")\n    else:\n        print(f\"Error creating snapshot for VPS {vps_id}: {response.text}\")\n\n# Function to power off VPS\ndef shutdown_vps(vps_id):\n    url = f\"{BASE_URL}/droplets/{vps_id}/actions\"\n    headers = {\n        'Content-Type': 'application/json',\n        'Authorization': f'Bearer {API_KEY}'\n    }\n    data = {\n        'type': 'power_off'\n    }\n    response = requests.post(url, headers=headers, json=data)\n    if response.status_code == 201:\n        print(f\"VPS {vps_id} powered off\")\n    else:\n        print(f\"Error powering off VPS {vps_id}: {response.text}\")\n\n# Main function: backup and shutdown on weekends\ndef run_weekend_shutdown():\n    # Check if it's weekend\n    now = datetime.now()\n    if now.weekday() == 5 or now.weekday() == 6:  # Saturday or Sunday\n        print(\"Starting snapshot backup and VPS shutdown...\")\n        for vps_id in TEST_VPS_IDS:\n            backup_snapshot(vps_id)\n            shutdown_vps(vps_id)\n        print(\"Completed snapshot backup and VPS shutdown.\")\n    else:\n        print(\"Not weekend. No action taken.\")\n\n# Schedule script to run daily at 23:59\nschedule.every().day.at(\"23:59\").do(run_weekend_shutdown)\n\n# Run the script\nif __name__ == \"__main__\":\n    while True:\n        schedule.run_pending()\n        time.sleep(60)  # Check every minute\n

In the code:

  • API_KEY is your access key to the DigitalOcean account.
  • TEST_VPS_IDS contains the IDs or names of the testing VPS instances.
  • backup_snapshot() calls the API to create a snapshot.
  • shutdown_vps() powers off the VPS via the power_off action.
  • run_weekend_shutdown() checks the day and only executes actions on weekends.

Testing and Troubleshooting

After deploying the script, verify its operation:

  • Run the script manually to confirm snapshots are created and VPS instances are powered off.
  • Ensure the API key has full access to the testing VPS instances.
  • Monitor logs for errors, such as connection issues, permission denials, or API rate limits.
  • If errors occur, check the API error codes and adjust the script accordingly.

To avoid rate-limiting errors, add delays between API calls or implement exponential backoff.

References and Resources

For more information on VPS platforms and their APIs, refer to:

This practical technical guide helps businesses apply Green DevOps principles to reduce cloud costs effectively. The Python script can be adapted for various platforms and integrated into existing automation systems.

DPTCloud Tier III Infrastructure

Recommended NVMe Cloud VPS Plans to Deploy This Setup

Enterprise RAID 10 NVMe SSDs, CMC & FPT District 9 uplinks with Anycast Anti-DDoS and 99.99% SLA.

View 22 VPS Plans
ECO · vn-02

VPS-2E

94.600 ₫ / mo

10% VAT included

  • CPU: 2 vCPU
  • RAM: 2 GB
  • SSD: 30 GB NVMe
ECO · vn-02Recommended

VPS-3E

170.500 ₫ / mo

10% VAT included

  • CPU: 2 vCPU
  • RAM: 4 GB
  • SSD: 50 GB NVMe
BASIC · vn-01Recommended

VPS-05

457.600 ₫ / mo

10% VAT included

  • CPU: 4 vCPU
  • RAM: 8 GB
  • SSD: 50 GB NVMe

Related Articles

View all
ZaloZalo SupportDiscord0384 753 478