Exemple #1
0
    def create_resource(self, properties, location, is_full_object):
        res = json.loads(properties)
        if not is_full_object:
            if not location:
                if self.resource_id:
                    rg_name = parse_resource_id(self.resource_id)['resource_group']
                else:
                    rg_name = self.resource_group_name
                location = self.rcf.resource_groups.get(rg_name).location

            res = GenericResource(location=location, properties=res)
        elif res.get('location', None) is None:
            raise IncorrectUsageError("location of the resource is required")

        if self.resource_id:
            resource = self.rcf.resources.create_or_update_by_id(self.resource_id,
                                                                 self.api_version,
                                                                 res)
        else:
            resource = self.rcf.resources.create_or_update(self.resource_group_name,
                                                           self.resource_provider_namespace,
                                                           self.parent_resource_path or '',
                                                           self.resource_type,
                                                           self.resource_name,
                                                           self.api_version,
                                                           res)
        return resource
Exemple #2
0
    def create_resource(self, properties, location, is_full_object):
        res = json.loads(properties)
        if not is_full_object:
            if not location:
                if self.resource_id:
                    rg_name = parse_resource_id(self.resource_id)['resource_group']
                else:
                    rg_name = self.resource_group_name
                location = self.rcf.resource_groups.get(rg_name).location

            res = GenericResource(location=location, properties=res)
        elif res.get('location', None) is None:
            raise IncorrectUsageError("location of the resource is required")

        if self.resource_id:
            resource = self.rcf.resources.create_or_update_by_id(self.resource_id,
                                                                 self.api_version,
                                                                 res)
        else:
            resource = self.rcf.resources.create_or_update(self.resource_group_name,
                                                           self.resource_provider_namespace,
                                                           self.parent_resource_path or '',
                                                           self.resource_type,
                                                           self.resource_name,
                                                           self.api_version,
                                                           res)
        return resource
Exemple #3
0
    def update_resource_tags(tag_action, resource, tags):
        client = tag_action.session.client(
            'azure.mgmt.resource.ResourceManagementClient')

        # resource group type
        if is_resource_group(resource):
            params_patch = ResourceGroupPatchable(tags=tags)
            client.resource_groups.update(
                resource['name'],
                params_patch,
            )
        # other Azure resources
        else:
            # deserialize the original object
            az_resource = GenericResource.deserialize(resource)

            if not tag_action.manager.tag_operation_enabled(az_resource.type):
                raise NotImplementedError(
                    'Cannot tag resource with type {0}'.format(
                        az_resource.type))
            api_version = tag_action.session.resource_api_version(
                resource['id'])

            # create a PATCH object with only updates to tags
            tags_patch = GenericResource(tags=tags)

            client.resources.update_by_id(resource['id'], api_version,
                                          tags_patch)
    def update_resource_tags(tag_action, resource, tags):
        client = tag_action.session.client(
            'azure.mgmt.resource.ResourceManagementClient')

        # resource group type
        if tag_action.manager.type == 'resourcegroup':
            params_patch = ResourceGroupPatchable(tags=tags)
            client.resource_groups.update(
                resource['name'],
                params_patch,
            )
        # other Azure resources
        else:
            # deserialize the original object
            az_resource = GenericResource.deserialize(resource)

            if not tag_action.manager.tag_operation_enabled(az_resource.type):
                raise NotImplementedError(
                    'Cannot tag resource with type {0}'.format(
                        az_resource.type))
            api_version = tag_action.session.resource_api_version(
                resource['id'])

            # create a GenericResource object with the required parameters
            generic_resource = GenericResource(
                location=az_resource.location,
                tags=tags,
                properties=az_resource.properties,
                kind=az_resource.kind,
                managed_by=az_resource.managed_by,
                identity=az_resource.identity)

            client.resources.update_by_id(resource['id'], api_version,
                                          generic_resource)
Exemple #5
0
    def _process_resource(self, resource):
        resource['sku']['capacity'] = self.capacity
        resource['sku']['tier'] = self.tier
        resource['sku']['name'] = self.tier

        az_resource = GenericResource.deserialize(resource)

        api_version = self.session.resource_api_version(resource['id'])

        # create a GenericResource object with the required parameters
        generic_resource = GenericResource(sku=az_resource.sku)

        self.client.resources.update_by_id(resource['id'], api_version, generic_resource)
