Codebase list python-digitalocean / HEAD
HEAD

Tree @HEAD (Download .tar.gz)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
<h1 align="center">python-digitalocean</h1>
<p align="center">Easy access to Digital Ocean APIs to deploy droplets, images and more.</p>

<p align="center">
<a href="https://travis-ci.org/koalalorenzo/python-digitalocean"><img src="https://travis-ci.org/koalalorenzo/python-digitalocean.svg" alt="Build Status"></a>
<a href="https://github.com/koalalorenzo/python-digitalocean"><img src="https://img.shields.io/github/forks/koalalorenzo/python-digitalocean.svg?style=social&label=Fork"></a>
<a href="https://github.com/koalalorenzo/python-digitalocean"><img src="https://img.shields.io/github/stars/koalalorenzo/python-digitalocean.svg?style=social&label=Star"></a>
<a href="https://github.com/koalalorenzo/python-digitalocean"><img src="https://img.shields.io/github/watchers/koalalorenzo/python-digitalocean.svg?style=social&label=Watch"></a>
</p>

## Table of Contents

- [How to install](#how-to-install)
- [Configurations](#configurations)
- [Features](#features)
- [Examples](#examples)
   - [Listing the droplets](#listing-the-droplets)
   - [Listing the droplets by tags](#listing-the-droplets-by-tags)
   - [Add a tag to a droplet](#add-a-tag-to-a-droplet)
   - [Shutdown all droplets](#shutdown-all-droplets)
   - [Creating a Droplet and checking its status](#creating-a-droplet-and-checking-its-status)
   - [Checking the status of the droplet](#checking-the-status-of-the-droplet)
   - [Listing the Projects](#listing-the-projects)
   - [Assign a resource for specific project](#assigne-a-resource-for-specific-project)
   - [List all the resources of a project](#list-all-the-resources-of-a-project)
   - [Add SSHKey into DigitalOcean Account](#add-sshkey-into-digitalocean-account)
   - [Creating a new droplet with all your SSH keys](#creating-a-new-droplet-with-all-your-ssh-keys)
   - [Creating a Firewall](#creating-a-firewall)
   - [Listing the domains](#listing-the-domains)
   - [Listing records of a domain](#listing-records-of-a-domain)
   - [Creating a domain record](#creating-a-domain-record)
   - [Update a domain record](#update-a-domain-record)
- [Getting account requests/hour limits status](#getting-account-requestshour-limits-status)
- [Session customization](#session-customization)
- [Testing](#testing)
   - [Test using Docker](#test-using-docker)
   - [Testing using pytest manually](#testing-using-pytest-manually)
- [Links](#links)

## 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](#table-of-contents)**

## 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](#table-of-contents)**

## 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, 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](#table-of-contents)**

## Examples
### Listing the droplets

This example shows how to list all the active droplets:

```python
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:

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

**[⬆ back to top](#table-of-contents)**

### Listing the droplets by tags

This example shows how to list all the active droplets:

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

**[⬆ back to top](#table-of-contents)**

### Add a tag to a droplet

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

```python
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](#table-of-contents)**

### Shutdown all droplets

This example shows how to shutdown all the active droplets:

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

**[⬆ back to top](#table-of-contents)**

### Creating a Droplet and checking its status

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

```python
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](#table-of-contents)**

### Checking the status of the droplet
```python
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](#table-of-contents)**

### Listing the Projects

This example shows how to list all the projects:

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

**[⬆ back to top](#table-of-contents)**

### Assign a resource for specific project

```python
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](#table-of-contents)**

### List all the resources of a project
```python
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](#table-of-contents)**

### Add SSHKey into DigitalOcean Account
```python
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](#table-of-contents)**

### Creating a new droplet with all your SSH keys
```python
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](#table-of-contents)**

### Creating a Firewall

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

```python
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](#table-of-contents)**

### Listing the domains

This example shows how to list all the active domains:

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

**[⬆ back to top](#table-of-contents)**

### Listing records of a domain

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

```python
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](#table-of-contents)**

### Creating a domain record

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

```python
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](#table-of-contents)**

### Update a domain record

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

```python
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 == 'usb':
        r.data = '1.1.1.1'
        r.save()
```

**[⬆ back to top](#table-of-contents)**

## Getting account requests/hour limits status

Each request will also include the rate limit information:

```python
import digitalocean
account = digitalocean.Account(token="secretspecialuniquesnowflake").load()
# or
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
account = manager.get_account()
```
Output:
```text
droplet_limit: 25
email: 'name@domain.me'
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:
 ```python
import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
domains = manager.get_all_domains()

print(manager.ratelimit_limit)
```

**[⬆ back to top](#table-of-contents)**

## Session customization

You can take advandtage of the [requests](http://docs.python-requests.org/en/master/) 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`:
```python
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`](https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.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:

```python
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](http://docs.python-requests.org/en/master/user/advanced/?highlight=HTTPAdapter#event-hooks) to get more details about this feature.

**[⬆ back to top](#table-of-contents)**

## Testing

### Test using Docker
To test this python-digitalocean you can use [docker](https://www.docker.com) 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](#table-of-contents)**

### Testing using pytest manually
Use [pytest](http://pytest.org/) 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](#table-of-contents)**

## Links

  * GitHub: [https://github.com/koalalorenzo/python-digitalocean](https://github.com/koalalorenzo/python-digitalocean)
  * PyPI page: [https://pypi.python.org/pypi/python-digitalocean/](https://pypi.python.org/pypi/python-digitalocean/)
  * Author Website: [http://who.is.lorenzo.setale.me/?](http://setale.me/)
  * Author Blog: [http://blog.setale.me/](http://blog.setale.me/)

**[⬆ back to top](#table-of-contents)**