Digital-Ocean
Droplets API

Professional Guide: Automating DigitalOcean Droplet Setup Using Python

In this guide, we will explore how to use Python to automate the creation and management of DigitalOcean droplets via their API. This walkthrough includes secure API token management, creating multiple droplets, and organizing the project in a professional and scalable way. By the end of this guide, you’ll have the ability to deploy and manage multiple cloud servers in just a few lines of code.


Prerequisites

Before proceeding, ensure the following:

  1. DigitalOcean Account: You need an active DigitalOcean (opens in a new tab) account.
  2. Python Installed: Python 3.x must be installed on your machine.
  3. DigitalOcean API Token: Obtain an API token from your DigitalOcean dashboard under API > Tokens/Keys.
  4. Basic Understanding of Python: You should be comfortable with basic Python scripting.

Step 1: Install Required Python Packages

First, you need to install the necessary Python libraries. We’ll use python-digitalocean to interact with DigitalOcean’s API and python-dotenv to handle environment variables.

Run the following command to install them:

pip install python-digitalocean python-dotenv

Step 2: Set Up Environment Variables

To avoid hardcoding your DigitalOcean API token into your scripts, we’ll store it in an environment file (.env). This is a good practice to protect sensitive data.

  1. Create a .env file in your project directory and add your API token:
DIGITALOCEAN_API_TOKEN=your_api_token_here
  1. Load this token in your Python script using the python-dotenv library.

Step 3: Creating a Python Script for Droplet Management

Let’s create a Python script that will interact with the DigitalOcean API to create droplets. This script will handle creating multiple droplets simultaneously and display their details once created.

1. Create the Project Structure

To maintain a clean and scalable project, structure your files as follows:

/digitalocean-droplet-manager
├── /scripts
│   ├── create_droplets.py       # Script for creating multiple droplets
│   ├── list_droplets.py         # Script for listing all droplets
│   └── delete_droplet.py        # Script for deleting a specific droplet
├── /config
│   └── .env                     # Environment file for API token
├── /logs                        # Optional: Directory for logs
├── requirements.txt             # List of Python dependencies
└── README.md                    # Project documentation

2. Creating Multiple Droplets Script

Let’s write the main script create_droplets.py that allows you to create multiple droplets at once.

import os
import digitalocean
from dotenv import load_dotenv
 
# Load the API token from the .env file
load_dotenv()
api_token = os.getenv('DIGITALOCEAN_API_TOKEN')
 
# Initialize the API Manager
manager = digitalocean.Manager(token=api_token)
 
# Function to create a single droplet
def create_droplet(name, region, size, image):
    droplet = digitalocean.Droplet(
        token=api_token,
        name=name,
        region=region,
        image=image,
        size_slug=size,
        backups=False
    )
    droplet.create()
    return droplet
 
# Function to create multiple droplets
def create_multiple_droplets(names, region="nyc3", size="s-1vcpu-1gb", image="ubuntu-20-04-x64"):
    droplets = []
    for name in names:
        print(f"Creating droplet: {name}...")
        droplet = create_droplet(name, region, size, image)
        droplets.append(droplet)
    return droplets
 
# Droplet names to be created
droplet_names = ["app-server-1", "app-server-2", "db-server"]
 
# Create multiple droplets
droplets = create_multiple_droplets(droplet_names)
 
# Wait for each droplet to be fully created and fetch details
for droplet in droplets:
    actions = droplet.get_actions()
    for action in actions:
        action.load()
        print(f"Action {action.type} for droplet {droplet.name}: {action.status}")

3. How It Works

  • The create_multiple_droplets function accepts a list of names and creates droplets for each one.
  • You can specify additional parameters such as the region (region), droplet size (size), and image (image), with default values of nyc3, s-1vcpu-1gb, and ubuntu-20-04-x64.
  • Once droplets are created, the script prints out the status of each creation action.

Step 4: List All Droplets

Now that we’ve created multiple droplets, it’s time to fetch their details. We’ll create a script to list all active droplets, showing key information such as names, IDs, and IP addresses.

list_droplets.py

import os
import digitalocean
from dotenv import load_dotenv
 
# Load the API token
load_dotenv()
api_token = os.getenv('DIGITALOCEAN_API_TOKEN')
 
# Initialize the API Manager
manager = digitalocean.Manager(token=api_token)
 
# Fetch all droplets
droplets = manager.get_all_droplets()
 
# Display droplet details
for droplet in droplets:
    print(f"Droplet Name: {droplet.name}")
    print(f"ID: {droplet.id}")
    print(f"IP Address: {droplet.ip_address}")
    print(f"Status: {droplet.status}")
    print("-" * 40)

Step 5: Deleting a Droplet

Finally, we’ll create a script to delete a specific droplet. This script will take a droplet ID as input and remove it from your account.

delete_droplet.py

import os
import digitalocean
from dotenv import load_dotenv
 
# Load the API token
load_dotenv()
api_token = os.getenv('DIGITALOCEAN_API_TOKEN')
 
# Initialize the API Manager
manager = digitalocean.Manager(token=api_token)
 
# Get the droplet ID to delete
droplet_id = int(input("Enter the droplet ID to delete: "))
 
# Fetch and delete the droplet
droplet = manager.get_droplet(droplet_id)
droplet.destroy()
 
print(f"Droplet with ID {droplet_id} has been deleted.")

Step 6: Running the Scripts

To execute these scripts, open your terminal in the project directory and run the following:

  1. Creating Droplets:
python scripts/create_droplets.py

This will create multiple droplets and display the status of their creation.

  1. Listing Droplets:
python scripts/list_droplets.py

This will list all existing droplets along with their details.

  1. Deleting a Droplet:
python scripts/delete_droplet.py

Enter the droplet ID you want to delete when prompted.


Step 7: Project Organization and Best Practices

To make your project easy to maintain, follow these best practices:

  1. Use Environment Variables: Store sensitive information, such as API tokens, in environment variables or configuration files (.env).
  2. Logging: Consider adding logging functionality to keep track of actions and errors.
  3. Documentation: Update your README.md to include instructions for other users or contributors.

Sample README.md:

# DigitalOcean Droplet Manager
 
A Python-based tool for creating, listing, and deleting DigitalOcean droplets using the DigitalOcean API.
 
## Prerequisites
 
- Python 3.x
- DigitalOcean API token
 
## Setup
 
1. Clone the repository.
2. Install dependencies:
 
```bash copy
pip install -r requirements.txt
  1. Add your DigitalOcean API token to the .env file:
DIGITALOCEAN_API_TOKEN=your_api_token_here

Scripts

  • create_droplets.py: Creates multiple droplets.
  • list_droplets.py: Lists all droplets and their details.
  • delete_droplet.py: Deletes a specific droplet by ID.

Running the Scripts

  • To create droplets:
python scripts/create_droplets.py
  • To list droplets:
python scripts/list_droplets.py
  • To delete a droplet:
python scripts/delete_droplet.py

---

### Conclusion

You now have a complete, professional setup for managing DigitalOcean droplets using Python. You’ve learned how to:

1. Securely store and manage API tokens.
2. Create multiple droplets programmatically.
3. List and manage existing droplets.
4. Delete droplets when they are no longer needed.

This setup can be extended for more advanced use cases, such as monitoring, scaling, or integrating with deployment pipelines.