summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/cloudscale/cloudscale_server.py
blob: 149dd2eddd24a2541994fdc685765668b8243bb4 (plain)
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2017, Gaudenz Steinlin <gaudenz.steinlin@cloudscale.ch>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.

ANSIBLE_METADATA = {'metadata_version': '1.0',
                    'status': ['preview'],
                    'supported_by': 'community'}


DOCUMENTATION = '''
---
module: cloudscale_server
short_description: Manages servers on the cloudscale.ch IaaS service
description:
  - Create, start, stop and delete servers on the cloudscale.ch IaaS service.
  - All operations are performed using the cloudscale.ch public API v1.
  - "For details consult the full API documentation: U(https://www.cloudscale.ch/en/api/v1)."
  - An valid API token is required for all operations. You can create as many tokens as you like using the cloudscale.ch control panel at
    U(https://control.cloudscale.ch).
notes:
  - Instead of the api_token parameter the CLOUDSCALE_API_TOKEN environment variable can be used.
  - To create a new server at least the C(name), C(ssh_key), C(image) and C(flavor) options are required.
  - If more than one server with the name given by the C(name) option exists, execution is aborted.
  - Once a server is created all parameters except C(state) are read-only. You can't change the name, flavor or any other property. This is a limitation
    of the cloudscale.ch API. The module will silently ignore differences between the configured parameters and the running server if a server with the
    correct name or UUID exists. Only state changes will be applied.
version_added: 2.3
author: "Gaudenz Steinlin <gaudenz.steinlin@cloudscale.ch>"
options:
  state:
    description:
      - State of the server
    required: False
    default: running
    choices: ['running', 'stopped', 'absent']
  name:
    description:
      - Name of the Server
      - Either C(name) or C(uuid) are required. These options are mutually exclusive.
    required: False
  uuid:
    description:
      - UUID of the server
      - Either C(name) or C(uuid) are required. These options are mutually exclusive.
    required: False
  flavor:
    description:
      - Flavor of the server
    required: False
  image:
    description:
      - Image used to create the server
    required: False
  volume_size_gb:
    description:
      - Size of the root volume in GB
    required: False
    default: 10
  bulk_volume_size_gb:
    description:
      - Size of the bulk storage volume in GB
    required: False
    default: null (no bulk storage volume)
  ssh_keys:
    description:
       - List of SSH public keys
       - Use the full content of your .pub file here.
    required: False
  use_public_network:
    description:
      - Attach a public network interface to the server
    required: False
    default: True
  use_private_network:
    description:
      - Attach a private network interface to the server
    required: False
    default: False
  use_ipv6:
    description:
      - Enable IPv6 on the public network interface
    required: False
    default: True
  anti_affinity_with:
    description:
      - UUID of another server to create an anti-affinity group with
    required: False
  user_data:
    description:
      - Cloud-init configuration (cloud-config) data to use for the server.
    required: False
  api_token:
    description:
      - cloudscale.ch API token.
      - This can also be passed in the CLOUDSCALE_API_TOKEN environment variable.
    required: False
'''

EXAMPLES = '''
# Start a server (if it does not exist) and register the server details
- name: Start cloudscale.ch server
  cloudscale_server:
    name: my-shiny-cloudscale-server
    image: debian-8
    flavor: flex-4
    ssh_keys: ssh-rsa XXXXXXXXXX...XXXX ansible@cloudscale
    use_private_network: True
    bulk_volume_size_gb: 100
    api_token: xxxxxx
  register: server1

# Start another server in anti-affinity to the first one
- name: Start second cloudscale.ch server
  cloudscale_server:
    name: my-other-shiny-server
    image: ubuntu-16.04
    flavor: flex-8
    ssh_keys: ssh-rsa XXXXXXXXXXX ansible@cloudscale
    anti_affinity_with: '{{ server1.uuid }}'
    api_token: xxxxxx

# Stop the first server
- name: Stop my first server
  cloudscale_server:
    uuid: '{{ server1.uuid }}'
    state: stopped
    api_token: xxxxxx

# Delete my second server
- name: Delete my second server
  cloudscale_server:
    name: my-other-shiny-server
    state: absent
    api_token: xxxxxx

# Start a server and wait for the SSH host keys to be generated
- name: Start server and wait for SSH host keys
  cloudscale_server:
    name: my-cloudscale-server-with-ssh-key
    image: debian-8
    flavor: flex-4
    ssh_keys: ssh-rsa XXXXXXXXXXX ansible@cloudscale
    api_token: xxxxxx
  register: server
  until: server.ssh_fingerprints
  retries: 60
  delay: 2
'''

