def test_snake_to_camel_reversed(self):
     for (k, v) in EXPECTED_REVERSIBLE.items():
         self.assertEqual(_snake_to_camel(v, capitalize_first=True), k)
 def test_camel_to_snake_and_back(self):
     for (k, v) in EXPECTED_REVERSIBLE.items():
         self.assertEqual(
             _snake_to_camel(_camel_to_snake(k, reversible=True),
                             capitalize_first=True), k)
    def exec_module(self, **kwargs):

        for key in list(self.module_arg_spec.keys()):
            setattr(self, key, kwargs[key])

        changed = False

        original = self.get()
        if self.state == 'present':
            # Create the resource instance
            params = dict(
                dead_lettering_on_filter_evaluation_exceptions=self.dead_lettering_on_filter_evaluation_exceptions,
                dead_lettering_on_message_expiration=self.dead_lettering_on_message_expiration,
                enable_batched_operations=self.enable_batched_operations,
                forward_dead_lettered_messages_to=self.forward_dead_lettered_messages_to,
                forward_to=self.forward_to,
                max_delivery_count=self.max_delivery_count,
                requires_session=self.requires_session
            )
            if self.status:
                params['status'] = self.servicebus_models.EntityStatus(str.capitalize(_snake_to_camel(self.status)))
            for k, v in duration_spec_map.items():
                seconds = getattr(self, v)
                if seconds:
                    params[k] = timedelta(seconds=seconds)

            instance = self.servicebus_models.SBSubscription(**params)
            result = original
            if not original:
                changed = True
                result = instance
            else:
                result = original
                attribute_map_keys = set(self.servicebus_models.SBSubscription._attribute_map.keys())
                validation_keys = set(self.servicebus_models.SBSubscription._validation.keys())
                attribute_map = attribute_map_keys - validation_keys
                for attribute in attribute_map:
                    value = getattr(instance, attribute)
                    if value and value != getattr(original, attribute):
                        changed = True
            if changed and not self.check_mode:
                result = self.create_or_update(instance)
            self.results = self.to_dict(result)
        elif original:
            changed = True
            if not self.check_mode:
                self.delete()
                self.results['deleted'] = True

        self.results['changed'] = changed
        return self.results
    def exec_module(self, **kwargs):
        """Main module execution method"""

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            if hasattr(self, key):
                setattr(self, key, kwargs[key])
            elif kwargs[key] is not None:
                self.batch_account[key] = kwargs[key]

        resource_group = self.get_resource_group(self.resource_group)
        if self.batch_account.get('location') is None:
            self.batch_account['location'] = resource_group.location
        if self.batch_account.get('auto_storage_account') is not None:
            self.batch_account['auto_storage'] = {
                'storage_account_id':
                self.normalize_resource_id(
                    self.batch_account.pop('auto_storage_account'),
                    '/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.Storage/storageAccounts/{name}'
                )
            }
        if self.batch_account.get('key_vault') is not None:
            id = self.normalize_resource_id(
                self.batch_account.pop('key_vault'),
                '/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.KeyVault/vaults/{name}'
            )
            url = 'https://' + id.split('/').pop() + '.vault.azure.net/'
            self.batch_account['key_vault_reference'] = {'id': id, 'url': url}
        self.batch_account['pool_allocation_mode'] = _snake_to_camel(
            self.batch_account['pool_allocation_mode'], True)

        response = None

        self.mgmt_client = self.get_mgmt_svc_client(
            BatchManagementClient,
            base_url=self._cloud_environment.endpoints.resource_manager)

        old_response = self.get_batchaccount()

        if not old_response:
            self.log("Batch Account instance doesn't exist")
            if self.state == 'absent':
                self.log("Old instance didn't exist")
            else:
                self.to_do = Actions.Create
        else:
            self.log("Batch Account instance already exists")
            if self.state == 'absent':
                self.to_do = Actions.Delete
            elif self.state == 'present':
                self.results['old'] = old_response
                self.results['new'] = self.batch_account
                if not self.idempotency_check(old_response,
                                              self.batch_account):
                    self.to_do = Actions.Update

        if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
            self.log("Need to Create / Update the Batch Account instance")

            self.results['changed'] = True
            if self.check_mode:
                return self.results

            response = self.create_update_batchaccount()

            self.log("Creation / Update done")
        elif self.to_do == Actions.Delete:
            self.log("Batch Account instance deleted")
            self.results['changed'] = True

            if self.check_mode:
                return self.results

            self.delete_batchaccount()
        else:
            self.log("Batch Account instance unchanged")
            self.results['changed'] = False
            response = old_response

        if self.state == 'present':
            self.results.update({
                'id':
                response.get('id', None),
                'account_endpoint':
                response.get('account_endpoint', None)
            })
        return self.results
