262 lines
10 KiB
Python
262 lines
10 KiB
Python
#!/usr/bin/python
|
|
# -*- coding: utf-8 -*-
|
|
# MIT License (see LICENSE)
|
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
__metaclass__ = type
|
|
|
|
DOCUMENTATION = r'''
|
|
module: vps
|
|
short_description: Buy a Interweb Angola VPS or manage one you have
|
|
version_added: 1.0.0
|
|
description:
|
|
- With O(server_id), manages an existing server: power state, time zone and reverse DNS. Nothing is bought.
|
|
- With O(product_id), buys a new server with the account credit. O(idempotency_key) is required, so running the
|
|
task again within 24 hours returns the same purchase instead of buying again. Save the returned RV(server.id) and
|
|
use O(server_id) from then on.
|
|
- The API cannot cancel services. Cancel in Meu Interweb.
|
|
options:
|
|
server_id:
|
|
description: Id of a server you already have.
|
|
type: int
|
|
product_id:
|
|
description: Catalog product to buy (see M(interweb_ao.cloud.catalog_info)).
|
|
type: int
|
|
billing_cycle:
|
|
description: Billing cycle of the purchase.
|
|
type: str
|
|
choices: [monthly, quarterly, semi_annually, annually, biennially, triennially]
|
|
config_options:
|
|
description: >-
|
|
Choices of the purchase, as C({"option id": choice id}). Options left out get the first choice.
|
|
type: dict
|
|
promo_code:
|
|
description: Promo code for the purchase.
|
|
type: str
|
|
idempotency_key:
|
|
description:
|
|
- Unique value for this purchase, such as C(web-01-2026). Required with O(product_id).
|
|
- The API keeps it for 24 hours; a repeated task with the same key and the same options gets the same answer.
|
|
type: str
|
|
state:
|
|
description:
|
|
- V(present) only makes sure the server exists. V(running), V(stopped) and V(restarted) also set the power state.
|
|
type: str
|
|
choices: [present, running, stopped, restarted]
|
|
default: present
|
|
timezone:
|
|
description: Time zone of the server, such as C(UTC).
|
|
type: str
|
|
reverse_dns:
|
|
description: >-
|
|
Reverse DNS name of each IP of the server, as C({"ip": "hostname"}). An empty name goes back to the default.
|
|
type: dict
|
|
wait:
|
|
description: Wait for a new server to be ready and for power actions to finish.
|
|
type: bool
|
|
default: true
|
|
wait_timeout:
|
|
description: Seconds to wait.
|
|
type: int
|
|
default: 1800
|
|
extends_documentation_fragment:
|
|
- interweb_ao.cloud.auth
|
|
author:
|
|
- Interweb Angola (@interweb-ao)
|
|
'''
|
|
|
|
EXAMPLES = r'''
|
|
- name: Make sure the server is running, with its reverse DNS
|
|
interweb_ao.cloud.vps:
|
|
server_id: 12345
|
|
state: running
|
|
reverse_dns:
|
|
203.0.113.10: mail.example.co.ao
|
|
|
|
- name: Buy a VPS (simulated with a sandbox_ key)
|
|
interweb_ao.cloud.vps:
|
|
product_id: "{{ vps_product_id }}"
|
|
billing_cycle: monthly
|
|
idempotency_key: web-01
|
|
state: running
|
|
register: bought
|
|
|
|
- name: Show the new server
|
|
ansible.builtin.debug:
|
|
msg: "{{ bought.server.id }} {{ bought.server.ip }}"
|
|
'''
|
|
|
|
RETURN = r'''
|
|
server:
|
|
description: The server, as GET /v1/servers/{id} answers. Empty when the purchase was simulated.
|
|
returned: always
|
|
type: dict
|
|
purchase:
|
|
description: The answer of the purchase (order_id, invoice_id, amount, currency, service_id).
|
|
returned: when a server was bought
|
|
type: dict
|
|
simulated:
|
|
description: True when the API only simulated the writes (sandbox_ key).
|
|
returned: always
|
|
type: bool
|
|
actions:
|
|
description: What was done or, in check mode, what would be done.
|
|
returned: always
|
|
type: list
|
|
elements: str
|
|
'''
|
|
|
|
import time
|
|
|
|
from ansible.module_utils.basic import AnsibleModule
|
|
from ..module_utils.api import (
|
|
ApiError, PANEL_NAME, auth_argument_spec, fail, get_client, new_idempotency_key,
|
|
)
|
|
|
|
RUNNING = ('running', 'starting', 'restarting')
|
|
STOPPED = ('stopped', 'stopping')
|
|
|
|
|
|
def wait_server(client, server_id, timeout):
|
|
deadline = time.time() + timeout
|
|
while True:
|
|
try:
|
|
srv = client.get('/v1/servers/%d' % server_id)
|
|
if srv.get('status') == 'active' and srv.get('power_state') != 'unknown':
|
|
return srv
|
|
except ApiError as e:
|
|
if e.status != 404:
|
|
raise
|
|
srv = None
|
|
if time.time() >= deadline:
|
|
return srv
|
|
time.sleep(20)
|
|
|
|
|
|
def main():
|
|
spec = auth_argument_spec()
|
|
spec.update(
|
|
server_id=dict(type='int'),
|
|
product_id=dict(type='int'),
|
|
billing_cycle=dict(type='str', choices=['monthly', 'quarterly', 'semi_annually', 'annually', 'biennially', 'triennially']),
|
|
config_options=dict(type='dict'),
|
|
promo_code=dict(type='str'),
|
|
idempotency_key=dict(type='str', no_log=False),
|
|
state=dict(type='str', default='present', choices=['present', 'running', 'stopped', 'restarted']),
|
|
timezone=dict(type='str'),
|
|
reverse_dns=dict(type='dict'),
|
|
wait=dict(type='bool', default=True),
|
|
wait_timeout=dict(type='int', default=1800),
|
|
)
|
|
module = AnsibleModule(
|
|
argument_spec=spec,
|
|
mutually_exclusive=[('server_id', 'product_id')],
|
|
required_one_of=[('server_id', 'product_id')],
|
|
required_by={'product_id': ('billing_cycle', 'idempotency_key')},
|
|
supports_check_mode=True,
|
|
)
|
|
p = module.params
|
|
client = get_client(module, ['vps:read'] if module.check_mode else ['vps:read', 'vps:write'])
|
|
result = dict(changed=False, server={}, simulated=False, actions=[])
|
|
|
|
try:
|
|
server_id = p['server_id']
|
|
if server_id is None:
|
|
result['changed'] = True
|
|
result['actions'].append('buy product %s (%s)' % (p['product_id'], p['billing_cycle']))
|
|
if module.check_mode:
|
|
module.exit_json(**result)
|
|
body = dict(product_id=p['product_id'], billing_cycle=p['billing_cycle'])
|
|
if p['config_options']:
|
|
body['config_options'] = dict((str(k), int(v)) for k, v in p['config_options'].items())
|
|
if p['promo_code']:
|
|
body['promo_code'] = p['promo_code']
|
|
r = client.request('POST', '/v1/services/purchase', body=body, idempotency_key=p['idempotency_key'])
|
|
result['purchase'] = r.data
|
|
if r.simulated:
|
|
result['simulated'] = True
|
|
result['warnings'] = ['The API key is a sandbox_ key: the purchase was simulated and no server exists.']
|
|
module.exit_json(**result)
|
|
server_id = (r.data or {}).get('service_id')
|
|
if not server_id:
|
|
module.fail_json(msg='The purchase was accepted but the API did not give a server id. Check it in %s.' % PANEL_NAME, **result)
|
|
if not p['wait']:
|
|
result['server'] = dict(id=server_id)
|
|
module.exit_json(**result)
|
|
srv = wait_server(client, server_id, p['wait_timeout'])
|
|
if not srv:
|
|
result['server'] = dict(id=server_id)
|
|
result['warnings'] = ['Server %s is not ready yet; run the task again later with server_id.' % server_id]
|
|
module.exit_json(**result)
|
|
else:
|
|
try:
|
|
srv = client.get('/v1/servers/%d' % server_id)
|
|
except ApiError as e:
|
|
if e.status == 404:
|
|
module.fail_json(msg='Server %s is not in the account (or is not active or suspended).' % server_id)
|
|
raise
|
|
|
|
base = '/v1/servers/%d' % server_id
|
|
power = srv.get('power_state')
|
|
action = None
|
|
if p['state'] == 'running' and power not in RUNNING:
|
|
action = 'start'
|
|
elif p['state'] == 'stopped' and power not in STOPPED:
|
|
action = 'stop'
|
|
elif p['state'] == 'restarted':
|
|
action = 'restart'
|
|
pending = []
|
|
if action:
|
|
result['actions'].append(action)
|
|
if not module.check_mode:
|
|
try:
|
|
r = client.request('POST', '%s/%s' % (base, action), idempotency_key=new_idempotency_key())
|
|
result['simulated'] = result['simulated'] or r.simulated
|
|
if r.data and r.data.get('action_id') and not r.simulated:
|
|
pending.append(r.data['action_id'])
|
|
except ApiError as e:
|
|
if not (e.has('already_running') or e.has('already_stopped')):
|
|
raise
|
|
result['actions'].pop()
|
|
action = None
|
|
|
|
if p['timezone']:
|
|
tz = client.get(base + '/timezone')
|
|
if tz.get('timezone') != p['timezone']:
|
|
if p['timezone'] not in (tz.get('available') or [p['timezone']]):
|
|
module.fail_json(msg='Time zone %s is not available. Choose one of: %s' % (p['timezone'], ', '.join(tz.get('available') or [])))
|
|
result['actions'].append('timezone %s' % p['timezone'])
|
|
if not module.check_mode:
|
|
r = client.request('PUT', base + '/timezone', body=dict(timezone=p['timezone']))
|
|
result['simulated'] = result['simulated'] or r.simulated
|
|
|
|
if p['reverse_dns']:
|
|
have = dict((x.get('ip'), x.get('hostname') or '') for x in (client.get(base + '/reverse-dns').get('records') or []))
|
|
changed = [dict(ip=str(ip), hostname=str(h or '')) for ip, h in p['reverse_dns'].items() if have.get(str(ip), '') != str(h or '')]
|
|
if changed:
|
|
result['actions'].append('reverse DNS of %s' % ', '.join(x['ip'] for x in changed))
|
|
if not module.check_mode:
|
|
r = client.request('PUT', base + '/reverse-dns', body=dict(records=changed))
|
|
result['simulated'] = result['simulated'] or r.simulated
|
|
|
|
if p['wait'] and not module.check_mode:
|
|
for action_id in pending:
|
|
a = client.wait_action(action_id, timeout=p['wait_timeout'])
|
|
if a.get('status') == 'failed':
|
|
module.fail_json(msg='The %s action failed: %s' % (action, a.get('result')), **result)
|
|
|
|
result['changed'] = result['changed'] or bool(result['actions'])
|
|
if result['actions'] and not module.check_mode:
|
|
try:
|
|
srv = client.get(base)
|
|
except ApiError:
|
|
pass
|
|
result['server'] = srv
|
|
module.exit_json(**result)
|
|
except ApiError as e:
|
|
fail(module, e, **result)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|