项目作者: koalalorenzo

项目描述 :
🐍🐳 Python module to manage Digital Ocean droplets
高级语言: Python
项目地址: git://github.com/koalalorenzo/python-digitalocean.git
创建时间: 2013-02-13T11:09:49Z
项目社区:https://github.com/koalalorenzo/python-digitalocean

开源协议:GNU Lesser General Public License v3.0

下载


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

  1. pip install -U python-digitalocean

or via sources:

  1. python setup.py install

⬆ back to top

Configurations

Specify a custom provider using environment variable

  1. export DIGITALOCEAN_END_POINT=http://example.com/

Specify the DIGITALOCEAN_ACCESS_TOKEN using environment variable

  1. 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:

  1. import digitalocean
  2. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  3. my_projects = manager.get_all_projects()
  4. print(my_projects)

Assign a resource for specific project

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

List all the resources of a project

  1. import digitalocean
  2. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  3. my_projects = manager.get_all_projects()
  4. resources = my_projects[0].get_all_resources()
  5. print(resources)

Listing the droplets

This example shows how to list all the active droplets:

  1. import digitalocean
  2. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  3. my_droplets = manager.get_all_droplets()
  4. print(my_droplets)

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

  1. import digitalocean
  2. 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:

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

⬆ back to top

Add a tag to a droplet

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

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

⬆ back to top

Shutdown all droplets

This example shows how to shutdown all the active droplets:

  1. import digitalocean
  2. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  3. my_droplets = manager.get_all_droplets()
  4. for droplet in my_droplets:
  5. 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

  1. import digitalocean
  2. droplet = digitalocean.Droplet(token="secretspecialuniquesnowflake",
  3. name='Example',
  4. region='nyc2', # New York 2
  5. image='ubuntu-20-04-x64', # Ubuntu 20.04 x64
  6. size_slug='s-1vcpu-1gb', # 1GB RAM, 1 vCPU
  7. backups=True)
  8. 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

  1. import digitalocean
  2. floating_ip = digitalocean.FloatingIP(region_slug='nyc2', token="secretspecialuniquesnowflake")
  3. # To Create IP
  4. static_ip = floating_ip.reserve()
  5. print(static_ip)
  6. # To Delete IP
  7. release_static_ip = floating_ip.destroy()
  8. print(release_static_ip) # returns True on success

⬆ back to top

Checking the status of the droplet

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

⬆ back to top

Listing the Projects

This example shows how to list all the projects:

  1. import digitalocean
  2. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  3. my_projects = manager.get_all_projects()
  4. print(my_projects)

⬆ back to top

Assign a resource for specific project

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

⬆ back to top

List all the resources of a project

  1. import digitalocean
  2. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  3. my_projects = manager.get_all_projects()
  4. resources = my_projects[0].get_all_resources()
  5. print(resources)

⬆ back to top

Add SSHKey into DigitalOcean Account

  1. from digitalocean import SSHKey
  2. user_ssh_key = open('/home/<$USER>/.ssh/id_rsa.pub').read()
  3. key = SSHKey(token='secretspecialuniquesnowflake',
  4. name='uniquehostname',
  5. public_key=user_ssh_key)
  6. key.create()

⬆ back to top

Creating a new droplet with all your SSH keys

  1. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  2. keys = manager.get_all_sshkeys()
  3. droplet = digitalocean.Droplet(token=manager.token,
  4. name='DropletWithSSHKeys',
  5. region='ams3', # Amster
  6. image='ubuntu-20-04-x64', # Ubuntu 20.04 x64
  7. size_slug='s-1vcpu-1gb', # 1GB RAM, 1 vCPU
  8. ssh_keys=keys, #Automatic conversion
  9. backups=False)
  10. 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.

  1. from digitalocean import Firewall, InboundRule, OutboundRule, Destinations, Sources
  2. inbound_rule = InboundRule(protocol="tcp", ports="80",
  3. sources=Sources(
  4. load_balancer_uids=[
  5. "4de7ac8b-495b-4884-9a69-1050c6793cd6"]
  6. )
  7. )
  8. outbound_rule = OutboundRule(protocol="tcp", ports="all",
  9. destinations=Destinations(
  10. addresses=[
  11. "0.0.0.0/0",
  12. "::/0"]
  13. )
  14. )
  15. firewall = Firewall(token="secretspecialuniquesnowflake",
  16. name="new-firewall",
  17. inbound_rules=[inbound_rule],
  18. outbound_rules=[outbound_rule],
  19. droplet_ids=[8043964, 8043972])
  20. firewall.create()

⬆ back to top

Listing the domains

This example shows how to list all the active domains:

  1. import digitalocean
  2. TOKEN="secretspecialuniquesnowflake"
  3. manager = digitalocean.Manager(token=TOKEN)
  4. my_domains = manager.get_all_domains()
  5. print(my_domains)

⬆ back to top

Listing records of a domain

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

  1. import digitalocean
  2. TOKEN="secretspecialuniquesnowflake"
  3. domain = digitalocean.Domain(token=TOKEN, name="example.com")
  4. records = domain.get_records()
  5. for r in records:
  6. 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):

  1. import digitalocean
  2. TOKEN="secretspecialuniquesnowflake"
  3. domain = digitalocean.Domain(token=TOKEN, name="example.com")
  4. new_record = domain.create_new_domain_record(
  5. type='A',
  6. name='sub',
  7. data='93.184.216.34'
  8. )
  9. print(new_record)

⬆ back to top

Update a domain record

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

  1. import digitalocean
  2. TOKEN="secretspecialuniquesnowflake"
  3. domain = digitalocean.Domain(token=TOKEN, name="example.com")
  4. records = domain.get_records()
  5. id = None
  6. for r in records:
  7. if r.name == 'sub':
  8. r.data = '1.1.1.1'
  9. r.save()

⬆ back to top

Getting account requests/hour limits status

Each request will also include the rate limit information:

  1. import digitalocean
  2. account = digitalocean.Account(token="secretspecialuniquesnowflake").load()
  3. # or
  4. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  5. account = manager.get_account()

Output:

  1. droplet_limit: 25
  2. email: 'name@domain.me'
  3. email_verified: True
  4. end_point: 'https://api.digitalocean.com/v2/'
  5. floating_ip_limit: 3
  6. ratelimit_limit: '5000'
  7. ratelimit_remaining: '4995'
  8. ratelimit_reset: '1505378973'
  9. status: 'active'
  10. status_message: ''
  11. token:'my_secret_token'
  12. uuid: 'my_id'

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

  1. import digitalocean
  2. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  3. domains = manager.get_all_domains()
  4. 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:

  1. import digitalocean
  2. import requests
  3. from requests.adapters import HTTPAdapter
  4. from requests.packages.urllib3.util.retry import Retry
  5. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  6. retry = Retry(connect=3)
  7. adapter = HTTPAdapter(max_retries=retry)
  8. 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:

  1. import digitalocean
  2. def handle_response(response, *args, **kwargs):
  3. if response.status_code == 500:
  4. # Make a lot things from the raw response
  5. pass
  6. return response
  7. manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
  8. 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:

  1. docker build -t "pdo-tests" .

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

  1. 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:

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

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

  1. $ python -m pytest

⬆ back to top

⬆ back to top