示例#5
0
    def exec_module(self, **kwargs):
        """Main module execution method"""

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            if hasattr(self, key):
                setattr(self, key, kwargs[key])
            elif kwargs[key] is not None:
                if key == "id":
                    self.parameters["id"] = kwargs[key]
                elif key == "location":
                    self.parameters["location"] = kwargs[key]
                elif key == "sku":
                    ev = kwargs[key]
                    if 'name' in ev:
                        if ev['name'] == 'standard_small':
                            ev['name'] = 'Standard_Small'
                        elif ev['name'] == 'standard_medium':
                            ev['name'] = 'Standard_Medium'
                        elif ev['name'] == 'standard_large':
                            ev['name'] = 'Standard_Large'
                        elif ev['name'] == 'waf_medium':
                            ev['name'] = 'WAF_Medium'
                        elif ev['name'] == 'waf_large':
                            ev['name'] = 'WAF_Large'
                    if 'tier' in ev:
                        if ev['tier'] == 'standard':
                            ev['tier'] = 'Standard'
                        elif ev['tier'] == 'waf':
                            ev['tier'] = 'WAF'
                    self.parameters["sku"] = ev
                elif key == "ssl_policy":
                    ev = kwargs[key]
                    if 'policy_type' in ev:
                        ev['policy_type'] = _snake_to_camel(
                            ev['policy_type'], True)
                    if 'policy_name' in ev:
                        if ev['policy_name'] == 'ssl_policy20150501':
                            ev['policy_name'] = 'AppGwSslPolicy20150501'
                        elif ev['policy_name'] == 'ssl_policy20170401':
                            ev['policy_name'] = 'AppGwSslPolicy20170401'
                        elif ev['policy_name'] == 'ssl_policy20170401_s':
                            ev['policy_name'] = 'AppGwSslPolicy20170401S'
                    if 'min_protocol_version' in ev:
                        if ev['min_protocol_version'] == 'tls_v1_0':
                            ev['min_protocol_version'] = 'TLSv1_0'
                        elif ev['min_protocol_version'] == 'tls_v1_1':
                            ev['min_protocol_version'] = 'TLSv1_1'
                        elif ev['min_protocol_version'] == 'tls_v1_2':
                            ev['min_protocol_version'] = 'TLSv1_2'
                    if 'disabled_ssl_protocols' in ev:
                        protocols = ev['disabled_ssl_protocols']
                        if protocols is not None:
                            for i in range(len(protocols)):
                                if protocols[i] == 'tls_v1_0':
                                    protocols[i] = 'TLSv1_0'
                                elif protocols[i] == 'tls_v1_1':
                                    protocols[i] = 'TLSv1_1'
                                elif protocols[i] == 'tls_v1_2':
                                    protocols[i] = 'TLSv1_2'
                    if 'cipher_suites' in ev:
                        suites = ev['cipher_suites']
                        if suites is not None:
                            for i in range(len(suites)):
                                suites[i] = suites[i].upper()
                elif key == "gateway_ip_configurations":
                    self.parameters["gateway_ip_configurations"] = kwargs[key]
                elif key == "authentication_certificates":
                    self.parameters["authentication_certificates"] = kwargs[
                        key]
                elif key == "ssl_certificates":
                    self.parameters["ssl_certificates"] = kwargs[key]
                elif key == "redirect_configurations":
                    ev = kwargs[key]
                    for i in range(len(ev)):
                        item = ev[i]
                        if 'redirect_type' in item:
                            item['redirect_type'] = _snake_to_camel(
                                item['redirect_type'], True)
                        if 'target_listener' in item:
                            id = http_listener_id(self.subscription_id,
                                                  kwargs['resource_group'],
                                                  kwargs['name'],
                                                  item['target_listener'])
                            item['target_listener'] = {'id': id}
                    self.parameters["redirect_configurations"] = ev
                elif key == "frontend_ip_configurations":
                    ev = kwargs[key]
                    for i in range(len(ev)):
                        item = ev[i]
                        if 'private_ip_allocation_method' in item:
                            item[
                                'private_ip_allocation_method'] = _snake_to_camel(
                                    item['private_ip_allocation_method'], True)
                        if 'public_ip_address' in item:
                            id = public_ip_id(self.subscription_id,
                                              kwargs['resource_group'],
                                              item['public_ip_address'])
                            item['public_ip_address'] = {'id': id}
                    self.parameters["frontend_ip_configurations"] = ev
                elif key == "frontend_ports":
                    self.parameters["frontend_ports"] = kwargs[key]
                elif key == "backend_address_pools":
                    self.parameters["backend_address_pools"] = kwargs[key]
                elif key == "probes":
                    ev = kwargs[key]
                    for i in range(len(ev)):
                        item = ev[i]
                        if 'protocol' in item:
                            item['protocol'] = _snake_to_camel(
                                item['protocol'], True)
                    self.parameters["probes"] = ev
                elif key == "backend_http_settings_collection":
                    ev = kwargs[key]
                    for i in range(len(ev)):
                        item = ev[i]
                        if 'protocol' in item:
                            item['protocol'] = _snake_to_camel(
                                item['protocol'], True)
                        if 'cookie_based_affinity' in item:
                            item['cookie_based_affinity'] = _snake_to_camel(
                                item['cookie_based_affinity'], True)
                        if 'probe' in item:
                            id = probe_id(self.subscription_id,
                                          kwargs['resource_group'],
                                          kwargs['name'], item['probe'])
                            item['probe'] = {'id': id}
                    self.parameters["backend_http_settings_collection"] = ev
                elif key == "http_listeners":
                    ev = kwargs[key]
                    for i in range(len(ev)):
                        item = ev[i]
                        if 'frontend_ip_configuration' in item:
                            id = frontend_ip_configuration_id(
                                self.subscription_id, kwargs['resource_group'],
                                kwargs['name'],
                                item['frontend_ip_configuration'])
                            item['frontend_ip_configuration'] = {'id': id}

                        if 'frontend_port' in item:
                            id = frontend_port_id(self.subscription_id,
                                                  kwargs['resource_group'],
                                                  kwargs['name'],
                                                  item['frontend_port'])
                            item['frontend_port'] = {'id': id}
                        if 'ssl_certificate' in item:
                            id = ssl_certificate_id(self.subscription_id,
                                                    kwargs['resource_group'],
                                                    kwargs['name'],
                                                    item['ssl_certificate'])
                            item['ssl_certificate'] = {'id': id}
                        if 'protocol' in item:
                            item['protocol'] = _snake_to_camel(
                                item['protocol'], True)
                        ev[i] = item
                    self.parameters["http_listeners"] = ev
                elif key == "request_routing_rules":
                    ev = kwargs[key]
                    for i in range(len(ev)):
                        item = ev[i]
                        if 'backend_address_pool' in item:
                            id = backend_address_pool_id(
                                self.subscription_id, kwargs['resource_group'],
                                kwargs['name'], item['backend_address_pool'])
                            item['backend_address_pool'] = {'id': id}
                        if 'backend_http_settings' in item:
                            id = backend_http_settings_id(
                                self.subscription_id, kwargs['resource_group'],
                                kwargs['name'], item['backend_http_settings'])
                            item['backend_http_settings'] = {'id': id}
                        if 'http_listener' in item:
                            id = http_listener_id(self.subscription_id,
                                                  kwargs['resource_group'],
                                                  kwargs['name'],
                                                  item['http_listener'])
                            item['http_listener'] = {'id': id}
                        if 'protocol' in item:
                            item['protocol'] = _snake_to_camel(
                                item['protocol'], True)
                        if 'rule_type' in ev:
                            item['rule_type'] = _snake_to_camel(
                                item['rule_type'], True)
                        if 'redirect_configuration' in item:
                            id = redirect_configuration_id(
                                self.subscription_id, kwargs['resource_group'],
                                kwargs['name'], item['redirect_configuration'])
                            item['redirect_configuration'] = {'id': id}
                        ev[i] = item
                    self.parameters["request_routing_rules"] = ev
                elif key == "etag":
                    self.parameters["etag"] = kwargs[key]

        old_response = None
        response = None

        self.mgmt_client = self.get_mgmt_svc_client(
            NetworkManagementClient,
            base_url=self._cloud_environment.endpoints.resource_manager)

        resource_group = self.get_resource_group(self.resource_group)

        if "location" not in self.parameters:
            self.parameters["location"] = resource_group.location

        old_response = self.get_applicationgateway()

        if not old_response:
            self.log("Application Gateway instance doesn't exist")
            if self.state == 'absent':
                self.log("Old instance didn't exist")
            else:
                self.to_do = Actions.Create
        else:
            self.log("Application Gateway instance already exists")
            if self.state == 'absent':
                self.to_do = Actions.Delete
            elif self.state == 'present':
                self.log(
                    "Need to check if Application Gateway instance has to be deleted or may be updated"
                )
                self.to_do = Actions.Update

        if (self.to_do == Actions.Update):
            if (self.parameters['location'] != old_response['location']
                    or self.parameters['sku']['name'] !=
                    old_response['sku']['name']
                    or self.parameters['sku']['tier'] !=
                    old_response['sku']['tier']
                    or self.parameters['sku']['capacity'] !=
                    old_response['sku']['capacity']
                    or not compare_arrays(old_response, self.parameters,
                                          'authentication_certificates')
                    or not compare_arrays(old_response, self.parameters,
                                          'gateway_ip_configurations')
                    or not compare_arrays(old_response, self.parameters,
                                          'redirect_configurations')
                    or not compare_arrays(old_response, self.parameters,
                                          'frontend_ip_configurations')
                    or not compare_arrays(old_response, self.parameters,
                                          'frontend_ports')
                    or not compare_arrays(old_response, self.parameters,
                                          'backend_address_pools') or
                    not compare_arrays(old_response, self.parameters, 'probes')
                    or not compare_arrays(old_response, self.parameters,
                                          'backend_http_settings_collection')
                    or not compare_arrays(old_response, self.parameters,
                                          'request_routing_rules')
                    or not compare_arrays(old_response, self.parameters,
                                          'http_listeners')):

                self.to_do = Actions.Update
            else:
                self.to_do = Actions.NoAction

        if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
            self.log(
                "Need to Create / Update the Application Gateway instance")

            if self.check_mode:
                self.results['changed'] = True
                self.results["parameters"] = self.parameters
                return self.results

            response = self.create_update_applicationgateway()

            if not old_response:
                self.results['changed'] = True
            else:
                self.results['changed'] = old_response.__ne__(response)
            self.log("Creation / Update done")
        elif self.to_do == Actions.Delete:
            self.log("Application Gateway instance deleted")
            self.results['changed'] = True

            if self.check_mode:
                return self.results

            self.delete_applicationgateway()
            # make sure instance is actually deleted, for some Azure resources, instance is hanging around
            # for some time after deletion -- this should be really fixed in Azure
            while self.get_applicationgateway():
                time.sleep(20)
        else:
            self.log("Application Gateway instance unchanged")
            self.results['changed'] = False
            response = old_response

        if response:
            self.results["id"] = response["id"]

        return self.results
