· 7 years ago · Jul 20, 2018, 01:28 PM
1# -*- coding:utf-8 -*-
2import os
3import time
4from boto.vpc import VPCConnection
5from boto.ec2.regioninfo import EC2RegionInfo
6
7def _wait_state(objs, state_name, timeout=120):
8 """
9 Wait for cloud ressources to be in a given state.
10 :param objs: list of boto object with update() method
11 :type: list
12 :param state_name: Instance state name expected
13 :type state_name: str
14 :param timeout: Timeout for instances to reach state_name
15 :type timeout: int
16 :return: boto objects which are not in the expected state_name
17 :rtype: list
18
19 """
20 objs = [obj for obj in objs if hasattr(obj, 'update')]
21
22 timeout = time.time() + timeout
23 while time.time() < timeout and objs:
24 for obj in objs:
25 if obj.update() == state_name:
26 objs.remove(obj)
27 time.sleep(5)
28 return objs
29
30def run_and_attach_volume(fcu):
31 """
32 Run instance and attach a 100Gib volume to it
33 :param fcu: connector
34 :type fcu: boto.vpc.VPCConnection
35 """
36 sg = fcu.create_security_group('demo-101', '101_boto')
37 sg.authorize('tcp', 22, 22, '0.0.0.0/0')
38 print 'Security group {0} created'.format(sg)
39 time.sleep(5)
40 ###
41 instance = fcu.run_instances('ami-d4f2f835', key_name='heckle-work', instance_type='c4.large', security_groups=[sg.name]).instances[0]
42 ###
43 _wait_state([instance], 'running')
44 instance.update()
45 print 'Instance {0} created. Ip: {1}'.format(instance, instance.ip_address)
46 fcu.create_tags([instance.id], {'Name': '101_boto'})
47 ###
48 vol = fcu.create_volume(zone='eu-west-2a', size=100)
49 ###
50 _wait_state([vol], 'available')
51 fcu.attach_volume(vol.id, instance.id, '/dev/xvdz')
52 print 'Volume {0} attached on /dev/xvdz'.format(vol.id)
53
54def setup_outscale_connector():
55 """
56 Setup an boto.vpc.VPCConnection
57 :returns: connector
58 :rtype: boto.vpc.VPCConnection
59 """
60 # Fetch access_key, secret_key and endpoint in envrionment
61 access_key_id = os.environ.get('AWS_ACCESS_KEY_ID')
62 secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
63 fcu_endpoint = os.environ.get('FCU_ENDPOINT', None)
64
65 # Setup connector
66 fcu_endpoint = EC2RegionInfo(endpoint=fcu_endpoint)
67 return VPCConnection(access_key_id, secret_access_key, region=fcu_endpoint)
68
69
70if __name__ == '__main__':
71 fcu = setup_outscale_connector()
72 run_and_attach_volume(fcu)