• Stars
    star
    1,248
  • Rank 36,187 (Top 0.8 %)
  • Language
    Python
  • License
    GNU Lesser Genera...
  • Created about 11 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🐍🐳 Python module to manage Digital Ocean droplets

python-digitalocean

Easy access to Digital Ocean APIs to deploy droplets, images and more.

Build Status

Table of Contents

How to install

You can install python-digitalocean using pip

pip install -U python-digitalocean

or via sources:

python setup.py install

⬆ back to top

Configurations

Specify a custom provider using environment variable

export DIGITALOCEAN_END_POINT=http://example.com/

Specify the DIGITALOCEAN_ACCESS_TOKEN using environment variable

export DIGITALOCEAN_ACCESS_TOKEN='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

Note: Probably want to add the export line above to your .bashrc file.

⬆ back to top

Features

python-digitalocean support all the features provided via digitalocean.com APIs, such as:

  • Get user's Projects
  • Assign a resource to a user project
  • List the resources of user's project
  • Get user's Droplets
  • Get user's Images (Snapshot and Backups)
  • Get public Images
  • Get Droplet's event status
  • Create and Remove a Droplet
  • Create or Delete Reserve IP
  • Create, Add and Remove Tags from Droplets
  • Resize a Droplet
  • Shutdown, restart and boot a Droplet
  • Power off, power on and "power cycle" a Droplet
  • Perform Snapshot
  • Enable/Disable automatic Backups
  • Restore root password of a Droplet

⬆ back to top

##Β Examples

Listing the Projects

This example shows how to list all the projects:

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_projects = manager.get_all_projects()
print(my_projects)

Assign a resource for specific project

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_projects = manager.get_all_projects()
my_projects[0].assign_resource(["do:droplet:<Droplet Number>"])

List all the resources of a project

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_projects = manager.get_all_projects()
resources = my_projects[0].get_all_resources()
print(resources)

Listing the droplets

This example shows how to list all the active droplets:

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_droplets = manager.get_all_droplets()
print(my_droplets)

This example shows how to specify custom provider's end point URL:

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake", end_point="http://example.com/")

⬆ back to top

Listing the droplets by tags

This example shows how to list all the active droplets:

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_droplets = manager.get_all_droplets(tag_name="awesome")
print(my_droplets)

⬆ back to top

Add a tag to a droplet

This example shows how to add a tag to a droplet:

import digitalocean
tag = digitalocean.Tag(token="secretspecialuniquesnowflake", name="tag_name")
tag.create() # create tag if not already created
tag.add_droplets(["DROPLET_ID"])

⬆ back to top

Shutdown all droplets

This example shows how to shutdown all the active droplets:

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_droplets = manager.get_all_droplets()
for droplet in my_droplets:
    droplet.shutdown()

⬆ back to top

Creating a Droplet and checking its status

This example shows how to create a droplet and how to check its status

import digitalocean
droplet = digitalocean.Droplet(token="secretspecialuniquesnowflake",
                               name='Example',
                               region='nyc2', # New York 2
                               image='ubuntu-20-04-x64', # Ubuntu 20.04 x64
                               size_slug='s-1vcpu-1gb',  # 1GB RAM, 1 vCPU
                               backups=True)
droplet.create()

⬆ back to top

Create or Delete Reserved IP

This example shows how to create a reserved ip in specific region and delete it

import digitalocean

floating_ip = digitalocean.FloatingIP(region_slug='nyc2', token="secretspecialuniquesnowflake")
         
# To Create IP
static_ip = floating_ip.reserve()
print(static_ip)

# To Delete IP
release_static_ip = floating_ip.destroy()
print(release_static_ip) # returns True on success
        

⬆ back to top

Checking the status of the droplet

actions = droplet.get_actions()
for action in actions:
    action.load()
    # Once it shows "completed", droplet is up and running
    print(action.status)

⬆ back to top

Listing the Projects

This example shows how to list all the projects:

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_projects = manager.get_all_projects()
print(my_projects)

⬆ back to top

Assign a resource for specific project

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_projects = manager.get_all_projects()
my_projects[0].assign_resource(["do:droplet:<Droplet Number>"])

⬆ back to top

List all the resources of a project

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_projects = manager.get_all_projects()
resources = my_projects[0].get_all_resources()
print(resources)

⬆ back to top

Add SSHKey into DigitalOcean Account

from digitalocean import SSHKey

