Esempio n. 1
0
    def run(self):
        """Return error, changed, result"""
        if not HAS_OVH:
            return self.fail('OVH Api wrapper not installed')

        credentials = ['endpoint', 'application_key',
                       'application_secret', 'consumer_key']
        credentials_in_parameters = [
            cred in self.params for cred in credentials]
        try:
            if all(credentials_in_parameters):
                self.client = ovh.Client(
                    **{credential: self.params[credential] for credential in credentials})  # noqa
            else:
                self.client = ovh.Client()
        except APIError as api_error:
            return self.fail("Failed to call OVH API: {0}".format(api_error))

        choice_map = dict(
            dns=self.change_dns,
            getmac=self.get_mac,
            terminate=self.terminate_server,
            status=self.get_status_install,
            install=self.launch_install,
            monitoring=self.change_monitoring,
            reverse=self.change_reverse,
            list=self.list_service,
            boot=self.change_boot_dedicated,
            template=self.generate_template,
            vrack=self.change_vrack,
        )

        return choice_map.get(self.params['service'])()
Esempio n. 2
0
def get_ovh_client(module):
	if module.params['endpoint'] and module.params['application_key'] and module.params['application_secret'] and module.params['consumer_key']:
		return ovh.Client(
			endpoint=module.params['endpoint'],
			application_key= module.params['application_key'],
			application_secret=module.params['application_secret'],
			consumer_key=module.params['consumer_key']
		)		
	else:
		return ovh.Client()	
Esempio n. 3
0
 def client(self):
     return ovh.Client(
         endpoint=self._params.get_value("sms_ovh_endpoint"),
         application_key=self._params.get_value("sms_ovh_application_key"),
         application_secret=self._params.get_value(
             "sms_ovh_application_secret"),
         consumer_key=self._params.get_value("sms_ovh_consumer_key"))
Esempio n. 4
0
def main():
    parser = argparse.ArgumentParser(description='Create a snapshot of the vps')
    parser.add_argument('--endpoint', metavar='ENDPOINT', default="ovh-eu",
                        help='endpoint')
    parser.add_argument('--application_key', metavar='APPKEY', required=True,
                        help='application key')
    parser.add_argument('--application_secret', metavar='APPSECRET', required=True,
                        help='application secret')
    parser.add_argument('--consumer_key', metavar='CONSUMERKEY', required=True,
                        help='consumer key')
    parser.add_argument('--vps', metavar='VPSNAME', required=True,
                        help='vps name')
    args = parser.parse_args()

    client = ovh.Client(
        endpoint=args.endpoint,
        application_key=args.application_key,
        application_secret=args.application_secret,
        consumer_key=args.consumer_key,
    )

    try:
        result = client.get('/vps/%s/snapshot'%args.vps)
    except ovh.exceptions.ResourceNotFoundError:
        logger.error("vps snapshot cannot be found")
    else:
        snapshotDate = datetime.strptime(result['creationDate'], '%Y-%m-%dT%H:%M:%S%z')
        logger.debug(snapshotDate)
        oldDays = (datetime.now(timezone.utc) - snapshotDate).days
        if oldDays <= 1:
            logger.info("vps snapshot is %d days old"%oldDays)
        elif oldDays <=2:
            logger.warning("vps snapshot is %d days old"%oldDays)
        else:
            logger.error("vps snapshot is %d days old"%oldDays)
    def get_paramhost(self, type):

        client = ovh.Client(endpoint=self.endpoint)
        zone = '/hosting/web/%' % (domain)
        res = client.get(zone)['status']

        return res
    def getFournisseurZoneDnsrecordId(self, cr, uid, ids, context):
        # create a client using configuration
        zonerecords = {}
        client = ovh.Client(endpoint='ovh-eu')
        # Request RO, /me API access
        access_rules = [
            {
                'method': 'GET',
                'path': '/*'
            },
            {
                'method': 'POST',
                'path': '/*'
            },
            {
                'method': 'PUT',
                'path': '/*'
            },
            {
                'method': 'DELETE',
                'path': '/*'
            },
        ]
        # Request token
        #validation = client.request_consumerkey(access_rules)
        for domain in self.browse(self, cr, uid, ids, context=None):
            zone = domain.domain
            _logger.info('zone   %s' % (zone))

        zone = '/domain/zone/' + zone
        zonerecords = client.get(zone)
        _logger.info('zone records  %s' % (zonerecords))

        return zonerecords