示例#6
0
    def exec_module(self, **kwargs):
        """Main module execution method"""

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            if hasattr(self, key):
                setattr(self, key, kwargs[key])
            elif kwargs[key] is not None:
                self.lab_virtual_machine[key] = kwargs[key]

        self.lab_virtual_machine[
            'gallery_image_reference'] = self.lab_virtual_machine.pop(
                'image', None)

        if self.lab_virtual_machine.get('artifacts') is not None:
            for artifact in self.lab_virtual_machine.get('artifacts'):
                source_name = artifact.pop('source_name')
                source_path = artifact.pop('source_path')
                template = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.DevTestLab/labs/{2}/artifactsources/{3}{4}"
                artifact['artifact_id'] = template.format(
                    self.subscription_id, self.resource_group, self.lab_name,
                    source_name, source_path)

        self.lab_virtual_machine['size'] = self.lab_virtual_machine.pop(
            'vm_size')
        self.lab_virtual_machine['os_type'] = _snake_to_camel(
            self.lab_virtual_machine['os_type'], True)

        if self.lab_virtual_machine.get('storage_type'):
            self.lab_virtual_machine['storage_type'] = _snake_to_camel(
                self.lab_virtual_machine['storage_type'], True)

        lab_subnet = self.lab_virtual_machine.pop('lab_subnet')

        if isinstance(lab_subnet, str):
            vn_and_subnet = lab_subnet.split('/subnets/')
            if (len(vn_and_subnet) == 2):
                self.lab_virtual_machine[
                    'lab_virtual_network_id'] = vn_and_subnet[0]
                self.lab_virtual_machine['lab_subnet_name'] = vn_and_subnet[1]
            else:
                self.fail("Invalid 'lab_subnet' resource id format")
        else:
            template = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.DevTestLab/labs/{2}/virtualnetworks/{3}"
            self.lab_virtual_machine[
                'lab_virtual_network_id'] = template.format(
                    self.subscription_id, self.resource_group, self.lab_name,
                    lab_subnet.get('virtual_network_name'))
            self.lab_virtual_machine['lab_subnet_name'] = lab_subnet.get(
                'name')

        response = None

        self.mgmt_client = self.get_mgmt_svc_client(
            DevTestLabsClient,
            base_url=self._cloud_environment.endpoints.resource_manager)

        old_response = self.get_virtualmachine()

        if not old_response:
            self.log("Virtual Machine instance doesn't exist")
            if self.state == 'absent':
                self.log("Old instance didn't exist")
            else:
                self.to_do = Actions.Create
            # get location from the lab as it has to be the same and has to be specified (why??)
            lab = self.get_devtestlab()
            self.lab_virtual_machine['location'] = lab['location']
        else:
            self.log("Virtual Machine instance already exists")
            if self.state == 'absent':
                self.to_do = Actions.Delete
            elif self.state == 'present':
                self.lab_virtual_machine['location'] = old_response['location']

                if old_response['size'].lower(
                ) != self.lab_virtual_machine.get('size').lower():
                    self.lab_virtual_machine['size'] = old_response['size']
                    self.module.warn("Property 'size' cannot be changed")

                if self.lab_virtual_machine.get('storage_type') is not None and \
                   old_response['storage_type'].lower() != self.lab_virtual_machine.get('storage_type').lower():
                    self.lab_virtual_machine['storage_type'] = old_response[
                        'storage_type']
                    self.module.warn(
                        "Property 'storage_type' cannot be changed")

                if old_response.get('gallery_image_reference',
                                    {}) != self.lab_virtual_machine.get(
                                        'gallery_image_reference', {}):
                    self.lab_virtual_machine[
                        'gallery_image_reference'] = old_response[
                            'gallery_image_reference']
                    self.module.warn("Property 'image' cannot be changed")

                # currently artifacts can be only specified when vm is created
                # and in addition we don't have detailed information, just a number of "total artifacts"
                if len(self.lab_virtual_machine.get(
                        'artifacts', [])) != old_response[
                            'artifact_deployment_status']['total_artifacts']:
                    self.module.warn("Property 'artifacts' cannot be changed")

                if self.lab_virtual_machine.get(
                        'disallow_public_ip_address') is not None:
                    if old_response[
                            'disallow_public_ip_address'] != self.lab_virtual_machine.get(
                                'disallow_public_ip_address'):
                        self.module.warn(
                            "Property 'disallow_public_ip_address' cannot be changed"
                        )
                self.lab_virtual_machine[
                    'disallow_public_ip_address'] = old_response[
                        'disallow_public_ip_address']

                if self.lab_virtual_machine.get('allow_claim') is not None:
                    if old_response[
                            'allow_claim'] != self.lab_virtual_machine.get(
                                'allow_claim'):
                        self.module.warn(
                            "Property 'allow_claim' cannot be changed")
                self.lab_virtual_machine['allow_claim'] = old_response[
                    'allow_claim']

                if self.lab_virtual_machine.get('notes') is not None:
                    if old_response['notes'] != self.lab_virtual_machine.get(
                            'notes'):
                        self.to_do = Actions.Update
                else:
                    self.lab_virtual_machine['notes'] = old_response['notes']

        if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
            self.log("Need to Create / Update the Virtual Machine instance")

            self.results['changed'] = True
            if self.check_mode:
                return self.results

            response = self.create_update_virtualmachine()

            self.log("Creation / Update done")
        elif self.to_do == Actions.Delete:
            self.log("Virtual Machine instance deleted")
            self.results['changed'] = True

            if self.check_mode:
                return self.results

            self.delete_virtualmachine()
        else:
            self.log("Virtual Machine instance unchanged")
            self.results['changed'] = False
            response = old_response

        if self.state == 'present':
            self.results.update({
                'id': response.get('id', None),
                'compute_id': response.get('compute_id', None),
                'fqdn': response.get('fqdn', None)
            })
        return self.results
    def exec_module(self, **kwargs):

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            setattr(self, key, kwargs[key])

        self.results = dict()
        changed = False

        if not self.location:
            resource_group = self.get_resource_group(self.resource_group)
            self.location = resource_group.location

        if self.sku == 'per_gb2018':
            self.sku = 'PerGB2018'
        else:
            self.sku = _snake_to_camel(self.sku)
        workspace = self.get_workspace()
        if not workspace and self.state == 'present':
            changed = True
            workspace = self.log_analytics_models.Workspace(
                sku=self.log_analytics_models.WorkspaceSku(name=self.sku),
                retention_in_days=self.retention_in_days,
                location=self.location,
                tags=self.tags)
            if not self.check_mode:
                workspace = self.create_workspace(workspace)
        elif workspace and self.state == 'present':
            if workspace.retention_in_days != self.retention_in_days:
                changed = True
            results = dict()
            update_tags, results['tags'] = self.update_tags(workspace.tags)
            if update_tags:
                changed = True
            if not self.check_mode and changed:
                workspace = self.log_analytics_models.Workspace(
                    sku=self.log_analytics_models.WorkspaceSku(name=self.sku),
                    retention_in_days=self.retention_in_days,
                    location=self.location,
                    tags=results['tags'])
                workspace = self.create_workspace(workspace)
        elif workspace and self.state == 'absent':
            changed = True
            workspace = None
            if not self.check_mode:
                self.delete_workspace()
        if workspace and workspace.id:
            self.results = self.to_dict(workspace)
            self.results['intelligence_packs'] = self.list_intelligence_packs()
            self.results['management_groups'] = self.list_management_groups()
            self.results['usages'] = self.list_usages()
            self.results['shared_keys'] = self.get_shared_keys()
        # handle the intelligence pack
        if workspace and workspace.id and self.intelligence_packs:
            intelligence_packs = self.results['intelligence_packs']
            for key in self.intelligence_packs.keys():
                enabled = self.intelligence_packs[key]
                for x in intelligence_packs:
                    if x['name'].lower() == key.lower():
                        if x['enabled'] != enabled:
                            changed = True
                            if not self.check_mode:
                                self.change_intelligence(x['name'], enabled)
                                x['enabled'] = enabled
                        break
        self.results['changed'] = changed
        return self.results
    def exec_module(self, **kwargs):
        """Main module execution method"""

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            if hasattr(self, key):
                setattr(self, key, kwargs[key])
            elif kwargs[key] is not None:
                self.custom_image[key] = kwargs[key]

        if self.state == 'present':
            windows_os_state = self.custom_image.pop('windows_os_state', False)
            linux_os_state = self.custom_image.pop('linux_os_state', False)
            source_vm_name = self.custom_image.pop('source_vm')
            temp = "/subscriptions/{0}/resourcegroups/{1}/providers/microsoft.devtestlab/labs/{2}/virtualmachines/{3}"
            self.custom_image['vm'] = {}
            self.custom_image['vm']['source_vm_id'] = temp.format(
                self.subscription_id, self.resource_group, self.lab_name,
                source_vm_name)
            if windows_os_state:
                self.custom_image['vm']['windows_os_info'] = {
                    'windows_os_state':
                    _snake_to_camel(windows_os_state, True)
                }
            elif linux_os_state:
                self.custom_image['vm']['linux_os_info'] = {
                    'linux_os_state': _snake_to_camel(linux_os_state, True)
                }
            else:
                self.fail(
                    "Either 'linux_os_state' or 'linux_os_state' must be specified"
                )

        response = None

        self.mgmt_client = self.get_mgmt_svc_client(
            DevTestLabsClient,
            base_url=self._cloud_environment.endpoints.resource_manager)

        old_response = self.get_customimage()

        if not old_response:
            self.log("Custom Image instance doesn't exist")
            if self.state == 'absent':
                self.log("Old instance didn't exist")
            else:
                self.to_do = Actions.Create
        else:
            self.log("Custom Image instance already exists")
            if self.state == 'absent':
                self.to_do = Actions.Delete
            elif self.state == 'present':
                if (not default_compare(self.custom_image, old_response, '',
                                        self.results)):
                    self.to_do = Actions.Update

        if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
            self.log("Need to Create / Update the Custom Image instance")

            if self.check_mode:
                self.results['changed'] = True
                return self.results

            response = self.create_update_customimage()

            self.results['changed'] = True
            self.log("Creation / Update done")
        elif self.to_do == Actions.Delete:
            self.log("Custom Image instance deleted")
            self.results['changed'] = True

            if self.check_mode:
                return self.results

            self.delete_customimage()
            # This currently doesnt' work as there is a bug in SDK / Service
            if isinstance(response, LROPoller) or isinstance(
                    response, AzureOperationPoller):
                response = self.get_poller_result(response)
        else:
            self.log("Custom Image instance unchanged")
            self.results['changed'] = False
            response = old_response

        if self.state == 'present':
            self.results.update({'id': response.get('id', None)})
        return self.results
    def exec_module(self, **kwargs):

        for key in self.module_arg_spec.keys():
            setattr(self, key, kwargs[key])

        self._base_url = '{0}.azure-devices.net'.format(self.hub)
        config = {
            'base_url': self._base_url,
            'key': self.hub_policy_key,
            'policy': self.hub_policy_name
        }
        self._mgmt_client = self.get_data_svc_client(**config)

        changed = False

        device = self.get_device()
        if self.state == 'present':
            if not device:
                changed = True
                auth = {'type': _snake_to_camel(self.auth_method)}
                if self.auth_method == 'self_signed':
                    auth['x509Thumbprint'] = {
                        'primaryThumbprint': self.primary_key,
                        'secondaryThumbprint': self.secondary_key
                    }
                elif self.auth_method == 'sas':
                    auth['symmetricKey'] = {
                        'primaryKey': self.primary_key,
                        'secondaryKey': self.secondary_key
                    }
                device = {
                    'deviceId': self.name,
                    'capabilities': {
                        'iotEdge': self.edge_enabled or False
                    },
                    'authentication': auth
                }
                if self.status is not None and not self.status:
                    device['status'] = 'disabled'
            else:
                if self.edge_enabled is not None and self.edge_enabled != device[
                        'capabilities']['iotEdge']:
                    changed = True
                    device['capabilities']['iotEdge'] = self.edge_enabled
                if self.status is not None:
                    status = 'enabled' if self.status else 'disabled'
                    if status != device['status']:
                        changed = True
                        device['status'] = status
            if changed and not self.check_mode:
                device = self.create_or_update_device(device)
            twin = self.get_twin()
            if twin:
                if not twin.get('tags'):
                    twin['tags'] = dict()
                twin_change = False
                if self.twin_tags and not self.is_equal(
                        self.twin_tags, twin['tags']):
                    twin_change = True
                if self.desired and not self.is_equal(
                        self.desired, twin['properties']['desired']):
                    twin_change = True
                if twin_change and not self.check_mode:
                    self.update_twin(twin)
                changed = changed or twin_change
                device['tags'] = twin.get('tags') or dict()
                device['properties'] = twin['properties']
                device['modules'] = self.list_device_modules()
            elif self.twin_tags or self.desired:
                self.fail(
                    "Device twin is not supported in IoT Hub with basic tier.")
        elif device:
            if not self.check_mode:
                self.delete_device(device['etag'])
            changed = True
            device = None
        self.results = device or dict()
        self.results['changed'] = changed
        return self.results