RETURN = '''
href:
  description: API URL to get details about this server
  returned: success when not state == absent
  type: string
  sample: https://api.cloudscale.ch/v1/servers/cfde831a-4e87-4a75-960f-89b0148aa2cc
uuid:
  description: The unique identifier for this server
  returned: success
  type: string
  sample: cfde831a-4e87-4a75-960f-89b0148aa2cc
name:
  description: The display name of the server
  returned: success
  type: string
  sample: its-a-me-mario.cloudscale.ch
state:
  description: The current status of the server
  returned: success
  type: string
  sample: running
flavor:
  description: The flavor that has been used for this server
  returned: success when not state == absent
  type: string
  sample: flex-8
image:
  description: The image used for booting this server
  returned: success when not state == absent
  type: string
  sample: debian-8
volumes:
  description: List of volumes attached to the server
  returned: success when not state == absent
  type: list
  sample: [ {"type": "ssd", "device": "/dev/vda", "size_gb": "50"} ]
interfaces:
  description: List of network ports attached to the server
  returned: success when not state == absent
  type: list
  sample: [ { "type": "public", "addresses": [ ... ] } ]
ssh_fingerprints:
  description: A list of SSH host key fingerprints. Will be null until the host keys could be retrieved from the server.
  returned: success when not state == absent
  type: list
  sample: ["ecdsa-sha2-nistp256 SHA256:XXXX", ... ]
ssh_host_keys:
  description: A list of SSH host keys. Will be null until the host keys could be retrieved from the server.
  returned: success when not state == absent
  type: list
  sample: ["ecdsa-sha2-nistp256 XXXXX", ... ]
anti_affinity_with:
  description: List of servers in the same anti-affinity group
  returned: success when not state == absent
  type: string
  sample: []
'''

from datetime import datetime, timedelta
import json
import os
from time import sleep

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves.urllib.parse import urlencode
from ansible.module_utils.urls import fetch_url

API_URL      = 'https://api.cloudscale.ch/v1/'
TIMEOUT_WAIT = 30
ALLOWED_STATES = ('running',
                  'stopped',
                  'absent',
                  )