Exemple #6
0
def tag_resource(resource_group_name,
                 resource_name,
                 resource_type,
                 tags,
                 parent_resource_path=None,
                 api_version=None,
                 resource_provider_namespace=None):
    ''' Updates the tags on an existing resource. To clear tags, specify the --tag option
    without anything else. '''
    rcf = _resource_client_factory()
    resource = rcf.resources.get(resource_group_name,
                                 resource_provider_namespace,
                                 parent_resource_path, resource_type,
                                 resource_name, api_version)
    # pylint: disable=no-member
    parameters = GenericResource(location=resource.location,
                                 tags=tags,
                                 plan=resource.plan,
                                 properties=resource.properties,
                                 kind=resource.kind,
                                 managed_by=resource.managed_by,
                                 sku=resource.sku,
                                 identity=resource.identity)
    try:
        rcf.resources.create_or_update(resource_group_name,
                                       resource_provider_namespace,
                                       parent_resource_path, resource_type,
                                       resource_name, api_version, parameters)
    except CloudError as ex:
        # TODO: Remove workaround once Swagger and SDK fix is implemented (#120123723)
        if '202' not in str(ex):
            raise ex
Exemple #7
0
    def process(self, resources):
        session = utils.local_session(self.manager.session_factory)
        client = self.manager.get_client('azure.mgmt.resource.ResourceManagementClient')

        for resource in resources:
            # get existing tags
            tags = resource.get('tags', {})

            # add or update tags
            new_tags = self.data.get('tags') or {self.data.get('tag'): self.data.get('value')}
            for key in new_tags:
                tags[key] = new_tags[key]

            # resource group type
            if self.manager.type == 'resourcegroup':
                params_patch = ResourceGroupPatchable(
                    tags=tags
                )
                client.resource_groups.update(
                    resource['name'],
                    params_patch,
                )
            # other Azure resources
            else:
                az_resource = GenericResource.deserialize(resource)
                api_version = session.resource_api_version(az_resource.id)
                az_resource.tags = tags

                client.resources.create_or_update_by_id(resource['id'], api_version, az_resource)
def get_resource(existing_tags):
    resource = GenericResource(tags=existing_tags).serialize()
    resource['id'] = '/subscriptions/ea42f556-5106-4743-99b0-c129bfa71a47/resourceGroups/' \
                     'TEST_VM/providers/Microsoft.Compute/virtualMachines/cctestvm'
    resource['name'] = 'cctestvm'
    resource['type'] = 'Microsoft.Compute/virtualMachines'
    return resource
Exemple #9
0
    def update_resource_tags(tag_action, resource, tags):
        client = tag_action.session.client('azure.mgmt.resource.ResourceManagementClient')

        # resource group type
        if tag_action.manager.type == 'resourcegroup':
            params_patch = ResourceGroupPatchable(
                tags=tags
            )
            client.resource_groups.update(
                resource['name'],
                params_patch,
            )
        # other Azure resources
        else:
            # generic armresource tagging isn't supported yet Github issue #2637
            if tag_action.manager.type == 'armresource':
                raise NotImplementedError('Cannot tag generic ARM resources.')

            api_version = tag_action.session.resource_api_version(resource['id'])

            # deserialize the original object
            az_resource = GenericResource.deserialize(resource)

            # create a GenericResource object with the required parameters
            generic_resource = GenericResource(location=az_resource.location,
                                               tags=tags,
                                               properties=az_resource.properties,
                                               kind=az_resource.kind,
                                               managed_by=az_resource.managed_by,
                                               identity=az_resource.identity)

            client.resources.update_by_id(resource['id'], api_version, generic_resource)
Exemple #10
0
def get_resource_group_resource(existing_tags):
    resource = GenericResource(tags=existing_tags).serialize()
    resource[
        'id'] = '/subscriptions/ea42f556-5106-4743-99b0-c129bfa71a47/resourceGroups/test_rg'
    resource['name'] = 'test_rg'
    resource['type'] = 'resourceGroups'
    return resource
Exemple #11
0
    def process(self, resources):
        session = utils.local_session(self.manager.session_factory)
        client = self.manager.get_client(
            'azure.mgmt.resource.ResourceManagementClient')

        for resource in resources:
            # get existing tags
            tags = resource.get('tags', {})

            # add or update tags
            new_tags = self.data.get('tags') or {
                self.data.get('tag'): self.data.get('value')
            }
            for key in new_tags:
                tags[key] = new_tags[key]

            # resource group type
            if self.manager.type == 'resourcegroup':
                params_patch = ResourceGroupPatchable(tags=tags)
                client.resource_groups.update(
                    resource['name'],
                    params_patch,
                )
            # other Azure resources
            else:
                az_resource = GenericResource.deserialize(resource)
                api_version = session.resource_api_version(az_resource.id)
                az_resource.tags = tags

                client.resources.create_or_update_by_id(
                    resource['id'], api_version, az_resource)