示例#10
0
    def exec_module(self, **kwargs):
        """Main module execution method"""

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            setattr(self, key, kwargs[key])

        self.cdn_client = self.get_cdn_client()

        to_be_updated = False

        resource_group = self.get_resource_group(self.resource_group)
        if not self.location:
            self.location = resource_group.location

        if self.query_string_caching_behavior:
            self.query_string_caching_behavior = _snake_to_camel(
                self.query_string_caching_behavior)

        response = self.get_cdnendpoint()

        if self.state == 'present':

            if not response:

                if self.started is None:
                    # If endpoint dosen't exist and no start/stop operation specified, create endpoint.
                    if self.origins is None:
                        self.fail(
                            "Origins is not provided when trying to create endpoint"
                        )
                    self.log("Need to create the Azure CDN endpoint")

                    if not self.check_mode:
                        result = self.create_cdnendpoint()
                        self.results['id'] = result['id']
                        self.results['host_name'] = result['host_name']
                        self.log("Creation done")

                    self.results['changed'] = True
                    return self.results

                else:
                    # Fail the module when user try to start/stop a non-existed endpoint
                    self.log("Can't stop/stop a non-existed endpoint")
                    self.fail(
                        "This endpoint is not found, stop/start is forbidden")

            else:
                self.log('Results : {0}'.format(response))
                self.results['id'] = response['id']
                self.results['host_name'] = response['host_name']

                update_tags, response['tags'] = self.update_tags(
                    response['tags'])

                if update_tags:
                    to_be_updated = True

                if response['provisioning_state'] == "Succeeded":
                    if self.started is False and response[
                            'resource_state'] == 'Running':
                        self.log("Need to stop the Azure CDN endpoint")

                        if not self.check_mode:
                            result = self.stop_cdnendpoint()
                            self.log("Endpoint stopped")

                        self.results['changed'] = True

                    elif self.started and response[
                            'resource_state'] == 'Stopped':
                        self.log("Need to start the Azure CDN endpoint")

                        if not self.check_mode:
                            result = self.start_cdnendpoint()
                            self.log("Endpoint started")

                        self.results['changed'] = True

                    elif self.started is not None:
                        self.module.warn(
                            "Start/Stop not performed due to current resource state {0}"
                            .format(response['resource_state']))
                        self.results['changed'] = False

                    if self.purge:
                        self.log("Need to purge endpoint")

                        if not self.check_mode:
                            result = self.purge_cdnendpoint()
                            self.log("Endpoint purged")

                        self.results['changed'] = True

                    to_be_updated = to_be_updated or self.check_update(
                        response)

                    if to_be_updated:
                        self.log("Need to update the Azure CDN endpoint")
                        self.results['changed'] = True

                        if not self.check_mode:
                            result = self.update_cdnendpoint()
                            self.results['host_name'] = result['host_name']
                            self.log("Update done")

                elif self.started is not None:
                    self.module.warn(
                        "Start/Stop not performed due to current provisioning state {0}"
                        .format(response['provisioning_state']))
                    self.results['changed'] = False

        elif self.state == 'absent' and response:
            self.log("Need to delete the Azure CDN endpoint")
            self.results['changed'] = True

            if not self.check_mode:
                self.delete_cdnendpoint()
                self.log("Azure CDN endpoint deleted")

        return self.results
示例#11
0
    def exec_module(self, **kwargs):
        """Main module execution method"""

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            if hasattr(self, key):
                setattr(self, key, kwargs[key])
            elif kwargs[key] is not None:
                self.lab[key] = kwargs[key]

        if self.lab.get('storage_type'):
            self.lab['lab_storage_type'] = _snake_to_camel(self.lab['storage_type'], True)
            self.lab.pop('storage_type', None)
        if self.lab.get('premium_data_disks') is not None:
            self.lab['premium_data_disks'] = 'Enabled' if self.lab['premium_data_disks'] else 'Disabled'

        response = None

        self.mgmt_client = self.get_mgmt_svc_client(DevTestLabsClient,
                                                    base_url=self._cloud_environment.endpoints.resource_manager,
                                                    api_version='2018-10-15')

        resource_group = self.get_resource_group(self.resource_group)
        if self.lab.get('location') is None:
            self.lab['location'] = resource_group.location

        old_response = self.get_devtestlab()

        if not old_response:
            self.log("DevTest Lab instance doesn't exist")
            if self.state == 'absent':
                self.log("Old instance didn't exist")
            else:
                self.to_do = Actions.Create
        else:
            self.log("DevTest Lab instance already exists")
            if self.state == 'absent':
                self.to_do = Actions.Delete
            elif self.state == 'present':
                if self.lab.get('lab_storage_type') is not None and \
                   self.lab.get('lab_storage_type').lower() != old_response.get('lab_storage_type', '').lower():
                    self.to_do = Actions.Update
                if (self.lab.get('premium_data_disks') is not None and
                        self.lab.get('premium_data_disks').lower() != old_response.get('premium_data_disks').lower()):
                    self.to_do = Actions.Update

        if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
            self.log("Need to Create / Update the DevTest Lab instance")
            self.results['changed'] = True

            if self.check_mode:
                return self.results

            response = self.create_update_devtestlab()
            self.log("Creation / Update done")
        elif self.to_do == Actions.Delete:
            self.log("DevTest Lab instance deleted")
            self.results['changed'] = True

            if self.check_mode:
                return self.results

            self.delete_devtestlab()
            # This currently doesnt' work as there is a bug in SDK / Service
            if isinstance(response, LROPoller) or isinstance(response, AzureOperationPoller):
                response = self.get_poller_result(response)
        else:
            self.log("DevTest Lab instance unchanged")
            self.results['changed'] = False
            response = old_response

        if self.state == 'present':
            self.results.update({
                'id': response.get('id', None)
            })
        return self.results
    def exec_module(self, **kwargs):

        for key in self.module_arg_spec.keys():
            setattr(self, key, kwargs[key])

        self._base_url = '{0}.azure-devices.net'.format(self.hub)
        config = {
            'base_url': self._base_url,
            'key': self.hub_policy_key,
            'policy': self.hub_policy_name
        }
        self._mgmt_client = self.get_data_svc_client(**config)

        changed = False

        module = self.get_module()
        if self.state == 'present':
            if not module:
                changed = True
                auth = {'type': _snake_to_camel(self.auth_method)}
                if self.auth_method == 'self_signed':
                    auth['x509Thumbprint'] = {
                        'primaryThumbprint': self.primary_key,
                        'secondaryThumbprint': self.secondary_key
                    }
                elif self.auth_method == 'sas':
                    auth['symmetricKey'] = {
                        'primaryKey': self.primary_key,
                        'secondaryKey': self.secondary_key
                    }
                module = {
                    'deviceId': self.device,
                    'moduleId': self.name,
                    'authentication': auth
                }
            if changed and not self.check_mode:
                module = self.create_or_update_module(module)
            twin = self.get_twin()
            if not twin.get('tags'):
                twin['tags'] = dict()
            twin_change = False
            if self.twin_tags and not self.is_equal(self.twin_tags,
                                                    twin['tags']):
                twin_change = True
            if self.desired and not self.is_equal(
                    self.desired, twin['properties']['desired']):
                self.module.warn('desired')
                twin_change = True
            if twin_change and not self.check_mode:
                twin = self.update_twin(twin)
            changed = changed or twin_change
            module['tags'] = twin.get('tags') or dict()
            module['properties'] = twin['properties']
        elif module:
            if not self.check_mode:
                self.delete_module(module['etag'])
            changed = True
            module = None
        self.results = module or dict()
        self.results['changed'] = changed
        return self.results
    def exec_module(self, **kwargs):

        for key in list(self.module_arg_spec.keys()):
            setattr(self, key, kwargs[key])

        changed = False
        original = self.get()
        if self.state == 'present':
            # Create the resource instance
            params = dict(
                enable_batched_operations=self.enable_batched_operations,
                enable_express=self.enable_express,
                enable_partitioning=self.enable_partitioning,
                max_size_in_megabytes=self.max_size_in_mb,
                support_ordering=self.support_ordering
            )
            if self.status:
                params['status'] = self.servicebus_models.EntityStatus(str.capitalize(_snake_to_camel(self.status)))
            for k, v in duration_spec_map.items():
                seconds = getattr(self, v)
                if seconds:
                    params[k] = timedelta(seconds=seconds)

            instance = self.servicebus_models.SBTopic(**params)
            result = original
            if not original:
                changed = True
                result = instance
            else:
                result = original
                attribute_map = set(self.servicebus_models.SBTopic._attribute_map.keys()) - set(self.servicebus_models.SBTopic._validation.keys())
                for attribute in attribute_map:
                    value = getattr(instance, attribute)
                    if value and value != getattr(original, attribute):
                        changed = True
            if changed and not self.check_mode:
                result = self.create_or_update(instance)
            self.results = self.to_dict(result)
        elif original:
            changed = True
            if not self.check_mode:
                self.delete()
                self.results['deleted'] = True

        self.results['changed'] = changed
        return self.results
    def exec_module(self, **kwargs):

        for key in list(self.module_arg_spec.keys()) + ['tags']:
            setattr(self, key, kwargs[key])

        changed = False
        results = dict()
        vgw = None

        resource_group = self.get_resource_group(self.resource_group)
        if not self.location:
            self.location = resource_group.location

        self.virtual_network = self.parse_resource_to_dict(self.virtual_network)
        resource_group = self.get_resource_group(self.resource_group)

        try:
            vgw = self.network_client.virtual_network_gateways.get(self.resource_group, self.name)
            if self.state == 'absent':
                self.log("CHANGED: vnet exists but requested state is 'absent'")
                changed = True
        except CloudError:
            if self.state == 'present':
                self.log("CHANGED: VPN Gateway {0} does not exist but requested state is 'present'".format(self.name))
                changed = True

        if vgw:
            results = vgw_to_dict(vgw)
            if self.state == 'present':
                update_tags, results['tags'] = self.update_tags(results['tags'])
                if update_tags:
                    changed = True
                sku = dict(name=self.sku, tier=self.sku)
                if sku != results['sku']:
                    changed = True
                if self.enable_bgp != results['enable_bgp']:
                    changed = True
                if self.bgp_settings and self.bgp_settings['asn'] != results['bgp_settings']['asn']:
                    changed = True

        self.results['changed'] = changed
        self.results['id'] = results.get('id')

        if self.check_mode:
            return self.results
        if changed:
            if self.state == 'present':
                if not self.sku:
                    self.fail('Parameter error: sku is required when creating a vpn gateway')
                if not self.ip_configurations:
                    self.fail('Parameter error: ip_configurations required when creating a vpn gateway')
                subnet = self.network_models.SubResource(
                    id='/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/virtualNetworks/{2}/subnets/GatewaySubnet'.format(
                        self.virtual_network['subscription_id'],
                        self.virtual_network['resource_group'],
                        self.virtual_network['name']))

                public_ip_address = self.network_models.SubResource(
                    id='/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/publicIPAddresses/{2}'.format(
                        self.virtual_network['subscription_id'],
                        self.virtual_network['resource_group'],
                        self.ip_configurations[0]['public_ip_address_name']))

                vgw_ip_configurations = [
                    self.network_models.VirtualNetworkGatewayIPConfiguration(
                        private_ip_allocation_method=ip_config.get('private_ip_allocation_method'),
                        subnet=subnet,
                        public_ip_address=public_ip_address,
                        name='default'
                    ) for ip_config in self.ip_configurations
                ]

                vgw_sku = self.network_models.VirtualNetworkGatewaySku(
                    name=self.sku,
                    tier=self.sku
                )

                vgw_bgp_settings = self.network_models.BgpSettings(
                    asn=self.bgp_settings.get('asn'),
                ) if self.bgp_settings else None
                vgw = self.network_models.VirtualNetworkGateway(
                    location=self.location,
                    ip_configurations=vgw_ip_configurations,
                    gateway_type=_snake_to_camel(self.gateway_type, True),
                    vpn_type=_snake_to_camel(self.vpn_type, True),
                    enable_bgp=self.enable_bgp,
                    sku=vgw_sku,
                    bgp_settings=vgw_bgp_settings
                )
                if self.tags:
                    vgw.tags = self.tags
                results = self.create_or_update_vgw(vgw)

            else:
                results = self.delete_vgw()

        if self.state == 'present':
            self.results['id'] = results.get('id')
        return self.results