Esempio n. 7
0
def main():
    module = AnsibleModule(argument_spec=dict(
        description=dict(required=True),
        project_name=dict(required=True),
        state=dict(required=True),
    ))

    # Get parameters
    description = module.params.get('description')
    project_name = module.params.get('project_name')
    state = module.params.get('state')

    # Connect to OVH API
    client = ovh.Client()
    #checking Cloud projects
    result2 = client.get('/cloud/project')
    project_exist = False
    for project_id in result2:
        project = client.get('/cloud/project/{}'.format(project_id))
        if project_name == project['description']:
            project_exist = True
            break
    #get vrack
    vrack_exist = False
    result2 = client.get('/vrack')
    if not result2:
        # create vrack
        create_vrack = client.post('/order/vrack/new')
        orderid = create_vrack['orderId']
        #pay vrack order by order Id
        vrack_pay = client.post(
            '/me/order/{}/payWithRegisteredPaymentMean'.format(orderid),
            paymentMean='fidelityAccount')
        # check vrack order status
        order_stat_vrack = client.get('/me/order/{}/status'.format(orderid))
        counter = 0
        while (order_stat_vrack != 'delivered') and (
                counter != 5):  # This constructs an infinite loop
            counter += 1
            order_stat_vrack = client.get(
                '/me/order/{}/status'.format(orderid))
            time.sleep(40)

        if counter == 5:
            print 'Vrack creation timeout'
            exit
        if order_stat_vrack == 'delivered':
            vrack_status = 'DONE'
            vrack_id = client.get('/vrack')
            vrack_details = client.get('/vrack/{}'.format(vrack_id))
            module.exit_json(changed=True, vrack=vrack_id)
    else:
        vrack_exist = True
        #check vrack details
        for vracks_id in result2:
            vrack_details = client.get('/vrack/{}'.format(vracks_id))
            vrack_id = vracks_id
            print('There is an available vrack:{}'.format(vrack_id))
            module.exit_json(changed=False, vrack=vrack_id)
            break
Esempio n. 8
0
 def get_bill(self):
     client = ovh.Client(endpoint='ovh-eu')
     zone = '/me/order/39335072/details/115772326'
     linerecordid = client.get(zone)
     c = len(linerecordid)
     print c
     print linerecordid
Esempio n. 9
0
    def run_step2(self):
        self.ensure_one()
        if (
                not self.application_key or
                not self.application_secret or
                not self.endpoint):
            raise UserError(_(
                "The endpoint, the application key and the application secret "
                "must be set before validation."))
        client = ovh.Client(
            endpoint=self.endpoint,
            application_key=self.application_key,
            application_secret=self.application_secret)

        # Request RO, /me/bill* API access
        ck = client.new_consumer_key_request()
        ck.add_rules(ovh.API_READ_ONLY, "/me/bill*")

        # Request validation
        validation = ck.request()

        if not validation['validationUrl'] or not validation['consumerKey']:
            raise UserError(_(
                "The request to generate the consumer key failed."))

        self.write({
            'validation_url': validation['validationUrl'],
            'consumer_key': validation['consumerKey'],
            'state': 'step3',
            })
        return self.action_continue_wizard()
    def get_list_service_ovh(self):
        list = []
        client = ovh.Client(endpoint='kimsufi-eu')
        zone = '/dedicated/server'
        me = client.get(zone)
        list.append(me)
        client2 = ovh.Client(endpoint='ovh-eu')
        zone2 = '/dedicated/server'
        zone3 = '/cloud/project'
        me2 = client2.get(zone2)
        me3 = client2.get(zone3)
        list.append(me2)
        list.append(me3)
        self.logservice = list

        return True
    def GetRecordFournisseurZoneDnsById(self, cr, uid, ids, context):
        client = ovh.Client(endpoint='ovh-eu')
        # Request RO, /me API access
        access_rules = [
            {
                'method': 'GET',
                'path': '/*'
            },
            {
                'method': 'POST',
                'path': '/*'
            },
            {
                'method': 'PUT',
                'path': '/*'
            },
            {
                'method': 'DELETE',
                'path': '/*'
            },
        ]
        for domain in self.browse(cr, uid, ids, context=None):
            zone = domain.service_domain_id.name
            record = domain.zone_dns_ovh_id

        zone = '/domain/zone/%s/record/%s' % (zone, record)
        linerecordid = client.get(zone)
        return linerecordid
Esempio n. 12
0
 def __init__(self, args):
     self.client = ovh.Client(
         endpoint=args["endpoint"],
         application_key=args["application_key"],
         application_secret=args["application_secret"],
         consumer_key=args["consumer_key"],
     )