Exemple #12
0
    def tag(self, tags):
        resource = self.get_resource()
        # pylint: disable=no-member
        parameters = GenericResource(
            location=resource.location,
            tags=tags,
            plan=resource.plan,
            properties=resource.properties,
            kind=resource.kind,
            managed_by=resource.managed_by,
            sku=resource.sku,
            identity=resource.identity)

        if self.resource_id:
            return self.rcf.resources.create_or_update_by_id(self.resource_id, self.api_version,
                                                             parameters)
        else:
            return self.rcf.resources.create_or_update(
                self.resource_group_name,
                self.resource_provider_namespace,
                self.parent_resource_path or '',
                self.resource_type,
                self.resource_name,
                self.api_version,
                parameters)
Exemple #13
0
    def update_resource_tags(tag_action, resource, tags):
        client = tag_action.session.client(
            'azure.mgmt.resource.ResourceManagementClient')

        # resource group type
        if tag_action.manager.type == 'resourcegroup':
            params_patch = ResourceGroupPatchable(tags=tags)
            client.resource_groups.update(
                resource['name'],
                params_patch,
            )
        # other Azure resources
        else:
            # generic armresource tagging isn't supported yet Github issue #2637
            if tag_action.manager.type == 'armresource':
                raise NotImplementedError('Cannot tag generic ARM resources.')

            api_version = tag_action.session.resource_api_version(
                resource['id'])

            # deserialize the original object
            az_resource = GenericResource.deserialize(resource)

            # create a GenericResource object with the required parameters
            generic_resource = GenericResource(
                location=az_resource.location,
                tags=tags,
                properties=az_resource.properties,
                kind=az_resource.kind,
                managed_by=az_resource.managed_by,
                sku=az_resource.sku,
                identity=az_resource.identity)

            try:
                client.resources.update_by_id(resource['id'], api_version,
                                              generic_resource)
            except Exception as e:
                log.error("Failed to update tags for the resource.\n"
                          "Type: {0}.\n"
                          "Name: {1}.\n"
                          "Error: {2}".format(resource['type'],
                                              resource['name'], e))
Exemple #14
0
def update_resource_tags(self, session, client, resource, tags):
    # resource group type
    if self.manager.type == 'resourcegroup':
        params_patch = ResourceGroupPatchable(
            tags=tags
        )
        client.resource_groups.update(
            resource['name'],
            params_patch,
        )
    # other Azure resources
    else:
        az_resource = GenericResource.deserialize(resource)
        api_version = session.resource_api_version(az_resource.id)
        az_resource.tags = tags

        client.resources.create_or_update_by_id(resource['id'], api_version, az_resource)
Exemple #15
0
def update_resource_tags(self, resource, tags):

    # resource group type
    if self.manager.type == 'resourcegroup':
        params_patch = ResourceGroupPatchable(
            tags=tags
        )
        self.client.resource_groups.update(
            resource['name'],
            params_patch,
        )
    # other Azure resources
    else:
        az_resource = GenericResource.deserialize(resource)
        api_version = self.session.resource_api_version(az_resource.id)
        az_resource.tags = tags

        self.client.resources.create_or_update_by_id(resource['id'], api_version, az_resource)
    def test_resize_plan_from_resource_tag(self):
        web_management_client = self.session.client(
            'azure.mgmt.web.WebSiteManagementClient')
        app_plan = web_management_client.app_service_plans.get(
            'test_appserviceplan', 'cctest-appserviceplan-win')

        self.assertNotEqual(app_plan.sku.name, 'B1')

        resource_client = self.session.client(
            'azure.mgmt.resource.ResourceManagementClient')

        tags_patch = GenericResource(tags={'sku': 'B1'})
        resource_client.resources.update_by_id(app_plan.id, "2016-09-01",
                                               tags_patch)

        p = self.load_policy({
            'name':
            'test-azure-appserviceplan',
            'resource':
            'azure.appserviceplan',
            'filters': [{
                'type': 'value',
                'key': 'name',
                'op': 'eq',
                'value_type': 'normalize',
                'value': 'cctest-appserviceplan-win'
            }],
            'actions': [{
                'type': 'resize-plan',
                'size': {
                    'type': 'resource',
                    'key': 'tags.sku'
                }
            }],
        })

        resources = p.run()
        self.assertEqual(len(resources), 1)

        app_plan = web_management_client.app_service_plans.get(
            'test_appserviceplan', 'cctest-appserviceplan-win')
        self.assertEqual(app_plan.sku.name, 'B1')
Exemple #17
0
def update_resource_tags(self, resource, tags):

    # resource group type
    if self.manager.type == 'resourcegroup':
        params_patch = ResourceGroupPatchable(tags=tags)
        self.client.resource_groups.update(
            resource['name'],
            params_patch,
        )
    # other Azure resources
    else:
        if self.manager.type == 'armresource':
            raise NotImplementedError('Cannot tag generic ARM resources.')

        az_resource = GenericResource.deserialize(resource)
        api_version = self.session.resource_api_version(az_resource.id)
        az_resource.tags = tags

        self.client.resources.create_or_update_by_id(resource['id'],
                                                     api_version, az_resource)
Exemple #18
0
    def process(self, resources):
        session = utils.local_session(self.manager.session_factory)
        client = session.client('azure.mgmt.resource.ResourceManagementClient')

        for resource in resources:
            id = resource['id']

            tags = self.data.get('tags') or resource.get('tags', {})
            tag = self.data.get('tag')
            value = self.data.get('value')

            if tag and value:
                tags[tag] = value

            az_resource = GenericResource.deserialize(resource)
            api_version = session.resource_api_version(az_resource)
            az_resource.tags = tags

            client.resources.create_or_update_by_id(id, api_version,
                                                    az_resource)
Exemple #19
0
    def run(self, subscription_id, group_name, resource_name,
            resource_provider_namespace, resource_type, parent_resource_path,
            api_version, location):
        credentials = self.credentials

        resource_client = ResourceManagementClient(
            ResourceManagementClientConfiguration(credentials,
                                                  subscription_id))

        result = resource_client.resources.create_or_update(
            group_name,
            resource_provider_namespace=resource_provider_namespace,
            parent_resource_path=parent_resource_path,
            resource_type=resource_type,
            resource_name=resource_name,
            api_version=api_version,
            parameters=GenericResource(
                location=location,
                properties={},
            ),
        )
        return result
Exemple #20
0
    def update_resource_tags(tag_action, resource, tags):
        client = tag_action.session.client('azure.mgmt.resource.ResourceManagementClient')

        # resource group type
        if tag_action.manager.type == 'resourcegroup':
            params_patch = ResourceGroupPatchable(
                tags=tags
            )
            client.resource_groups.update(
                resource['name'],
                params_patch,
            )
        # other Azure resources
        else:
            if tag_action.manager.type == 'armresource':
                raise NotImplementedError('Cannot tag generic ARM resources.')

            az_resource = GenericResource.deserialize(resource)
            api_version = tag_action.session.resource_api_version(az_resource.id)
            az_resource.tags = tags

            client.resources.create_or_update_by_id(resource['id'], api_version, az_resource)
    def exec_module(self, **kwargs):
        for key in list(self.module_arg_spec.keys()) + ['tags', 'append_tags']:
            setattr(self, key, kwargs[key])

        self.results['check_mode'] = self.check_mode

        resource_group = self.get_resource_group(self.resource_group)
        if not self.location:
            # Set default location
            self.location = resource_group.location

        if not self.parent_resource_path:
            self.parent_resource_path = ''

        if not self.api_version:
            self.api_version = self.resolve_api_version()

        changed = False
        results = dict()
        resource = None

        try:
            self.log('Fetching resource {}'.format(self.name))
            resource = self.rm_client.resources.get(self.resource_group, self.provider_namespace,
                                                    self.parent_resource_path,
                                                    self.resource_type, self.name, self.api_version)
            results = self.serialize_obj(resource, AZURE_OBJECT_CLASS)
            self.check_provisioning_state(resource, self.state)

            self.results['state'] = results

            if self.state == 'present' and self.update:
                changed, self.results['state'] = self._check_resource_changed(results)
                update_tags, self.results['state']['tags'] = self.update_tags(results.get('tags'))
                if update_tags:
                    changed = True
            else:
                changed = True
        except ClientRequestError as ex:
            # Workaroung for some failing API calls for non-existing resources (e.g. RecoveryVault
            # backup items, amongst others)
            if ex.message == 'too many 500 error responses':
                # Resource doesn't exist
                pass
        except CloudError:
            changed = self.state == 'present'

        self.results['changed'] = changed

        if self.check_mode:
            return self.results

        if changed:
            if self.state == 'present':
                plan_object = None if not self.results['state'].get('plan') \
                              else Plan(self.results['state']['plan'])
                sku_object = None if not self.results['state'].get('sku') \
                              else Sku(self.results['state']['sku'])
                identity_object = None if not self.results['state'].get('identity') \
                              else Identity(self.results['state']['identity'])
                resource_object = GenericResource(
                    location=self.results['state'].get('location'),
                    tags=self.results['state'].get('tags'),
                    plan=plan_object, properties=self.results['state'].get('properties'),
                    kind=self.results['state'].get('kind'),
                    managed_by=self.results['state'].get('managed_by'), sku=sku_object,
                    identity=identity_object
                )
                self.results['state'] = self._create_or_update_resource(resource_object)
            elif self.state == 'absent':
                self._delete_resource()

        return self.results