-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
ec2.py
4195 lines (3447 loc) · 129 KB
/
ec2.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 -*-
'''
The EC2 Cloud Module
====================
The EC2 cloud module is used to interact with the Amazon Elastic Cloud
Computing.
To use the EC2 cloud module, set up the cloud configuration at
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/ec2.conf``:
.. code-block:: yaml
my-ec2-config:
# The EC2 API authentication id, set this and/or key to
# 'use-instance-role-credentials' to use the instance role credentials
# from the meta-data if running on an AWS instance
id: GKTADJGHEIQSXMKKRBJ08H
# The EC2 API authentication key, set this and/or id to
# 'use-instance-role-credentials' to use the instance role credentials
# from the meta-data if running on an AWS instance
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# The ssh keyname to use
keyname: default
# The amazon security group
securitygroup: ssh_open
# The location of the private key which corresponds to the keyname
private_key: /root/default.pem
# Be default, service_url is set to amazonaws.com. If you are using this
# driver for something other than Amazon EC2, change it here:
service_url: amazonaws.com
# The endpoint that is ultimately used is usually formed using the region
# and the service_url. If you would like to override that entirely, you
# can explicitly define the endpoint:
endpoint: myendpoint.example.com:1138/services/Cloud
# SSH Gateways can be used with this provider. Gateways can be used
# when a salt-master is not on the same private network as the instance
# that is being deployed.
# Defaults to None
# Required
ssh_gateway: gateway.example.com
# Defaults to port 22
# Optional
ssh_gateway_port: 22
# Defaults to root
# Optional
ssh_gateway_username: root
# One authentication method is required. If both
# are specified, Private key wins.
# Private key defaults to None
ssh_gateway_private_key: /path/to/key.pem
# Password defaults to None
ssh_gateway_password: ExamplePasswordHere
provider: ec2
:depends: requests
'''
# pylint: disable=invalid-name,function-redefined
# Import python libs
from __future__ import absolute_import
import os
import sys
import stat
import time
import uuid
import pprint
import logging
import yaml
# Import libs for talking to the EC2 API
import hmac
import hashlib
import binascii
import datetime
import base64
import msgpack
import json
import re
import decimal
# Import 3rd-party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
import salt.ext.six as six
from salt.ext.six.moves import map, range, zip
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse, urlencode as _urlencode
# Try to import PyCrypto, which may not be installed on a RAET-based system
try:
import Crypto
# PKCS1_v1_5 was added in PyCrypto 2.5
from Crypto.Cipher import PKCS1_v1_5 # pylint: disable=E0611
from Crypto.Hash import SHA # pylint: disable=E0611,W0611
HAS_PYCRYPTO = True
except ImportError:
HAS_PYCRYPTO = False
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Import salt libs
import salt.utils
from salt import syspaths
from salt._compat import ElementTree as ET
import salt.utils.http as http
import salt.utils.aws as aws
# Import salt.cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import (
SaltCloudException,
SaltCloudSystemExit,
SaltCloudConfigError,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure
)
# Get logging started
log = logging.getLogger(__name__)
SIZE_MAP = {
'Micro Instance': 't1.micro',
'Small Instance': 'm1.small',
'Medium Instance': 'm1.medium',
'Large Instance': 'm1.large',
'Extra Large Instance': 'm1.xlarge',
'High-CPU Medium Instance': 'c1.medium',
'High-CPU Extra Large Instance': 'c1.xlarge',
'High-Memory Extra Large Instance': 'm2.xlarge',
'High-Memory Double Extra Large Instance': 'm2.2xlarge',
'High-Memory Quadruple Extra Large Instance': 'm2.4xlarge',
'Cluster GPU Quadruple Extra Large Instance': 'cg1.4xlarge',
'Cluster Compute Quadruple Extra Large Instance': 'cc1.4xlarge',
'Cluster Compute Eight Extra Large Instance': 'cc2.8xlarge',
}
EC2_LOCATIONS = {
'ap-northeast-1': 'ec2_ap_northeast',
'ap-southeast-1': 'ec2_ap_southeast',
'ap-southeast-2': 'ec2_ap_southeast_2',
'eu-west-1': 'ec2_eu_west',
'sa-east-1': 'ec2_sa_east',
'us-east-1': 'ec2_us_east',
'us-west-1': 'ec2_us_west',
'us-west-2': 'ec2_us_west_oregon',
}
DEFAULT_LOCATION = 'us-east-1'
DEFAULT_EC2_API_VERSION = '2014-10-01'
EC2_RETRY_CODES = [
'RequestLimitExceeded',
'InsufficientInstanceCapacity',
'InternalError',
'Unavailable',
'InsufficientAddressCapacity',
'InsufficientReservedInstanceCapacity',
]
JS_COMMENT_RE = re.compile(r'/\*.*?\*/', re.S)
# Only load in this module if the EC2 configurations are in place
def __virtual__():
'''
Set up the libcloud functions and check for EC2 configurations
'''
if not HAS_REQUESTS:
return False
if get_configured_provider() is False:
return False
for provider, details in six.iteritems(__opts__['providers']):
if 'provider' not in details or details['provider'] != 'ec2':
continue
if not os.path.exists(details['private_key']):
raise SaltCloudException(
'The EC2 key file {0!r} used in the {1!r} provider '
'configuration does not exist\n'.format(
details['private_key'],
provider
)
)
keymode = str(
oct(stat.S_IMODE(os.stat(details['private_key']).st_mode))
)
if keymode not in ('0400', '0600'):
raise SaltCloudException(
'The EC2 key file {0!r} used in the {1!r} provider '
'configuration needs to be set to mode 0400 or 0600\n'.format(
details['private_key'],
provider
)
)
return True
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or 'ec2',
('id', 'key', 'keyname', 'private_key')
)
def _xml_to_dict(xmltree):
'''
Convert an XML tree into a dict
'''
if sys.version_info < (2, 7):
children_len = len(xmltree.getchildren())
else:
children_len = len(xmltree)
if children_len < 1:
name = xmltree.tag
if '}' in name:
comps = name.split('}')
name = comps[1]
return {name: xmltree.text}
xmldict = {}
for item in xmltree:
name = item.tag
if '}' in name:
comps = name.split('}')
name = comps[1]
if name not in xmldict:
if sys.version_info < (2, 7):
children_len = len(item.getchildren())
else:
children_len = len(item)
if children_len > 0:
xmldict[name] = _xml_to_dict(item)
else:
xmldict[name] = item.text
else:
if not isinstance(xmldict[name], list):
tempvar = xmldict[name]
xmldict[name] = []
xmldict[name].append(tempvar)
xmldict[name].append(_xml_to_dict(item))
return xmldict
def optimize_providers(providers):
'''
Return an optimized list of providers.
We want to reduce the duplication of querying
the same region.
If a provider is using the same credentials for the same region
the same data will be returned for each provider, thus causing
un-wanted duplicate data and API calls to EC2.
'''
tmp_providers = {}
optimized_providers = {}
for name, data in six.iteritems(providers):
if 'location' not in data:
data['location'] = DEFAULT_LOCATION
if data['location'] not in tmp_providers:
tmp_providers[data['location']] = {}
creds = (data['id'], data['key'])
if creds not in tmp_providers[data['location']]:
tmp_providers[data['location']][creds] = {'name': name,
'data': data,
}
for location, tmp_data in six.iteritems(tmp_providers):
for creds, data in six.iteritems(tmp_data):
_id, _key = creds
_name = data['name']
_data = data['data']
if _name not in optimized_providers:
optimized_providers[_name] = _data
return optimized_providers
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def query(params=None, setname=None, requesturl=None, location=None,
return_url=False, return_root=False):
provider = get_configured_provider()
service_url = provider.get('service_url', 'amazonaws.com')
# Retrieve access credentials from meta-data, or use provided
access_key_id, secret_access_key, token = aws.creds(provider)
attempts = 5
while attempts > 0:
params_with_headers = params.copy()
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
if not location:
location = get_location()
if not requesturl:
endpoint = provider.get(
'endpoint',
'ec2.{0}.{1}'.format(location, service_url)
)
requesturl = 'https://{0}/'.format(endpoint)
endpoint = _urlparse(requesturl).netloc
endpoint_path = _urlparse(requesturl).path
else:
endpoint = _urlparse(requesturl).netloc
endpoint_path = _urlparse(requesturl).path
if endpoint == '':
endpoint_err = (
'Could not find a valid endpoint in the '
'requesturl: {0}. Looking for something '
'like https://some.ec2.endpoint/?args').format(requesturl)
log.error(endpoint_err)
if return_url is True:
return {'error': endpoint_err}, requesturl
return {'error': endpoint_err}
log.debug('Using EC2 endpoint: {0}'.format(endpoint))
# AWS v4 signature
method = 'GET'
region = location
service = 'ec2'
canonical_uri = _urlparse(requesturl).path
host = endpoint.strip()
# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ') # Format date as YYYYMMDD'T'HHMMSS'Z'
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = hashlib.sha256('').hexdigest()
ec2_api_version = provider.get(
'ec2_api_version',
DEFAULT_EC2_API_VERSION
)
params_with_headers['Version'] = ec2_api_version
keys = sorted(params_with_headers.keys())
values = map(params_with_headers.get, keys)
querystring = _urlencode(list(zip(keys, values)))
querystring = querystring.replace('+', '%20')
canonical_request = method + '\n' + canonical_uri + '\n' + \
querystring + '\n' + canonical_headers + '\n' + \
signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + \
credential_scope + '\n' + \
hashlib.sha256(canonical_request).hexdigest()
kDate = sign(('AWS4' + provider['key']).encode('utf-8'), datestamp)
kRegion = sign(kDate, region)
kService = sign(kRegion, service)
signing_key = sign(kService, 'aws4_request')
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
hashlib.sha256).hexdigest()
#sig = binascii.b2a_base64(hashed)
authorization_header = algorithm + ' ' + 'Credential=' + \
provider['id'] + '/' + credential_scope + \
', ' + 'SignedHeaders=' + signed_headers + \
', ' + 'Signature=' + signature
headers = {'x-amz-date': amz_date, 'Authorization': authorization_header}
log.debug('EC2 Request: {0}'.format(requesturl))
log.trace('EC2 Request Parameters: {0}'.format(params_with_headers))
try:
result = requests.get(requesturl, headers=headers, params=params_with_headers)
log.debug(
'EC2 Response Status Code: {0}'.format(
# result.getcode()
result.status_code
)
)
log.trace(
'EC2 Response Text: {0}'.format(
result.text
)
)
result.raise_for_status()
break
except requests.exceptions.HTTPError as exc:
root = ET.fromstring(exc.response.content)
data = _xml_to_dict(root)
# check to see if we should retry the query
err_code = data.get('Errors', {}).get('Error', {}).get('Code', '')
if attempts > 0 and err_code and err_code in EC2_RETRY_CODES:
attempts -= 1
log.error(
'EC2 Response Status Code and Error: [{0} {1}] {2}; '
'Attempts remaining: {3}'.format(
exc.response.status_code, exc, data, attempts
)
)
# Wait a bit before continuing to prevent throttling
time.sleep(2)
continue
log.error(
'EC2 Response Status Code and Error: [{0} {1}] {2}'.format(
exc.response.status_code, exc, data
)
)
if return_url is True:
return {'error': data}, requesturl
return {'error': data}
else:
log.error(
'EC2 Response Status Code and Error: [{0} {1}] {2}'.format(
exc.response.status_code, exc, data
)
)
if return_url is True:
return {'error': data}, requesturl
return {'error': data}
response = result.text
root = ET.fromstring(response)
items = root[1]
if return_root is True:
items = root
if setname:
if sys.version_info < (2, 7):
children_len = len(root.getchildren())
else:
children_len = len(root)
for item in range(0, children_len):
comps = root[item].tag.split('}')
if comps[1] == setname:
items = root[item]
ret = []
for item in items:
ret.append(_xml_to_dict(item))
if return_url is True:
return ret, requesturl
return ret
def _wait_for_spot_instance(update_callback,
update_args=None,
update_kwargs=None,
timeout=10 * 60,
interval=30,
interval_multiplier=1,
max_failures=10):
'''
Helper function that waits for a spot instance request to become active
for a specific maximum amount of time.
:param update_callback: callback function which queries the cloud provider
for spot instance request. It must return None if
the required data, running instance included, is
not available yet.
:param update_args: Arguments to pass to update_callback
:param update_kwargs: Keyword arguments to pass to update_callback
:param timeout: The maximum amount of time(in seconds) to wait for the IP
address.
:param interval: The looping interval, i.e., the amount of time to sleep
before the next iteration.
:param interval_multiplier: Increase the interval by this multiplier after
each request; helps with throttling
:param max_failures: If update_callback returns ``False`` it's considered
query failure. This value is the amount of failures
accepted before giving up.
:returns: The update_callback returned data
:raises: SaltCloudExecutionTimeout
'''
if update_args is None:
update_args = ()
if update_kwargs is None:
update_kwargs = {}
duration = timeout
while True:
log.debug(
'Waiting for spot instance reservation. Giving up in '
'00:{0:02d}:{1:02d}'.format(
int(timeout // 60),
int(timeout % 60)
)
)
data = update_callback(*update_args, **update_kwargs)
if data is False:
log.debug(
'update_callback has returned False which is considered a '
'failure. Remaining Failures: {0}'.format(max_failures)
)
max_failures -= 1
if max_failures <= 0:
raise SaltCloudExecutionFailure(
'Too many failures occurred while waiting for '
'the spot instance reservation to become active.'
)
elif data is not None:
return data
if timeout < 0:
raise SaltCloudExecutionTimeout(
'Unable to get an active spot instance request for '
'00:{0:02d}:{1:02d}'.format(
int(duration // 60),
int(duration % 60)
)
)
time.sleep(interval)
timeout -= interval
if interval_multiplier > 1:
interval *= interval_multiplier
if interval > timeout:
interval = timeout + 1
log.info('Interval multiplier in effect; interval is '
'now {0}s'.format(interval))
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. Latest version can be found at:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
sizes = {
'Cluster Compute': {
'cc2.8xlarge': {
'id': 'cc2.8xlarge',
'cores': '16 (2 x Intel Xeon E5-2670, eight-core with '
'hyperthread)',
'disk': '3360 GiB (4 x 840 GiB)',
'ram': '60.5 GiB'
},
'cc1.4xlarge': {
'id': 'cc1.4xlarge',
'cores': '8 (2 x Intel Xeon X5570, quad-core with '
'hyperthread)',
'disk': '1690 GiB (2 x 840 GiB)',
'ram': '22.5 GiB'
},
},
'Cluster CPU': {
'cg1.4xlarge': {
'id': 'cg1.4xlarge',
'cores': '8 (2 x Intel Xeon X5570, quad-core with '
'hyperthread), plus 2 NVIDIA Tesla M2050 GPUs',
'disk': '1680 GiB (2 x 840 GiB)',
'ram': '22.5 GiB'
},
},
'High CPU': {
'c1.xlarge': {
'id': 'c1.xlarge',
'cores': '8 (with 2.5 ECUs each)',
'disk': '1680 GiB (4 x 420 GiB)',
'ram': '8 GiB'
},
'c1.medium': {
'id': 'c1.medium',
'cores': '2 (with 2.5 ECUs each)',
'disk': '340 GiB (1 x 340 GiB)',
'ram': '1.7 GiB'
},
'c3.large': {
'id': 'c3.large',
'cores': '2 (with 3.5 ECUs each)',
'disk': '32 GiB (2 x 16 GiB SSD)',
'ram': '3.75 GiB'
},
'c3.xlarge': {
'id': 'c3.xlarge',
'cores': '4 (with 3.5 ECUs each)',
'disk': '80 GiB (2 x 40 GiB SSD)',
'ram': '7.5 GiB'
},
'c3.2xlarge': {
'id': 'c3.2xlarge',
'cores': '8 (with 3.5 ECUs each)',
'disk': '160 GiB (2 x 80 GiB SSD)',
'ram': '15 GiB'
},
'c3.4xlarge': {
'id': 'c3.4xlarge',
'cores': '16 (with 3.5 ECUs each)',
'disk': '320 GiB (2 x 80 GiB SSD)',
'ram': '30 GiB'
},
'c3.8xlarge': {
'id': 'c3.8xlarge',
'cores': '32 (with 3.5 ECUs each)',
'disk': '320 GiB (2 x 160 GiB SSD)',
'ram': '60 GiB'
}
},
'High I/O': {
'hi1.4xlarge': {
'id': 'hi1.4xlarge',
'cores': '8 (with 4.37 ECUs each)',
'disk': '2 TiB',
'ram': '60.5 GiB'
},
},
'High Memory': {
'm2.2xlarge': {
'id': 'm2.2xlarge',
'cores': '4 (with 3.25 ECUs each)',
'disk': '840 GiB (1 x 840 GiB)',
'ram': '34.2 GiB'
},
'm2.xlarge': {
'id': 'm2.xlarge',
'cores': '2 (with 3.25 ECUs each)',
'disk': '410 GiB (1 x 410 GiB)',
'ram': '17.1 GiB'
},
'm2.4xlarge': {
'id': 'm2.4xlarge',
'cores': '8 (with 3.25 ECUs each)',
'disk': '1680 GiB (2 x 840 GiB)',
'ram': '68.4 GiB'
},
'r3.large': {
'id': 'r3.large',
'cores': '2 (with 3.25 ECUs each)',
'disk': '32 GiB (1 x 32 GiB SSD)',
'ram': '15 GiB'
},
'r3.xlarge': {
'id': 'r3.xlarge',
'cores': '4 (with 3.25 ECUs each)',
'disk': '80 GiB (1 x 80 GiB SSD)',
'ram': '30.5 GiB'
},
'r3.2xlarge': {
'id': 'r3.2xlarge',
'cores': '8 (with 3.25 ECUs each)',
'disk': '160 GiB (1 x 160 GiB SSD)',
'ram': '61 GiB'
},
'r3.4xlarge': {
'id': 'r3.4xlarge',
'cores': '16 (with 3.25 ECUs each)',
'disk': '320 GiB (1 x 320 GiB SSD)',
'ram': '122 GiB'
},
'r3.8xlarge': {
'id': 'r3.8xlarge',
'cores': '32 (with 3.25 ECUs each)',
'disk': '640 GiB (2 x 320 GiB SSD)',
'ram': '244 GiB'
}
},
'High-Memory Cluster': {
'cr1.8xlarge': {
'id': 'cr1.8xlarge',
'cores': '16 (2 x Intel Xeon E5-2670, eight-core)',
'disk': '240 GiB (2 x 120 GiB SSD)',
'ram': '244 GiB'
},
},
'High Storage': {
'hs1.8xlarge': {
'id': 'hs1.8xlarge',
'cores': '16 (8 cores + 8 hyperthreads)',
'disk': '48 TiB (24 x 2 TiB hard disk drives)',
'ram': '117 GiB'
},
},
'Micro': {
't1.micro': {
'id': 't1.micro',
'cores': '1',
'disk': 'EBS',
'ram': '615 MiB'
},
},
'Standard': {
'm1.xlarge': {
'id': 'm1.xlarge',
'cores': '4 (with 2 ECUs each)',
'disk': '1680 GB (4 x 420 GiB)',
'ram': '15 GiB'
},
'm1.large': {
'id': 'm1.large',
'cores': '2 (with 2 ECUs each)',
'disk': '840 GiB (2 x 420 GiB)',
'ram': '7.5 GiB'
},
'm1.medium': {
'id': 'm1.medium',
'cores': '1',
'disk': '400 GiB',
'ram': '3.75 GiB'
},
'm1.small': {
'id': 'm1.small',
'cores': '1',
'disk': '150 GiB',
'ram': '1.7 GiB'
},
'm3.2xlarge': {
'id': 'm3.2xlarge',
'cores': '8 (with 3.25 ECUs each)',
'disk': 'EBS',
'ram': '30 GiB'
},
'm3.xlarge': {
'id': 'm3.xlarge',
'cores': '4 (with 3.25 ECUs each)',
'disk': 'EBS',
'ram': '15 GiB'
},
}
}
return sizes
def avail_images(kwargs=None, call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not isinstance(kwargs, dict):
kwargs = {}
if 'owner' in kwargs:
owner = kwargs['owner']
else:
provider = get_configured_provider()
owner = config.get_cloud_config_value(
'owner', provider, __opts__, default='amazon'
)
ret = {}
params = {'Action': 'DescribeImages',
'Owner': owner}
images = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for image in images:
ret[image['imageId']] = image
return ret
def script(vm_):
'''
Return the script deployment object
'''
return 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_)
)
)
def keyname(vm_):
'''
Return the keyname
'''
return config.get_cloud_config_value(
'keyname', vm_, __opts__, search_global=False
)
def securitygroup(vm_):
'''
Return the security group
'''
return config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
def iam_profile(vm_):
'''
Return the IAM profile.
The IAM instance profile to associate with the instances.
This is either the Amazon Resource Name (ARN) of the instance profile
or the name of the role.
Type: String
Default: None
Required: No
Example: arn:aws:iam::111111111111:instance-profile/s3access
Example: s3access
'''
return config.get_cloud_config_value(
'iam_profile', vm_, __opts__, search_global=False
)
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, default='public_ips',
search_global=False
)
def get_ssh_gateway_config(vm_):
'''
Return the ssh_gateway configuration.
'''
ssh_gateway = config.get_cloud_config_value(
'ssh_gateway', vm_, __opts__, default=None,
search_global=False
)
# Check to see if a SSH Gateway will be used.
if not isinstance(ssh_gateway, str):
return None
# Create dictionary of configuration items
# ssh_gateway
ssh_gateway_config = {'ssh_gateway': ssh_gateway}
# ssh_gateway_port
ssh_gateway_config['ssh_gateway_port'] = config.get_cloud_config_value(
'ssh_gateway_port', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_username
ssh_gateway_config['ssh_gateway_user'] = config.get_cloud_config_value(
'ssh_gateway_username', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_private_key
ssh_gateway_config['ssh_gateway_key'] = config.get_cloud_config_value(
'ssh_gateway_private_key', vm_, __opts__, default=None,
search_global=False
)
# ssh_gateway_password
ssh_gateway_config['ssh_gateway_password'] = config.get_cloud_config_value(
'ssh_gateway_password', vm_, __opts__, default=None,
search_global=False
)
# Check if private key exists
key_filename = ssh_gateway_config['ssh_gateway_key']
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_gateway_private_key {0!r} does not exist'.format(
key_filename
)
)
elif (
key_filename is None and
not ssh_gateway_config['ssh_gateway_password']
):
raise SaltCloudConfigError(
'No authentication method. Please define: '
' ssh_gateway_password or ssh_gateway_private_key'
)
return ssh_gateway_config
def get_location(vm_=None):
'''
Return the EC2 region to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
)
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
params = {'Action': 'DescribeRegions'}
result = aws.query(params,
location=get_location(),
provider=get_provider(),
opts=__opts__,
sigver='4')
for region in result:
ret[region['regionName']] = {
'name': region['regionName'],
'endpoint': region['regionEndpoint'],
}
return ret
def get_availability_zone(vm_):
'''
Return the availability zone to use
'''
avz = config.get_cloud_config_value(
'availability_zone', vm_, __opts__, search_global=False
)
if avz is None:
return None
zones = _list_availability_zones()
# Validate user-specified AZ
if avz not in zones: