/
digital_ocean.py
1231 lines (984 loc) · 35.2 KB
/
digital_ocean.py
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digital_ocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import
import os
import time
import json
import pprint
import logging
import decimal
# Import Salt Libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
import salt.ext.six as six
from salt.ext.six.moves import zip
from salt.ext.six import string_types
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digital_ocean'
# Only load in this module if the DIGITAL_OCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = str(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + str(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = str(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, string_types):
vm_image = str(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = str(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = str(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digital_ocean',
vm_['profile']) is False:
return False
except AttributeError:
pass
# Since using "provider: <provider-engine>" is deprecated, alias provider
# to use driver: "driver: <provider-engine>"
if 'provider' in vm_:
vm_['driver'] = vm_.pop('provider')
salt.utils.cloud.fire_event(
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
{
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
transport=__opts__['transport']
)
log.info('Creating Cloud VM {0}'.format(vm_['name']))
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from {0}".format(vm_['name']))
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="{0}", dns_domain="{1}"'.format(dns_hostname, dns_domain))
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain, dns_hostname, t, d)
log.debug('create_dns_record: {0}'.format(__add_dns_addr__))
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
salt.utils.cloud.fire_event(
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
{'kwargs': kwargs},
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating {0} on DIGITAL_OCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: {1}'.format(
vm_['name'],
str(exc)
),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(str(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found {0} IP{1} interface for "{2}"'.format(facing, addr_family, ip_address))
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug('Found public IP address to use for ssh minion bootstrapping: {0}'.format(vm_['ssh_host']))
vm_['key_filename'] = key_filename
ret = salt.utils.cloud.bootstrap(vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'{0[name]}\''.format(vm_))
log.debug(
'\'{0[name]}\' VM creation details:\n{1}'.format(
vm_, pprint.pformat(data)
)
)
salt.utils.cloud.fire_event(
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
{
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
},
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = str(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
salt.utils.cloud.cache_node(node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'{0}\'. Remaining '
'attempts: {1}'.format(
name, attempts
)
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
items = query(method='account/keys')
ret = {}
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = str(key_pair[item])
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is {0}'.format(keyid))
details = query(method='account/keys', command=keyid)
return details
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
salt.utils.cloud.fire_event(
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
{'name': name},
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for {0}.'.format(name))
destroy_dns_records(name)
# Until the "to do" from line 748 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for {0}.'.format(name))
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : {0}'.format(delete_dns_record))
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: {0}'.format(line))
salt.utils.cloud.fire_event(
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
{'name': name},
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
salt.utils.cloud.delete_minion_cachedir(name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(dns_domain, name, record_type, record_data):
'''
Creates or updates a DNS record for the given name if the domain is managed with DO.
'''
domain = query(method='domains', droplet_id=dns_domain)
if domain:
result = query(
method='domains',
droplet_id=dns_domain,
command='records',
args={'type': record_type, 'name': name, 'data': record_data},
http_method='post'
)
return result
return False
# Delete this with create_dns_record() and delete_dns_record() for Carbon release
__deprecated_fqdn_parsing = lambda fqdn: ('.'.join(fqdn.split('.')[-2:]), '.'.join(fqdn.split('.')[:-2]))
def create_dns_record(hostname, ip_address):
salt.utils.warn_until(
'Carbon',
'create_dns_record() is deprecated and will be removed in Carbon. Please use post_dns_record() instead.'
)
return __deprecated_create_dns_record(hostname, ip_address)
def __deprecated_create_dns_record(hostname, ip_address):
domainname, subdomain = __deprecated_fqdn_parsing(hostname)
domain = query(method='domains', droplet_id=domainname)
if domain:
result = query(
method='domains',
droplet_id=domainname,
command='records',
args={'type': 'A', 'name': subdomain, 'data': ip_address},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
response = query(method='domains', droplet_id=domain, command='records')
log.debug("found DNS records: {0}".format(pprint.pformat(response)))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: {0}".format(repr(record_ids)))
for id in record_ids:
try:
log.info('deleting DNS record {0}'.format(id))
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain {0} record ID {1}.'.format(domain, hostname))
log.debug('DNS deletion REST call returned: {0}'.format(pprint.pformat(ret)))
return False
def delete_dns_record(hostname):
salt.utils.warn_until(
'Carbon',
'delete_dns_record() is deprecated and will be removed in Carbon. Please use destroy_dns_records() instead.'
)
return __deprecated_delete_dns_record(hostname)
def __deprecated_delete_dns_record(hostname):
'''
Deletes a DNS for the given hostname if the domain is managed with DO.
'''
domainname, subdomain = __deprecated_fqdn_parsing(hostname)
records = query(method='domains', droplet_id=domainname, command='records')
if records:
for record in records['domain_records']:
if record['name'] == subdomain:
return query(
method='domains',
droplet_id=domainname,
command='records/' + str(record['id']),
http_method='delete'
)
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Digital Ocean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digital_ocean':
return {'Error': 'The requested profile does not belong to Digital Ocean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
... code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + str(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
... code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False