-
Notifications
You must be signed in to change notification settings - Fork 3
/
oktawave
197 lines (176 loc) · 7.17 KB
/
oktawave
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
#!/usr/bin/env python
import json
from oktawave.api import OktawaveApi, PowerStatus, CloneType
# -- universal helper methods --
# copied/pasted between modules as they must fit in a single file
import requests.exceptions
import datetime
import time
from oktawave.exceptions import OktawaveAPIError
def serializable(obj):
# make obj json-serializable
if isinstance(obj, (basestring, int)):
return obj
elif isinstance(obj, datetime.datetime):
return obj.strftime('%c')
elif isinstance(obj, dict):
return {k: serializable(v) for k, v in obj.items()}
elif hasattr(obj, 'label'):
return obj.label
elif obj in (True, False, None):
return obj
else:
try:
iterator = iter(obj)
except TypeError:
return unicode(obj)
return [serializable(elt) for elt in obj]
class APIWrapper(object):
def __init__(self, module, api):
self.module = module
self.api = api
def request_wrapper(self, reqf):
def wrapper(*args, **kwargs):
while True:
try:
return reqf(*args, **kwargs)
except requests.exceptions.HTTPError as exc:
arg_msg = ', '.join(repr(a) for a in args)
kwarg_msg = ', '.join('%s=%s' % (k, repr(v)) for k, v in kwargs.items())
call_msg = '%s(%s)' % (reqf.__name__, ', '.join((arg_msg, kwarg_msg)))
self.module.fail_json(msg='Call to %s failed: %s' % (call_msg, exc.response.text))
except OktawaveAPIError as exc:
if exc.code == exc.OCI_PENDING_OPS: # wait a bit before retrying
time.sleep(5)
else:
raise
return wrapper
def __getattr__(self, name):
method = getattr(self.api, name)
return self.request_wrapper(method)
# -- end --
def get_oci_by_name(api, name):
instances = api.OCI_List()
for oci in instances:
if oci['name'] == name:
return oci
def wait_for_vm(api, name, timeout, want_password):
while timeout > 0:
oci = get_oci_by_name(api, name)
if oci:
break
time.sleep(10)
timeout -= 10
if not oci:
return
oci_settings = api.OCI_Settings(oci['id'])
oci['settings'] = serializable(oci_settings)
if not want_password:
return oci
while timeout > 0:
password = api.OCI_DefaultPassword(oci['id'])
if password:
oci['settings']['password'] = password
break
time.sleep(10)
timeout -= 10
return oci
def main():
module = AnsibleModule(
argument_spec=dict(
okta_username=dict(required=True),
okta_password=dict(required=True),
name=dict(required=True),
state=dict(default="present", choices=["absent", "present", "started", "stopped", "restarted"]),
disk_size_gb=dict(),
oci_class=dict(),
origin_oci=dict(),
template_id=dict(),
change_at_midnight=dict(choices=BOOLEANS, type='bool', default=False),
wait_timeout=dict(default=300),
),
supports_check_mode=True
)
okta_username = module.params.get('okta_username')
okta_password = module.params.get('okta_password')
name = module.params.get('name')
state = module.params.get('state')
disk_size_gb = module.params.get('disk_size_gb')
if disk_size_gb is not None:
disk_size_gb = int(disk_size_gb)
oci_class = module.params.get('oci_class')
origin_oci = module.params.get('origin_oci')
if origin_oci is not None:
origin_oci = int(origin_oci)
template_id = module.params.get('template_id')
if template_id is not None:
template_id = int(template_id)
change_at_midnight = module.params.get('change_at_midnight')
wait_timeout = int(module.params.get('wait_timeout'))
api = APIWrapper(module, OktawaveApi(username=okta_username, password=okta_password))
module_ret = dict(changed=False)
oci = get_oci_by_name(api, name)
if not oci:
if state == 'absent':
module.exit_json(**module_ret)
elif state in ('present', 'started'):
module_ret['changed'] = True
want_password = False
if origin_oci is not None:
if not module.check_mode:
try:
origin_settings = api.OCI_Settings(origin_oci)
except Exception as exc:
module.fail_json(msg='template OCI does not exist')
if oci_class is not None and origin_settings['vm_class_name'] != oci_class:
module.fail_json(msg='template OCI has class %s not %s' % (origin_settings['vm_class_name'], oci_class))
api.OCI_Clone(origin_oci, name, CloneType.AbsoluteCopy) # or 'Runtime'
elif template_id is not None:
if not module.check_mode:
api.OCI_Create(name, template_id, oci_class, disk_size_gb=disk_size_gb)
want_password = True
else:
module.fail_json(msg='either origin_oci or template_id is required to create a new OCI')
new_oci = wait_for_vm(api, name, wait_timeout, want_password)
if new_oci is None:
module.fail_json(msg='timeout waiting for new oci')
power_status = new_oci['status']
new_oci['status'] = unicode(power_status)
if state == 'started':
try:
if power_status.status != PowerStatus.PowerOn:
api.OCI_TurnOn(new_oci['id'])
except Exception as exc:
new_oci['power_on_exception'] = str(exc)
module_ret.update(new_oci)
else:
module.fail_json(msg='OCI %s does not exist, cannot stop/restart' % name)
else:
if state == 'absent':
if not module.check_mode:
api.OCI_Delete(oci['id'])
module_ret['changed'] = True
module.exit_json(**module_ret)
oci_settings = api.OCI_Settings(oci['id'])
oci['settings'] = serializable(oci_settings)
power_status = oci['status']
oci['status'] = unicode(power_status)
oci['settings']['password'] = api.OCI_DefaultPassword(oci['id'])
module_ret.update(oci)
if oci_class is not None and oci_class != oci_settings['vm_class_name']:
if not module.check_mode:
api.OCI_ChangeClass(oci['id'], oci_class, change_at_midnight)
module_ret['changed'] = True
if state == 'started' and power_status.status != PowerStatus.PowerOn:
api.OCI_TurnOn(oci['id'])
module_ret['changed'] = True
elif state == 'stopped' and power_status.status != PowerStatus.PowerOff:
api.OCI_TurnOff(oci['id'])
module_ret['changed'] = True
elif state == 'restarted':
api.OCI_Restart(oci['id'])
module_ret['changed'] = True
module.exit_json(**module_ret)
# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()