def backup(group, rootdir, debug):
    """Backup OVH telephony settings using API."""

    if debug:
        logger.set_min_level_to_print(logging.DEBUG)
        logger.set_min_level_to_mail(None)
        logger.debug('debug activated')

    logger.info('Program start')

    # OVH Client
    client = ovh.Client()

    # First part check all groups
    # If specific group only, take this
    if len(group):
        groups = group
    else:
        groups = client.get('/telephony')

    logger.new_loop_logger()
    for group in groups:
        logger.new_iteration(prefix=group)
        manager = BackupManager(client, group, rootdir, logger)
        manager.backup()
    logger.del_loop_logger()
Esempio n. 14
0
def get_credentials():
    """This function is used to obtain an authentication token.
    It should only be called once."""
    client = ovh.Client()
    access_rules = [
        {
            'method': 'GET',
            'path': '/domain/*'
        },
        {
            'method': 'PUT',
            'path': '/domain/*'
        },
        {
            'method': 'POST',
            'path': '/domain/*'
        },
        {
            'method': 'DELETE',
            'path': '/domain/*'
        },
    ]
    validation = client.request_consumerkey(access_rules)
    # print("Your consumer key is {}".format(validation['consumerKey']))
    # print("Please visit {} to validate".format(validation['validationUrl']))
    return validation['consumerKey']
Esempio n. 15
0
def projects(config_file=None, *args, **kwargs):
    connect = ovh.Client(config_file=config_file, *args, **kwargs)
    result = dict()
    for p in connect.get('/cloud/project'):
        project = connect.get(f'/cloud/project/{p}')
        result[project['description']] = project
    return result
Esempio n. 16
0
def create_client():
    return ovh.Client(
        endpoint=os.environ.get('ENDPOINT'),
        application_key=os.environ.get('APPLICATION_KEY'),
        application_secret=os.environ.get('APPLICATION_SECRET'),
        consumer_key=os.environ.get('CONSUMER_KEY'),
    )
Esempio n. 17
0
 def getMe(self, cr, uid, ids, context=None):
     """ se créer à ovh pour voir la disponibilité de command  """
     client = ovh.Client(endpoint='ovh-eu')
         
     
     zone ='/me'
     me = client.get(zone)
     values = {}
     values['nichandle']=me['nichandle']
     values['ovhCompany']=me['ovhCompany']
     values['sex']= me['sex']
     values['nom']= me['name']
     values['prenom']=me['firstname']
     values['forme_juridique']=me['legalform']
     values['organisation']=me['organisation']
     values['tax_eu_id']=me['vat']
     values['adresse']=me['address']
     values['code_postal']=me['zip']
     values['ville']=me['city']
     values['pays']=me['country']
     values['area'] =me['area']
     values['tel']=me['phone']
     values['email']=me['email']
     values['fax']=me['fax']
     values['email_2']=me['spareEmail']
     values['companyNationalIdentificationNumber']=me['companyNationalIdentificationNumber']
     values['state']=me['state']
     values['language']=me['language']
     
     _logger.info('vale zoneid   %s' % (me))
     self.write(cr, uid, ids, values, context=context)
    
     
     return True
Esempio n. 18
0
def main():
    module = AnsibleModule(
        argument_spec = dict(
            domain = dict(required=True),
            name = dict(default=''),
            value = dict(default=''),
            old_value = dict(default=''),
            type = dict(default='', choices=['A', 'AAAA', 'CNAME', 'DKIM', 'LOC', 'MX', 'NAPTR', 'NS', 'PTR', 'SPF', 'SRV', 'SSHFP', 'TXT']),
            state = dict(default='present', choices=['present', 'absent']),
        ),
        supports_check_mode = True
    )
    if not HAS_OVH_LIB:
        module.fail_json(msg='The "ovh" Python module is required')

    result = dict(
        changed=False,
        original_message='',
        message=''
    )

    result['original_message'] = module.params['name']

    # Get parameters
    domain = module.params.get('domain')
    name   = module.params.get('name')
    state  = module.params.get('state')
    fieldtype = module.params.get('type')
    targetval = module.params.get('value')
    old_targetval = module.params.get('old_value')

    # Connect to OVH API
    client = ovh.Client()

    # Check that the domain exists
    domains = client.get('/domain/zone')
    if not domain in domains:
        module.fail_json(msg='Domain {} does not exist'.format(domain), **result)

    # Obtain all domain records to check status against what is demanded
    records = get_domain_records(client, domain)
    current_record = check_record(records,name,fieldtype,targetval)
    old_record = check_record(records,name,fieldtype,old_targetval)
    response = [] 
    # Remove a record
    if state == 'absent':
        if not module.check_mode:
            if not current_record and name == "*":
                for record in records:
                    if record['fieldType'] != 'NS' and (fieldtype = '' or record['fieldtype'] == fieldtype):
                        response.append(client.delete('/domain/zone/{}/record/{}'.format(domain, record['id'])))
                        result['changed'] = True
            else:
                response.append(client.delete('/domain/zone/{}/record/{}'.format(domain, current_record)))
                response.append(client.post('/domain/zone/{}/refresh'.format(domain)))
                result['changed'] = True

            result['message'] = json.dumps(response)
            module.exit_json(**result)