示例#15
0
    def create_update_containerinstance(self):
        '''
        Creates or updates a container service with the specified configuration of orchestrator, masters, and agents.

        :return: deserialized container instance state dictionary
        '''
        self.log("Creating / Updating the container instance {0}".format(
            self.name))

        registry_credentials = None

        if self.registry_login_server is not None:
            registry_credentials = [
                self.cgmodels.ImageRegistryCredential(
                    server=self.registry_login_server,
                    username=self.registry_username,
                    password=self.registry_password)
            ]

        ip_address = None

        containers = []
        all_ports = set([])
        for container_def in self.containers:
            name = container_def.get("name")
            image = container_def.get("image")
            memory = container_def.get("memory")
            cpu = container_def.get("cpu")
            commands = container_def.get("commands")
            ports = []
            variables = []

            port_list = container_def.get("ports")
            if port_list:
                for port in port_list:
                    all_ports.add(port)
                    ports.append(self.cgmodels.ContainerPort(port=port))

            variable_list = container_def.get("environment_variables")
            if variable_list:
                for variable in variable_list:
                    variables.append(
                        self.cgmodels.EnvironmentVariable(
                            name=variable.get('name'),
                            value=variable.get('value')
                            if not variable.get('is_secure') else None,
                            secure_value=variable.get('value')
                            if variable.get('is_secure') else None))

            containers.append(
                self.cgmodels.Container(
                    name=name,
                    image=image,
                    resources=self.cgmodels.ResourceRequirements(
                        requests=self.cgmodels.ResourceRequests(
                            memory_in_gb=memory, cpu=cpu)),
                    ports=ports,
                    command=commands,
                    environment_variables=variables))

        if self.ip_address == 'public':
            # get list of ports
            if len(all_ports) > 0:
                ports = []
                for port in all_ports:
                    ports.append(self.cgmodels.Port(port=port, protocol="TCP"))
                ip_address = self.cgmodels.IpAddress(
                    ports=ports,
                    dns_name_label=self.dns_name_label,
                    type='public')

        parameters = self.cgmodels.ContainerGroup(
            location=self.location,
            containers=containers,
            image_registry_credentials=registry_credentials,
            restart_policy=_snake_to_camel(self.restart_policy, True)
            if self.restart_policy else None,
            ip_address=ip_address,
            os_type=self.os_type,
            volumes=None,
            tags=self.tags)

        try:
            response = self.containerinstance_client.container_groups.create_or_update(
                resource_group_name=self.resource_group,
                container_group_name=self.name,
                container_group=parameters)
            if isinstance(response, LROPoller):
                response = self.get_poller_result(response)
        except CloudError as exc:
            self.fail("Error when creating ACI {0}: {1}".format(
                self.name, exc.message or str(exc)))

        return response.as_dict()