def run_module(): module_args = ovh_argument_spec() module_args.update(dict(service_name=dict(required=True), )) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] if module.check_mode: module.exit_json( changed=True, msg= "Terminate {} is done, please confirm via the email sent - (dry run mode)" .format(service_name)) try: client.post('/dedicated/server/%s/terminate' % service_name) module.exit_json( changed=False, msg="Terminate {} is done, please confirm via the email sent". format(service_name)) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(service_name=dict(required=True), link_type=dict(required=True))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) link_type = module.params['link_type'] service_name = module.params['service_name'] try: result = client.get( '/dedicated/server/%s/networkInterfaceController?linkType=%s' % (service_name, link_type)) # XXX: This is a hack, would be better to detect what kind of server you are using: # If there is no result, maybe you have a server with multiples network interfaces on the same link (2x public + 2x vrack), like HGR # In this case, retry with public_lag/private_lag linkType if not result: result = client.get( '/dedicated/server/%s/networkInterfaceController?linkType=%s_lag' % (service_name, link_type)) module.exit_json(changed=False, msg=result) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update(dict( service_name=dict(required=True), state=dict(choices=['present', 'absent'], default='present') )) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) client = ovh_api_connect(module) service_name = module.params['service_name'] state = module.params['state'] if state == 'present': monitoring_bool = True elif state == 'absent': monitoring_bool = False if module.check_mode: module.exit_json(msg="Monitoring is now {} for {} - (dry run mode)".format(state, service_name), changed=True) try: server_state = client.get('/dedicated/server/%s' % service_name) if server_state['monitoring'] == monitoring_bool: module.exit_json(msg="Monitoring is already {} on {}".format(state, service_name), changed=False) client.put('/dedicated/server/%s' % service_name, monitoring=monitoring_bool) module.exit_json(msg="Monitoring is now {} on {}".format(state, service_name), changed=True) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error), changed=False)
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(service_name=dict(required=True), name=dict(required=True), region=dict(required=True))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] name = module.params['name'] region = module.params['region'] try: result = client.get('/cloud/project/%s/flavor' % (service_name), region=region) for f in result: if f['name'] == name: flavor_id = f['id'] module.exit_json(changed=False, id=flavor_id) module.fail_json(msg="Flavor {} not found in {}".format(name, region), changed=False) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(service_name=dict(required=True), instance_id=dict(required=True))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] instance_id = module.params['instance_id'] if module.check_mode: module.exit_json( msg="Monthly Billing enabled on {} ! - (dry run mode)".format( instance_id), changed=True) try: result = client.get('/cloud/project/%s/instance/%s' % (service_name, instance_id)) if result['monthlyBilling'] is not None and result['monthlyBilling'][ 'status'] == "ok": module.exit_json(changed=False, msg="Monthly billing already enabled") result = client.post( '/cloud/project/%s/instance/%s/activeMonthlyBilling' % (service_name, instance_id)) module.exit_json(changed=True, **result) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(service_name=dict(required=True), hostname=dict(required=True), template=dict(required=True), ssh_key_name=dict(required=False, default=None), soft_raid_devices=dict(required=False, default=None))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] hostname = module.params['hostname'] template = module.params['template'] ssh_key_name = module.params['ssh_key_name'] soft_raid_devices = module.params['soft_raid_devices'] if module.check_mode: module.exit_json( msg= "Installation in progress on {} as {} with template {} - (dry run mode)" .format(service_name, hostname, template), changed=True) try: compatible_templates = client.get( '/dedicated/server/%s/install/compatibleTemplates' % service_name) if template not in compatible_templates[ "ovh"] and template not in compatible_templates["personal"]: module.fail_json(msg="{} doesn't exist in compatibles templates". format(template)) except APIError as api_error: return module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) details = { "details": { "language": "en", "customHostname": hostname, "sshKeyName": ssh_key_name, "softRaidDevices": soft_raid_devices } } try: client.post('/dedicated/server/%s/install/start' % service_name, **details, templateName=template) module.exit_json( msg="Installation in progress on {} as {} with template {}!". format(service_name, hostname, template), changed=True) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update(dict( service_name=dict(required=True), boot=dict(required=True, choices=['harddisk', 'rescue']), force_reboot=dict(required=False, default=False, type='bool') )) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) client = ovh_api_connect(module) service_name = module.params['service_name'] boot = module.params['boot'] force_reboot = module.params['force_reboot'] changed = False bootid = {'harddisk': 1, 'rescue': 1122} if module.check_mode: module.exit_json( msg="{} is now set to boot on {}. Reboot in progress... - (dry run mode)".format(service_name, boot), changed=False) try: check = client.get( '/dedicated/server/%s' % service_name ) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) if bootid[boot] != check['bootId']: try: client.put( '/dedicated/server/%s' % service_name, bootId=bootid[boot] ) changed = True except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) if force_reboot: try: client.post( '/dedicated/server/%s/reboot' % service_name ) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) module.exit_json(msg="{} is now forced to reboot on {}".format(service_name, boot), changed=True) module.exit_json(msg="{} is now set to boot on {}".format(service_name, boot), changed=changed)
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(service_name=dict(required=True), max_retry=dict(required=False, default=240), sleep=dict(required=False, default=10))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] max_retry = module.params['max_retry'] sleep = module.params['sleep'] if module.check_mode: module.exit_json(msg="done - (dry run mode)", changed=False) for i in range(1, int(max_retry)): # Messages cannot be displayed in real time (yet) # https://github.com/ansible/proposals/issues/92 display.display("%i out of %i" % (i, int(max_retry)), constants.COLOR_VERBOSE) try: tasklist = client.get('/dedicated/server/%s/task' % service_name, function='reinstallServer') result = client.get('/dedicated/server/%s/task/%s' % (service_name, max(tasklist))) except APIError as api_error: return module.fail_jsonl( msg="Failed to call OVH API: {0}".format(api_error)) message = "" # Get more details in installation progression if "done" in result['status']: module.exit_json(msg="{}: {}".format(result['status'], message), changed=False) progress_status = client.get('/dedicated/server/%s/install/status' % service_name) if 'message' in progress_status and progress_status[ 'message'] == 'Server is not being installed or reinstalled at the moment': message = progress_status['message'] else: for progress in progress_status['progress']: if progress["status"] == "doing": message = progress['comment'] display.display("{}: {}".format(result['status'], message), constants.COLOR_VERBOSE) time.sleep(float(sleep)) module.fail_json(msg="Max wait time reached, about %i x %i seconds" % (i, int(sleep)))
def run_module(): module_args = ovh_argument_spec() module_args.update(dict(service_name=dict(required=True))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] try: result = client.get('/dedicated/server/%s' % (service_name)) module.exit_json(changed=False, **result) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update(dict( ip=dict(required=True), reverse=dict(required=True), ip_block=dict(required=False, default=None) )) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) client = ovh_api_connect(module) ip = module.params['ip'] reverse = module.params['reverse'] ip_block = module.params['ip_block'] # ip_block is only needed for vrack IPs. Default it to "ip" when not used if ip_block is None: ip_block = ip else: # url encode the ip mask (/26 -> %2F) ip_block = urllib.parse.quote(ip_block, safe='') if module.check_mode: module.exit_json(msg="Reverse {} to {} succesfully set ! - (dry run mode)".format(ip, reverse), changed=True) result = {} try: result = client.get('/ip/%s/reverse/%s' % (ip_block, ip)) except ResourceNotFoundError: result['reverse'] = '' if result['reverse'] == reverse: module.exit_json(msg="Reverse {} to {} already set !".format(ip, reverse), changed=False) try: client.post( '/ip/%s/reverse' % ip_block, ipReverse=ip, reverse=reverse ) module.exit_json( msg="Reverse {} to {} succesfully set !".format(ip, reverse), changed=True) except APIError as api_error: return module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update(dict( name=dict(required=True), flavor_id=dict(required=True), image_id=dict(required=False, default=None), service_name=dict(required=True), ssh_key_id=dict(required=False, default=None), region=dict(required=True), networks=dict(required=False, default=[], type="list"), )) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) client = ovh_api_connect(module) name = module.params['name'] service_name = module.params['service_name'] flavor_id = module.params['flavor_id'] image_id = module.params['image_id'] service_name = module.params['service_name'] ssh_key_id = module.params['ssh_key_id'] region = module.params['region'] networks = module.params['networks'] try: result = client.post('/cloud/project/%s/instance' % service_name, flavorId=flavor_id, imageId=image_id, monthlyBilling=False, name=name, region=region, networks=networks, sshKeyId=ssh_key_id ) module.exit_json(changed=True, **result) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(display_name=dict(required=True), service_name=dict(required=True))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) display_name = module.params['display_name'] service_name = module.params['service_name'] if module.check_mode: module.exit_json( msg="display_name has been set to {} ! - (dry run mode)".format( display_name), changed=True) try: result = client.get('/dedicated/server/%s/serviceInfos' % service_name) except APIError as api_error: return module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) service_id = result["serviceId"] resource = { "resource": { 'displayName': display_name, 'name': service_name } } try: client.put('/service/%s' % service_id, **resource) module.exit_json( msg="displayName succesfully set to {} for {} !".format( display_name, service_name), changed=True) except APIError as api_error: return module.fail_json( msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict( name=dict(required=True), service_name=dict(required=True), region=dict(required=True), )) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) name = module.params["name"] service_name = module.params["service_name"] region = module.params["region"] try: instances_list = client.get("/cloud/project/%s/instance" % (service_name), region=region) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) for i in instances_list: if i["name"] == name: instance_id = i["id"] instance_details = client.get("/cloud/project/%s/instance/%s" % (service_name, instance_id)) if instance_details["status"] == "ACTIVE": module.fail_json( msg="Instance must not be active to be deleted", changed=False) try: client.delete("/cloud/project/%s/instance/%s" % (service_name, instance_id)) module.exit_json(changed=True) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(ip=dict(required=True), reverse=dict(required=True))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) ip = module.params['ip'] reverse = module.params['reverse'] if module.check_mode: module.exit_json( msg="Reverse {} to {} succesfully set ! - (dry run mode)".format( ip, reverse), changed=True) result = {} try: result = client.get('/ip/%s/reverse/%s' % (ip, ip)) except ResourceNotFoundError: result['reverse'] = '' if result['reverse'] == reverse: module.exit_json(msg="Reverse {} to {} already set !".format( ip, reverse), changed=False) try: client.post('/ip/%s/reverse' % ip, ipReverse=ip, reverse=reverse) module.exit_json(msg="Reverse {} to {} succesfully set !".format( ip, reverse), changed=True) except APIError as api_error: return module.fail_json( msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(service_name=dict(required=True), vrack=dict(required=True), state=dict(choices=['present', 'absent'], default='present'))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] vrack = module.params['vrack'] state = module.params['state'] if module.check_mode: module.exit_json(msg="{} succesfully {} on {} - (dry run mode)".format( service_name, state, vrack), changed=True) try: # There is no easy way to know if the server is # on an old or new network generation. # So we need to call this new route # to ask for virtualNetworkInterface # and if the answer is empty, it's on a old generation. # The /vrack/%s/allowedServices route used previously # has availability and scaling problems. result = client.get('/dedicated/server/%s/virtualNetworkInterface' % service_name, mode='vrack') # XXX: This is a hack, would be better to detect what kind of server you are using: # If there is no result, maybe you have a server with multiples network interfaces on the same link (2x public + 2x vrack), like HGR # In this case, retry with vrack_aggregation mode if not result: result = client.get( '/dedicated/server/%s/virtualNetworkInterface' % service_name, mode='vrack_aggregation') except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) # XXX: In a near future, OVH will add the possibility to add # multiple interfaces to the same VRACK or another one # This code may break at this moment because # each server will have a list of dedicatedServerInterface # New generation if len(result): # transform the list to a string server_interface = "".join(result) try: is_already_registered = client.get( '/vrack/%s/dedicatedServerInterfaceDetails' % vrack) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) for new_server in is_already_registered: if new_server['dedicatedServer'] == service_name: if state == 'present': module.exit_json( msg="{} is already registered on new {}".format( service_name, vrack), changed=False) if state == 'absent': try: result = client.delete( '/vrack/%s/dedicatedServerInterface/%s' % (vrack, server_interface)) module.exit_json( msg="{} has been deleted from new {}".format( service_name, vrack), changed=True) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}". format(api_error)) if state == 'absent': module.exit_json( msg="{} is not present on new {}, don't remove it".format( service_name, vrack), changed=False) # Server is not yet registered on vrack, go for it try: client.post('/vrack/%s/dedicatedServerInterface' % vrack, dedicatedServerInterface=server_interface) module.exit_json(msg="{} has been added to new {}".format( service_name, vrack), changed=True) except APIError as api_error: return module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) # Old generation else: try: is_already_registered = client.get('/vrack/%s/dedicatedServer' % vrack) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) for old_server in is_already_registered: if old_server == service_name: if state == 'present': module.exit_json( msg="{} is already registered on old {}".format( service_name, vrack), changed=False) if state == 'absent': try: result = client.delete('/vrack/%s/dedicatedServer/%s' % (vrack, service_name)) module.exit_json( msg="{} has been deleted from old {}".format( service_name, vrack), changed=True) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}". format(api_error)) if state == 'absent': module.exit_json( msg="{} is not present on old {}, don't remove it".format( service_name, vrack), changed=False) # Server is not yet registered on vrack, go for it try: client.post('/vrack/%s/dedicatedServer' % vrack, dedicatedServer=service_name) module.exit_json(msg="{} has been added to old {}".format( service_name, vrack), changed=True) except APIError as api_error: return module.fail_json( msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(value=dict(required=True, type="list"), name=dict(required=True), domain=dict(required=True), record_type=dict(choices=[ 'A', 'AAAA', 'CAA', 'CNAME', 'DKIM', 'DMARC', 'DNAME', 'LOC', 'MX', 'NAPTR', 'NS', 'PTR', 'SPF', 'SRV', 'SSHFP', 'TLSA', 'TXT' ], default='A'), state=dict(choices=['present', 'absent'], default='present'), record_ttl=dict(type="int", required=False, default=0), append=dict(required=False, default=False, type="bool"))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) value = module.params['value'] domain = module.params['domain'] name = module.params['name'] record_type = module.params['record_type'] state = module.params['state'] append = module.params['append'] record_ttl = module.params["record_ttl"] if module.check_mode: module.exit_json(msg="{} set to {}.{} ! - (dry run mode)".format( ', '.join(value), name, domain)) try: existing_records = client.get('/domain/zone/%s/record' % domain, fieldType=record_type, subDomain=name) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) record_created = [] record_deleted = [] if state == 'present': # At least one record already exists if existing_records: for ind in existing_records: try: record = client.get('/domain/zone/%s/record/%s' % (domain, ind)) # the record already exists : don't add it later if record['target'] in value: value.remove(record['target']) # the record must not exist and append is set to false : delete from zone if record['target'] not in value and not append: client.delete('/domain/zone/%s/record/%s' % (domain, ind)) record_deleted.append(record['target']) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) for v in value: try: client.post('/domain/zone/%s/record' % domain, fieldType=record_type, subDomain=name, target=v, ttl=record_ttl) record_created.append(v) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) if len(record_deleted) + len(record_created): # we must run a refresh on zone after modifications client.post('/domain/zone/%s/refresh' % domain) msg = '' if len(record_deleted): msg += '{} deleted'.format(', '.join(record_deleted)) if len(record_created): if len(record_deleted): msg += ' and ' msg += '{} created'.format(', '.join(record_created)) msg += ' from record {}.{}'.format(name, domain) module.exit_json(msg=msg, changed=True) else: module.exit_json( msg="{} is already up-to-date on domain {}".format( name, domain), changed=False) elif state == 'absent': if not existing_records: module.exit_json(msg="Target {} doesn't exist on domain {}".format( name, domain), changed=False) try: for ind in existing_records: record = client.get('/domain/zone/%s/record/%s' % (domain, ind)) client.delete('/domain/zone/%s/record/%s' % (domain, ind)) record_deleted.append(record.get('target')) # we must run a refresh on zone after modifications client.post('/domain/zone/%s/refresh' % domain) module.exit_json(msg='{} deleted from record {}.{}'.format( ', '.join(record_deleted), name, domain), changed=True) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(template=dict(required=True), state=dict(choices=["present", "absent"], default="present"), service_name=dict(required=False, default=None))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) template = module.params['template'] state = module.params['state'] service_name = module.params['service_name'] # The action plugin resolve the "template" variable path. So we need to re-extract the basename src_template = os.path.basename(template) if module.check_mode: module.exit_json( msg="template {} is now {} - dry run mode".format(template, state)) try: template_list = client.get('/me/installationTemplate') except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) if state == 'absent': if src_template in template_list: try: client.delete('/me/installationTemplate/%s' % src_template) module.exit_json(msg="Template {} succesfully deleted".format( src_template, changed=True)) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) else: module.exit_json( msg="Template {} does not exists, do not delete it".format( src_template), changed=False) src = template with open(src, 'r') as stream: content = yaml.load(stream) conf = {} for i, j in content.items(): conf[i] = j # state == 'present' if src_template in template_list: module.exit_json(msg="Template {} already exists".format(src_template), changed=False) try: client.post('/me/installationTemplate', baseTemplateName=conf['baseTemplateName'], defaultLanguage=conf['defaultLanguage'], name=conf['templateName']) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) templates = { 'customization': { "customHostname": conf['customHostname'], "postInstallationScriptLink": conf['postInstallationScriptLink'], "postInstallationScriptReturn": conf['postInstallationScriptReturn'], "sshKeyName": conf['sshKeyName'], "useDistributionKernel": conf['useDistributionKernel'] }, 'defaultLanguage': conf['defaultLanguage'], 'templateName': conf['templateName'] } try: client.put('/me/installationTemplate/{}'.format(conf['templateName']), **templates) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) try: client.post('/me/installationTemplate/{}/partitionScheme'.format( conf['templateName']), name=conf['partitionScheme'], priority=conf['partitionSchemePriority']) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) if conf['isHardwareRaid']: try: result = client.get( '/dedicated/server/%s/install/hardwareRaidProfile' % service_name) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) if len(result['controllers']) != 1: module.fail_json( msg= "Failed to call OVH API: {0} Code can't handle more than one controller when using Hardware Raid setups" ) # XXX: Only works with a server who has one controller. # All the disks in this controller are taken to form one raid # In the future, some of our servers could have more than one controller # so we will have to adapt this code disks = result['controllers'][0]['disks'][0]['names'] # if 'raid 1' in conf['raidMode']: # TODO : create a list of disks like this # {'disks': ['[c0:d0,c0:d1]', # '[c0:d2,c0:d3]', # '[c0:d4,c0:d5]', # '[c0:d6,c0:d7]', # '[c0:d8,c0:d9]', # '[c0:d10,c0:d11]'], # 'mode': 'raid10', # 'name': 'managerHardRaid', # 'step': 1} # else: # TODO : for raid 0, it's assumed that # a simple list of disks would be sufficient try: result = client.post( '/me/installationTemplate/%s/partitionScheme/%s/hardwareRaid' % (conf['templateName'], conf['partitionScheme']), disks=disks, mode=conf['raidMode'], name=conf['partitionScheme'], step=1) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) partition = {} for k in conf['partition']: partition = ast.literal_eval(k) try: if 'raid' in partition.keys(): client.post( '/me/installationTemplate/%s/partitionScheme/%s/partition' % (conf['templateName'], conf['partitionScheme']), filesystem=partition['filesystem'], mountpoint=partition['mountpoint'], raid=partition['raid'], size=partition['size'], step=partition['step'], type=partition['type']) else: client.post( '/me/installationTemplate/%s/partitionScheme/%s/partition' % (conf['templateName'], conf['partitionScheme']), filesystem=partition['filesystem'], mountpoint=partition['mountpoint'], size=partition['size'], step=partition['step'], type=partition['type']) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) try: client.post('/me/installationTemplate/%s/checkIntegrity' % conf['templateName']) module.exit_json(msg="Template {} succesfully created".format( conf['templateName']), changed=True) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(service_name=dict(required=True), instance_id=dict(required=True), volume_id=dict(required=True), state=dict(choices=['present', 'absent'], default='present'))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] instance_id = module.params['instance_id'] volume_id = module.params['volume_id'] state = module.params['state'] if module.check_mode: module.exit_json( msg="Ensure volume id {} is {} on instance id {} - (dry run mode)". format(volume_id, state, instance_id), changed=True) volume_details = {} try: volume_details = client.get('/cloud/project/%s/volume/%s' % (service_name, volume_id)) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) # Search if the volume exist. Consider you manage a strict nomenclature. if instance_id in volume_details['attachedTo'] and state == 'absent': try: result = client.post('/cloud/project/%s/volume/%s/detach' % (service_name, volume_id), instanceId=instance_id) module.exit_json( changed=True, msg="Volume id {} has been detached from instance id {}". format(volume_id, instance_id), **result) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) elif instance_id not in volume_details['attachedTo'] and state == 'present': try: result = client.post('/cloud/project/%s/volume/%s/attach' % (service_name, volume_id), instanceId=instance_id) module.exit_json( changed=True, msg="Volume id {} has been attached to instance id {}".format( volume_id, instance_id), **result) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) else: # ( if instance_id not in volume_details and state == 'absent' ) or (if instance_id in volume_details and state == 'present' ) module.exit_json(changed=False, **volume_details)
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(service_name=dict(required=True), region=dict(required=True), size=dict(required=True, type="int"), volume_type=dict( required=False, choices=['classic', 'high-speed', 'high-speed-gen2'], default='classic'), name=dict(required=True), description=dict(required=False), image_id=dict(required=False), snapshot_id=dict(required=False), state=dict(choices=['present', 'absent'], default='present'))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) service_name = module.params['service_name'] region = module.params['region'] size = module.params['size'] volume_type = module.params['volume_type'] name = module.params['name'] description = module.params['description'] image_id = module.params['image_id'] snapshot_id = module.params['snapshot_id'] state = module.params['state'] if module.check_mode: module.exit_json(msg="Ensure volume {} is {} - (dry run mode)".format( name, state), changed=True) volume_list = [] try: volume_list = client.get('/cloud/project/%s/volume' % service_name, region=region) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format( api_error)) # show error message and exit # Search if the volume exist. Consider you manage a strict nomenclature based on name. for volume in volume_list: if volume['name'] == name: volume_id = volume['id'] volume_details = client.get('/cloud/project/%s/volume/%s' % (service_name, volume_id)) if state == 'absent': try: _ = client.delete('/cloud/project/%s/volume/%s' % (service_name, volume_id)) module.exit_json( msg="Volume {} ({}), has been deleted from cloud". format(name, volume_id), changed=True) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) else: # state == 'present': module.exit_json( msg= "Volume {} ({}) has already been created on OVH public Cloud " .format(name, volume_id), changed=False, **volume_details) if state == 'present': try: result = client.post('/cloud/project/%s/volume' % service_name, description=description, imageId=image_id, name=name, region=region, size=size, snapshotId=snapshot_id, type=volume_type) module.exit_json( msg="Volume {} ({}), has been created on OVH public Cloud". format(name, result['id']), changed=True, **result) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) else: # state == 'absent' module.exit_json( msg="Volume {} doesn't exist on OVH public Cloud ".format(name), changed=False)
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(ip=dict(required=True), name=dict(required=True), domain=dict(required=True), state=dict(choices=['present', 'absent'], default='present'))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) ip = module.params['ip'] domain = module.params['domain'] name = module.params['name'] state = module.params['state'] if module.check_mode: module.exit_json( msg="{} set to {}.{} ! - (dry run mode)".format(ip, name, domain)) try: existing_records = client.get('/domain/zone/%s/record' % domain, fieldType='A', subDomain=name) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) if state == 'present': # At least one record already exists if existing_records: for ind in existing_records: try: record = client.get('/domain/zone/%s/record/%s' % (domain, ind)) # The record already exist if record['subDomain'] == name and record['target'] == ip: module.exit_json( msg="{} is already registered on domain {}".format( name, domain), changed=False) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) # Gatekeeper: if more than one record match the query, # don't update anything and fail if len(existing_records) > 1: module.fail_json( msg= "More than one record match the name {} in domain {}, this module won't update all of these records." .format(name, domain)) # Update the record if needed: try: ind = existing_records[0] client.put('/domain/zone/%s/record/%s' % (domain, ind), subDomain=name, target=ip) # we must run a refresh on zone after modifications client.post('/domain/zone/%s/refresh' % domain) module.exit_json( msg="Record has been updated: {} is now targeting {}.{}". format(ip, name, domain), changed=True) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) # The record does not exist yet try: client.post('/domain/zone/%s/record' % domain, fieldType='A', subDomain=name, target=ip) # we must run a refresh on zone after modifications client.post('/domain/zone/%s/refresh' % domain) module.exit_json(msg="{} is now targeting {}.{}".format( ip, name, domain), changed=True) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) elif state == 'absent': if not existing_records: module.exit_json(msg="Target {} doesn't exist on domain {}".format( name, domain), changed=False) record_deleted = [] try: for ind in existing_records: record = client.get('/domain/zone/%s/record/%s' % (domain, ind)) client.delete('/domain/zone/%s/record/%s' % (domain, ind)) # we must run a refresh on zone after modifications client.post('/domain/zone/%s/refresh' % domain) record_deleted.append( "%s IN A %s" % (record.get('subDomain'), record.get('target'))) module.exit_json( msg=",".join(record_deleted) + " successfuly deleted from domain {}".format(domain), changed=True) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update( dict(template=dict(required=True), state=dict(choices=["present", "absent"], default="present"), service_name=dict(required=False, default=None))) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) client = ovh_api_connect(module) template = module.params['template'] state = module.params['state'] service_name = module.params['service_name'] # The action plugin resolve the "template" variable path. So we need to re-extract the basename src_template = os.path.basename(template) if module.check_mode: module.exit_json( msg="template {} is now {} - dry run mode".format(template, state)) try: template_list = client.get('/me/installationTemplate') except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) if state == 'absent': if src_template in template_list: try: client.delete('/me/installationTemplate/%s' % src_template) module.exit_json( msg="Template {} succesfully deleted".format(src_template), changed=True) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) else: module.exit_json( msg="Template {} does not exists, do not delete it".format( src_template), changed=False) src = template with open(src, 'r') as stream: content = yaml.safe_load(stream) conf = {} for i, j in content.items(): conf[i] = j # state == 'present' if src_template in template_list: module.exit_json(msg="Template {} already exists".format(src_template), changed=False) try: client.post('/me/installationTemplate', baseTemplateName=conf['baseTemplateName'], defaultLanguage=conf['defaultLanguage'], name=conf['templateName']) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) templates = { 'customization': { "customHostname": conf['customHostname'], "postInstallationScriptLink": conf['postInstallationScriptLink'], "postInstallationScriptReturn": conf['postInstallationScriptReturn'], "sshKeyName": conf['sshKeyName'], "useDistributionKernel": conf['useDistributionKernel'] }, 'defaultLanguage': conf['defaultLanguage'], 'templateName': conf['templateName'] } try: client.put('/me/installationTemplate/{}'.format(conf['templateName']), **templates) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) try: client.post('/me/installationTemplate/{}/partitionScheme'.format( conf['templateName']), name=conf['partitionScheme'], priority=conf['partitionSchemePriority']) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) if conf['isHardwareRaid']: try: result = client.get( '/dedicated/server/%s/install/hardwareRaidProfile' % service_name) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) if len(result['controllers']) != 1: module.fail_json( msg= "Failed to call OVH API: {0} Code can't handle more than one controller when using Hardware Raid setups" ) # XXX: Only works with a server who has one controller. # All the disks in this controller are taken to form one raid # In the future, some of our servers could have more than one controller # so we will have to adapt this code diskarray = result['controllers'][0]['disks'][0]['names'] disks = [] if conf['raidMode'] == 'raid1': # In raid1, we take the first two disks in the disk array disks = [diskarray[0], diskarray[1]] elif conf['raidMode'] == 'raid10' or conf['raidMode'] == 'raid60': # In raid10 or raid60, we configure two disk groups groups = [[], []] for i in range(len(diskarray)): if i < (len(diskarray) // 2): groups[0].append(diskarray[i]) else: groups[1].append(diskarray[i]) sep = ',' disks = [ '[' + (sep.join(groups[0])) + ']', '[' + (sep.join(groups[1])) + ']' ] else: # Fallback condition: pass every disk in the array (will be applied for raid0) disks = diskarray try: result = client.post( '/me/installationTemplate/%s/partitionScheme/%s/hardwareRaid' % (conf['templateName'], conf['partitionScheme']), disks=disks, mode=conf['raidMode'], name=conf['partitionScheme'], step=1) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) partition = {} for k in conf['partition']: partition = ast.literal_eval(k) if 'volumeName' not in partition.keys(): partition['volumeName'] = "" try: if 'raid' in partition.keys(): client.post( '/me/installationTemplate/%s/partitionScheme/%s/partition' % (conf['templateName'], conf['partitionScheme']), filesystem=partition['filesystem'], mountpoint=partition['mountpoint'], raid=partition['raid'], size=partition['size'], step=partition['step'], type=partition['type'], volumeName=partition['volumeName']) else: client.post( '/me/installationTemplate/%s/partitionScheme/%s/partition' % (conf['templateName'], conf['partitionScheme']), filesystem=partition['filesystem'], mountpoint=partition['mountpoint'], size=partition['size'], step=partition['step'], type=partition['type'], volumeName=partition['volumeName']) except APIError as api_error: module.fail_json( msg="Failed to call OVH API: {0}".format(api_error)) try: client.post('/me/installationTemplate/%s/checkIntegrity' % conf['templateName']) module.exit_json(msg="Template {} succesfully created".format( conf['templateName']), changed=True) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))
def run_module(): module_args = ovh_argument_spec() module_args.update(dict( name=dict(required=True), flavor_id=dict(required=True), image_id=dict(required=True), service_name=dict(required=True), ssh_key_id=dict(required=False, default=None), region=dict(required=True), networks=dict(required=False, default=[], type="list"), monthly_billing=dict(required=False, default=False, type="bool"), force_reinstall=dict(required=False, default=False, type="bool") )) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) client = ovh_api_connect(module) name = module.params['name'] service_name = module.params['service_name'] flavor_id = module.params['flavor_id'] image_id = module.params['image_id'] ssh_key_id = module.params['ssh_key_id'] region = module.params['region'] networks = module.params['networks'] monthly_billing = module.params['monthly_billing'] force_reinstall = module.params['force_reinstall'] try: instances_list = client.get('/cloud/project/%s/instance' % (service_name), region=region) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) for i in instances_list: if i['name'] == name: instance_id = i['id'] instance_details = client.get('/cloud/project/%s/instance/%s' % (service_name, instance_id)) if force_reinstall: try: reinstall_result = client.post( '/cloud/project/%s/instance/%s/reinstall' % (service_name, instance_id), imageId=image_id) module.exit_json(changed=True, **reinstall_result) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error)) module.exit_json(changed=False, msg="Instance {} [{}] in region {} is already installed".format(name, instance_id, region), **instance_details) try: result = client.post('/cloud/project/%s/instance' % service_name, flavorId=flavor_id, imageId=image_id, monthlyBilling=monthly_billing, name=name, region=region, networks=networks, sshKeyId=ssh_key_id ) module.exit_json(changed=True, **result) except APIError as api_error: module.fail_json(msg="Failed to call OVH API: {0}".format(api_error))