Esempio n. 19
0
    def get_domain(self):

        client = ovh.Client(endpoint='ovh-eu')
        zone = '/domain'
        linerecordid = client.get(zone)
        c = len(linerecordid)
        print c
        print linerecordid
Esempio n. 20
0
 def get_size_extra(self, nodeid):
     client = ovh.Client(endpoint='ovh-eu')
     zone = '/cloud/project/%s/flavor/%s'%(self.projetid, nodeid)
     params ={}
     params['flavorId'] = nodeid
     nodeextra = client.get(zone) 
     
     return nodeextra
def load_dns_entries(zone, fieldtype, subdomain):
    client = ovh.Client()

    dns_entries = client.get('/domain/zone/{}/record'.format(zone),
                             fieldType=fieldtype,
                             subDomain=subdomain)

    return dns_entries
Esempio n. 22
0
def get_project(name):
    client = ovh.Client()
    projects = client.get('/cloud/project')
    for project_id in projects:
        project = client.get('/cloud/project/{}'.format(project_id))
        if project.get('description') == name:
            return project_id
    raise LookupError
Esempio n. 23
0
def update(dns):
    import ovh, sys
    client = ovh.Client()
    recid = client.get(
        '/domain/zone/isil.paris/record?subDomain=_minecraft._tcp')[0]
    client.put('/domain/zone/isil.paris/record/%d' % recid,
               target="0 0 25565 %s" % dns)
    print "Updated record %d" % recid
Esempio n. 24
0
    def get_plateforme(self):

        client = ovh.Client(endpoint='ovh-eu')
        zone = '/hosting/web/dedaluvia.com/serviceInfos'
        linerecordid = client.get(zone)
        c = len(linerecordid)
        print c
        print linerecordid
Esempio n. 25
0
 def _connect(self):
     self.client = ovh.Client(
         endpoint=self.endpoint,
         application_key=self.appkey_,
         application_secret=self.appsecret_,
         consumer_key=self.consumerkey_,
     )
     self.ipxeBase = self.ipxeBase
Esempio n. 26
0
 def __init__(self, endpoint, application_key, application_secret,
              consumer_key):
     self._client = ovh.Client(
         endpoint=conf['ovh_ids']['endpoint'],
         application_key=conf['ovh_ids']['app_key'],
         application_secret=conf['ovh_ids']['app_secret'],
         consumer_key=conf['ovh_ids']['consumer_key'])
     self._cache = {}
Esempio n. 27
0
def create_instance(project_id, name):
    client = ovh.Client()
    return client.post(
        '/cloud/project/{}/storage'.format(project_id),
        archive=False,
        containerName=name,
        region='UK',
    )
Esempio n. 28
0
 def verifieDisponibilitedomain(self, cr, uid, ids, context=None):
     """ se créer à ovh pour voir la disponibilité de command  """
     client = ovh.Client(endpoint='ovh-eu')
     for this in self.browse(cr, uid, ids, context):
         domain = this.domain
     dispo = soapi_ovh()
     result = dispo.domain_check(domain)
     if result:
         self.write(cr, uid, ids, {'state': 'valide'}, context=context)
Esempio n. 29
0
    def call_verif_domain_info(self, domain):

        client = ovh.Client(endpoint=self.endpoint)
        zone = '/domain/%s/serviceInfos ' % (domain)
        res = client.get(zone)['status']
        if res == 'ok' or res == 'inCreation':
            return True
        else:
            return False
Esempio n. 30
0
 def __init__(self):
     """
     relies on
     OVH_ENDPOINT
     OVH_APPLICATION_KEY
     OVH_APPLICATION_SECRET
     OVH_CONSUMER_KEY
     """
     self.ovh = _ovh.Client()