user_ssh_key = open('/home/<$USER>/.ssh/id_rsa.pub').read()
key = SSHKey(token='secretspecialuniquesnowflake',
             name='uniquehostname',
             public_key=user_ssh_key)
key.create()

⬆ back to top

Creating a new droplet with all your SSH keys

manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
keys = manager.get_all_sshkeys()

droplet = digitalocean.Droplet(token=manager.token,
                               name='DropletWithSSHKeys',
                               region='ams3', # Amster
                               image='ubuntu-20-04-x64', # Ubuntu 20.04 x64
                               size_slug='s-1vcpu-1gb',  # 1GB RAM, 1 vCPU
                               ssh_keys=keys, #Automatic conversion
                               backups=False)
droplet.create()

⬆ back to top

Creating a Firewall

This example creates a firewall that only accepts inbound tcp traffic on port 80 from a specific load balancer and allows outbound tcp traffic on all ports to all addresses.

from digitalocean import Firewall, InboundRule, OutboundRule, Destinations, Sources

inbound_rule = InboundRule(protocol="tcp", ports="80",
                           sources=Sources(
                               load_balancer_uids=[
                                   "4de7ac8b-495b-4884-9a69-1050c6793cd6"]
                               )
                           )

outbound_rule = OutboundRule(protocol="tcp", ports="all",
                             destinations=Destinations(
                               addresses=[
                                   "0.0.0.0/0",
                                   "::/0"]
                                 )
                             )

firewall = Firewall(token="secretspecialuniquesnowflake",
                    name="new-firewall",
                    inbound_rules=[inbound_rule],
                    outbound_rules=[outbound_rule],
                    droplet_ids=[8043964, 8043972])
firewall.create()

⬆ back to top

Listing the domains

This example shows how to list all the active domains:

import digitalocean
TOKEN="secretspecialuniquesnowflake"
manager = digitalocean.Manager(token=TOKEN)
my_domains = manager.get_all_domains()
print(my_domains)

⬆ back to top

Listing records of a domain

This example shows how to list all records of a domain:

import digitalocean
TOKEN="secretspecialuniquesnowflake"
domain = digitalocean.Domain(token=TOKEN, name="example.com")
records = domain.get_records()
for r in records:
    print(r.name, r.domain, r.type, r.data)

⬆ back to top

Creating a domain record

This example shows how to create new domain record (sub.example.com):

import digitalocean
TOKEN="secretspecialuniquesnowflake"
domain = digitalocean.Domain(token=TOKEN, name="example.com")
new_record =  domain.create_new_domain_record(
                type='A',
                name='sub',
                data='93.184.216.34'
                )
print(new_record)

⬆ back to top

Update a domain record

This example shows how to modify an existing domain record (sub.example.com):

import digitalocean
TOKEN="secretspecialuniquesnowflake"
domain = digitalocean.Domain(token=TOKEN, name="example.com")
records = domain.get_records()
id = None
for r in records:
    if r.name == 'sub':
        r.data = '1.1.1.1'
        r.save()

⬆ back to top

Getting account requests/hour limits status

Each request will also include the rate limit information:

import digitalocean
account = digitalocean.Account(token="secretspecialuniquesnowflake").load()
# or
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
account = manager.get_account()

Output:

droplet_limit: 25
email: '[email protected]'
email_verified: True
end_point: 'https://api.digitalocean.com/v2/'
floating_ip_limit: 3
ratelimit_limit: '5000'
ratelimit_remaining: '4995'
ratelimit_reset: '1505378973'
status: 'active'
status_message: ''
token:'my_secret_token'
uuid: 'my_id'

When using the Manager().get_all.. functions, the rate limit will be stored on the manager object:

import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
domains = manager.get_all_domains()

print(manager.ratelimit_limit)

⬆ back to top

Session customization

You can take advantage of the requests library and configure the HTTP client under python-digitalocean.

Configure retries in case of connection error

This example shows how to configure your client to retry 3 times in case of ConnectionError:

import digitalocean
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
retry = Retry(connect=3)
adapter = HTTPAdapter(max_retries=retry)
manager._session.mount('https://', adapter)

See Retry object reference to get more details about all retries options.

Configure a hook on specified answer

This example shows how to launch custom actions if a HTTP 500 occurs:

import digitalocean

def handle_response(response, *args, **kwargs):
    if response.status_code == 500:
        # Make a lot things from the raw response
        pass
    return response

manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
manager._session.hooks['response'].append(handle_response)