class AnsibleCloudscaleServer(object):

    def __init__(self, module, api_token):
        self._module = module
        self._auth_header = {'Authorization': 'Bearer %s' % api_token}

        # Check if server already exists and load properties
        uuid = self._module.params['uuid']
        name = self._module.params['name']

        # Initialize server dictionary
        self.info = {'uuid': uuid, 'name': name, 'state': 'absent'}

        servers = self.list_servers()
        matching_server = []
        for s in servers:
            if uuid:
                # Look for server by UUID if given
                if s['uuid'] == uuid:
                    self.info =  self._transform_state(s)
                    break
            else:
                # Look for server by name
                if s['name'] == name:
                    matching_server.append(s)
        else:
            if len(matching_server) == 1:
                self.info = self._transform_state(matching_server[0])
            elif len(matching_server) > 1:
                self._module.fail_json(msg="More than one server with name '%s' exists. "
                                       "Use the 'uuid' parameter to identify the server" % name)


    def _get(self, api_call):
        resp, info = fetch_url(self._module, API_URL+api_call, headers=self._auth_header)

        if info['status'] == 200:
            return json.loads(resp.read())
        else:
            self._module.fail_json(msg='Failure while calling the cloudscale.ch API with GET for '
                                       '"%s": %s' % (api_call, info['body']))


    def _post(self, api_call, data=None):
        if data is not None:
            data = urlencode(data)

        resp, info = fetch_url(self._module,
                               API_URL+api_call,
                               headers = self._auth_header,
                               method='POST',
                               data=data)

        if info['status'] == 201:
            return json.loads(resp.read())
        elif info['status'] == 204:
            return None
        else:
            self._module.fail_json(msg='Failure while calling the cloudscale.ch API with POST for '
                                       '"%s": %s' % (api_call, info['body']))


    def _delete(self, api_call):
        resp, info = fetch_url(self._module,
                               API_URL+api_call,
                               headers = self._auth_header,
                               method='DELETE')

        if info['status'] == 204:
            return None
        else:
            self._module.fail_json(msg='Failure while calling the cloudscale.ch API with DELETE for '
                                       '"%s": %s' % (api_call, info['body']))


    @staticmethod
    def _transform_state(server):
        if 'status' in server:
            server['state'] = server['status']
            del server['status']
        else:
            server['state'] = 'absent'
        return server


    def update_info(self):

        # If we don't have a UUID (yet) there is nothing to update
        if not 'uuid' in self.info:
            return

        # Can't use _get here because we want to handle 404
        resp, info = fetch_url(self._module,
                               API_URL+'servers/'+self.info['uuid'],
                               headers=self._auth_header)
        if info['status'] == 200:
            self.info = self._transform_state(json.loads(resp.read()))
        elif info['status'] == 404:
            self.info = {'uuid': self.info['uuid'],
                         'name': self.info.get('name', None),
                         'state': 'absent'}
        else:
            self._module.fail_json(msg='Failure while calling the cloudscale.ch API for '
                                       'update_info: %s' % info['body'])


    def wait_for_state(self, states):
        start = datetime.now()
        while datetime.now() - start < timedelta(seconds=TIMEOUT_WAIT):
            self.update_info()
            if self.info['state'] in states:
                return True
            sleep(1)

        self._module.fail_json(msg='Timeout while waiting for a state change on server %s to states %s. Current state is %s'
                               % (self.info['name'], states, self.info['state']))


    def create_server(self):
        data = self._module.params.copy()

        # check for required parameters to create a server
        missing_parameters = []
        for p in ('name', 'ssh_keys', 'image', 'flavor'):
            if not p in data or not data[p]:
                missing_parameters.append(p)

        if len(missing_parameters) > 0:
            self._module.fail_json(msg='Missing required parameter(s) to create a new server: %s' %
                                   ' '.join(missing_parameters))

        # Sanitize data dictionary
        for k,v in data.items():

            # Remove items not relevant to the create server call
            if k in ('api_token', 'uuid', 'state'):
                del data[k]
                continue

            # Remove None values, these don't get correctly translated by urlencode
            if v is None:
                del data[k]
                continue

        self.info = self._transform_state(self._post('servers', data))
        self.wait_for_state(('running', ))


    def delete_server(self):
        self._delete('servers/%s' % self.info['uuid'])
        self.wait_for_state(('absent', ))


    def start_server(self):
        self._post('servers/%s/start' % self.info['uuid'])
        self.wait_for_state(('running', ))


    def stop_server(self):
        self._post('servers/%s/stop' % self.info['uuid'])
        self.wait_for_state(('stopped', ))


    def list_servers(self):
        return self._get('servers')


def main():
    module = AnsibleModule(
        argument_spec = dict(
            state               = dict(default='running',
                                       choices=ALLOWED_STATES),
            name                = dict(),
            uuid                = dict(),
            flavor              = dict(),
            image               = dict(),
            volume_size_gb      = dict(type='int', default=10),
            bulk_volume_size_gb = dict(type='int'),
            ssh_keys            = dict(type='list'),
            use_public_network  = dict(type='bool', default=True),
            use_private_network = dict(type='bool', default=False),
            use_ipv6            = dict(type='bool', default=True),
            anti_affinity_with  = dict(),
            user_data           = dict(),
            api_token           = dict(no_log=True),
        ),
        required_one_of=(('name', 'uuid'),),
        mutually_exclusive=(('name', 'uuid'),),
        supports_check_mode=True,
    )

    api_token = module.params['api_token'] or os.environ.get('CLOUDSCALE_API_TOKEN')

    if not api_token:
        module.fail_json(msg='The api_token module parameter or the CLOUDSCALE_API_TOKEN '
                             'environment varialbe are required for this module.')

    target_state = module.params['state']
    server = AnsibleCloudscaleServer(module, api_token)
    # The server could be in a changeing or error state.
    # Wait for one of the allowed states before doing anything.
    # If an allowed state can't be reached, this module fails.
    if not server.info['state'] in ALLOWED_STATES:
        server.wait_for_state(ALLOWED_STATES)
    current_state = server.info['state']

    if module.check_mode:
        module.exit_json(changed=not target_state == current_state,
                         **server.info)

    changed = False
    if current_state == 'absent' and target_state == 'running':
        server.create_server()
        changed = True
    elif current_state == 'absent' and target_state == 'stopped':
        server.create_server()
        server.stop_server()
        changed = True
    elif current_state == 'stopped' and target_state == 'running':
        server.start_server()
        changed = True
    elif current_state in ('running', 'stopped') and target_state == 'absent':
        server.delete_server()
        changed = True
    elif current_state == 'running' and target_state == 'stopped':
        server.stop_server()
        changed = True

    module.exit_json(changed=changed, **server.info)


if __name__ == '__main__':
    main()