See event hooks documentation to get more details about this feature.

⬆ back to top

Testing

Test using Docker

To test this python-digitalocean you can use docker to have a clean environment automatically. First you have to build the container by running in your shell on the repository directory:

docker build -t "pdo-tests" .

Then you can run all the tests (for both python 2 and python 3)

docker run pdo-tests

Note: This will use Ubuntu 14.04 as base and use your repository to run tests. So every time you edit some files, please run these commands to perform tests on your changes.

⬆ back to top

Testing using pytest manually

Use pytest to perform testing. It is recommended to use a dedicated virtualenv to perform tests, using these commands:

$ virtualenv /tmp/digitalocean_env
$ source /tmp/digitalocean_env/bin/activate
$ pip install -r requirements.txt

To run all the tests manually use py.test command:

$ python -m pytest

⬆ back to top

Links

⬆ back to top

More Repositories

1

docker-aliases

πŸ‘Ύ Run commands inside docker containers to keep your OS untouched using bash alias
Shell
103
star
2

wallets

πŸ’°Multi-crypto wallets/keys generator for cold storage with built-in encryption.
Go
56
star
3

backpack

Template system and package manager to deploy Hashicorp Nomad Jobs. Mirror on GitHub, Official repo available on Gitlab.com
Go
18
star
4

django-smartcc

A django Middleware that will help to set cache-control header on the views.
Python
16
star
5

steroids

Steroids is a set of tools to help python developers to build real-time ready, non-blocking, web application reducing efforts and time.
Python
10
star
6

terraforming-bitcoin

Quick and easy setup to build Bitcoin nodes with Terraform on Multiple Locations
HCL
9
star
7

cachet-k8s-cronjob

A simple Kubernetes Cronjob to send custom metrics to Cachet
Shell
5
star
8

siderus-daemon

Daemon for a Peer-to-Peer network system
Python
4
star
9

202003-immutable-infrastructure-vault

Example of Immutable Infrastructure with Vault, using Packer, Terraform, Ansible and AWS
HCL
4
star
10

bitstamp-coffee-bot

Example of a working Bitcoin trading bot for Bitstamp using NodeJS and CoffeeScript
CoffeeScript
4
star
11

OpenProfile

Open your identity to the web
JavaScript
3
star
12

dlike

Decentralized (IPFS/OrbitDB based) Like Widget for any static website. Mirror of GitLab repo
JavaScript
3
star
13

admin-tools

Set of scripts to help administrator to perform some boring stuff wit just some commands.
Shell
2
star
14

torquery

Python module helps to perform a lot of HTTP queries using the onion router.
Python
2
star
15

dockerfiles

Dockerfiles for vault, consul, test-kitchen, etsy-mixer, curl-loader, fwd
HCL
2
star
16

docker-pubssh

My personal docker image with a specific public ssh key.
2
star
17

playbooks

[Moved to GitLab] My Ansible Playbooks
HCL
2
star
18

dhouse

Green Map for renting/selling houses.
JavaScript
2
star
19

fun-blockchain

Writing a blockchain node from scratch, just for fun.
Go
2
star
20

simple-explorer

Simple Explorer is a BIP-37 programmable blockchain explorer.
CoffeeScript
2
star
21

twitch-meme-generator

[GitLab Mirror] Twitch bot to generate meme and display them on the stream
Go
2
star
22

greatdiary

Automatically exported from code.google.com/p/greatdiary
Python
1
star
23

screeps

Screeps.com scripts
JavaScript
1
star
24

mymosaic

Automatically exported from code.google.com/p/mymosaic
PHP
1
star
25

zeronet.io

ZeroNet - Decentralized websites using Bitcoin crypto and BitTorrent network
HTML
1
star
26

easy-rsync-clone

Shell script to clone files into an external device.
Shell
1
star
27

InnLabAffinity

Innovaction Lab Affinity
JavaScript
1
star
28

blog

[Moved to GitLab] My own personal blog.
JavaScript
1
star
29

hk-svcs-bridge

Go HomeKit bridge for Services (SystemD or others)
Go
1
star
30

blog.setale.me

My own personal blog
HTML
1
star
31

koalalorenzo

My GitHub Profile
1
star
32

CacheLayer

URL-Cache layer, to keep live API/URL when unavailable.
Python
1
star
33

PhiFi

Phishing Fighter!
Python
1
star
34

koalalorenzo.github.io

My personal website.
HTML
1
star