def check_update(self, response):
        if self.location and normalize_location_name(
                response['location']) != normalize_location_name(
                    self.location):
            self.log("Location Diff - Origin {0} / Update {1}".format(
                response['location'], self.location))
            return True

        if self.profile_status and response['profile_status'].lower(
        ) != self.profile_status:
            self.log("Profile Status Diff - Origin {0} / Update {1}".format(
                response['profile_status'], self.profile_status))
            return True

        if self.routing_method and response['routing_method'].lower(
        ) != self.routing_method:
            self.log(
                "Traffic Routing Method Diff - Origin {0} / Update {1}".format(
                    response['routing_method'], self.routing_method))
            return True

        if self.dns_config and \
           (response['dns_config']['relative_name'] != self.dns_config['relative_name'] or response['dns_config']['ttl'] != self.dns_config['ttl']):
            self.log("DNS Config Diff - Origin {0} / Update {1}".format(
                response['dns_config'], self.dns_config))
            return True

        for k, v in self.monitor_config.items():
            if v:
                if str(v).lower() != str(
                        response['monitor_config'][k]).lower():
                    self.log(
                        "Monitor Config Diff - Origin {0} / Update {1}".format(
                            response['monitor_config'], self.monitor_config))
                    return True
        return False
Beispiel #2
0
    def exec_module(self, **kwargs):
        for key in list(self.module_arg_spec.keys()) + ['tags']:
            setattr(self, key, kwargs[key])

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

        result = dict()
        changed = False

        result = self.get_table()
        if self.state == 'absent' and result:
            changed = True
            if not self.check_mode:
                self.delete_table()
        elif self.state == 'present':
            if not result:
                changed = True  # create new route table
            else:  # check update
                update_tags, self.tags = self.update_tags(result.tags)
                if update_tags:
                    changed = True
                if self.disable_bgp_route_propagation != result.disable_bgp_route_propagation:
                    changed = True

            if changed:
                result = self.network_models.RouteTable(
                    location=self.location,
                    tags=self.tags,
                    disable_bgp_route_propagation=self.
                    disable_bgp_route_propagation)
                if not self.check_mode:
                    result = self.create_or_update_table(result)

        self.results['id'] = result.id if result else None
        self.results['changed'] = changed
        return self.results
Beispiel #3
0
    def exec_module(self, **kwargs):

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

        results = None
        changed = False
        nic = None
        nsg = None

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

        # parse the virtual network resource group and name
        self.virtual_network = self.parse_resource_to_dict(self.virtual_network)

        # if not set the security group name, use nic name for default
        self.security_group = self.parse_resource_to_dict(self.security_group or self.name)

        if self.state == 'present' and not self.ip_configurations:
            # construct the ip_configurations array for compatiable
            self.deprecate('Setting ip_configuration flatten is deprecated and will be removed.'
                           ' Using ip_configurations list to define the ip configuration', version='2.9')
            self.ip_configurations = [
                dict(
                    private_ip_address=self.private_ip_address,
                    private_ip_allocation_method=self.private_ip_allocation_method,
                    public_ip_address_name=self.public_ip_address_name if self.public_ip else None,
                    public_ip_allocation_method=self.public_ip_allocation_method,
                    name='default',
                    primary=True
                )
            ]

        try:
            self.log('Fetching network interface {0}'.format(self.name))
            nic = self.network_client.network_interfaces.get(self.resource_group, self.name)

            self.log('Network interface {0} exists'.format(self.name))
            self.check_provisioning_state(nic, self.state)
            results = nic_to_dict(nic)
            self.log(results, pretty_print=True)

            nsg = None
            if self.state == 'present':
                # check for update
                update_tags, results['tags'] = self.update_tags(results['tags'])
                if update_tags:
                    changed = True

                if self.create_with_security_group != bool(results.get('network_security_group')):
                    self.log("CHANGED: add or remove network interface {0} network security group".format(self.name))
                    changed = True

                if not changed:
                    nsg = self.get_security_group(self.security_group['resource_group'], self.security_group['name'])
                    if nsg and results.get('network_security_group') and results['network_security_group'].get('id') != nsg.id:
                        self.log("CHANGED: network interface {0} network security group".format(self.name))
                        changed = True

                if results['ip_configurations'][0]['subnet']['virtual_network_name'] != self.virtual_network['name']:
                    self.log("CHANGED: network interface {0} virtual network name".format(self.name))
                    changed = True

                if results['ip_configurations'][0]['subnet']['resource_group'] != self.virtual_network['resource_group']:
                    self.log("CHANGED: network interface {0} virtual network resource group".format(self.name))
                    changed = True

                if results['ip_configurations'][0]['subnet']['name'] != self.subnet_name:
                    self.log("CHANGED: network interface {0} subnet name".format(self.name))
                    changed = True

                # check the ip_configuration is changed
                # construct two set with the same structure and then compare
                # the list should contains:
                # name, private_ip_address, public_ip_address_name, private_ip_allocation_method, subnet_name
                ip_configuration_result = self.construct_ip_configuration_set(results['ip_configurations'])
                ip_configuration_request = self.construct_ip_configuration_set(self.ip_configurations)
                if ip_configuration_result != ip_configuration_request:
                    self.log("CHANGED: network interface {0} ip configurations".format(self.name))
                    changed = True

            elif self.state == 'absent':
                self.log("CHANGED: network interface {0} exists but requested state is 'absent'".format(self.name))
                changed = True
        except CloudError:
            self.log('Network interface {0} does not exist'.format(self.name))
            if self.state == 'present':
                self.log("CHANGED: network interface {0} does not exist but requested state is 'present'".format(self.name))
                changed = True

        self.results['changed'] = changed
        self.results['state'] = results

        if self.check_mode:
            return self.results

        if changed:
            if self.state == 'present':
                subnet = self.network_models.SubResource(
                    '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/virtualNetworks/{2}/subnets/{3}'.format(
                        self.virtual_network['subscription_id'],
                        self.virtual_network['resource_group'],
                        self.virtual_network['name'],
                        self.subnet_name))

                nic_ip_configurations = [
                    self.network_models.NetworkInterfaceIPConfiguration(
                        private_ip_allocation_method=ip_config.get('private_ip_allocation_method'),
                        private_ip_address=ip_config.get('private_ip_address'),
                        name=ip_config.get('name'),
                        subnet=subnet,
                        public_ip_address=self.get_or_create_public_ip_address(ip_config),
                        load_balancer_backend_address_pools=([self.network_models.BackendAddressPool(id=self.backend_addr_pool_id(bap_id))
                                                              for bap_id in ip_config.get('load_balancer_backend_address_pools')]
                                                             if ip_config.get('load_balancer_backend_address_pools') else None),
                        primary=ip_config.get('primary')
                    ) for ip_config in self.ip_configurations
                ]

                nsg = self.create_default_securitygroup(self.security_group['resource_group'],
                                                        self.location,
                                                        self.security_group['name'],
                                                        self.os_type,
                                                        self.open_ports) if self.create_with_security_group else None

                self.log('Creating or updating network interface {0}'.format(self.name))
                nic = self.network_models.NetworkInterface(
                    id=results['id'] if results else None,
                    location=self.location,
                    tags=self.tags,
                    ip_configurations=nic_ip_configurations,
                    network_security_group=nsg
                )
                self.results['state'] = self.create_or_update_nic(nic)
            elif self.state == 'absent':
                self.log('Deleting network interface {0}'.format(self.name))
                self.delete_nic()
                # Delete doesn't return anything. If we get this far, assume success
                self.results['state']['status'] = 'Deleted'

        return self.results
    def exec_module(self, **kwargs):

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

        results = dict()
        changed = False
        rg = None
        contains_resources = False

        try:
            self.log('Fetching resource group {0}'.format(self.name))
            rg = self.rm_client.resource_groups.get(self.name)
            self.check_provisioning_state(rg, self.state)
            contains_resources = self.resources_exist()

            results = resource_group_to_dict(rg)
            if self.state == 'absent':
                self.log(
                    "CHANGED: resource group {0} exists but requested state is 'absent'"
                    .format(self.name))
                changed = True
            elif self.state == 'present':
                update_tags, results['tags'] = self.update_tags(
                    results['tags'])
                self.log("update tags %s" % update_tags)
                self.log("new tags: %s" % str(results['tags']))
                if update_tags:
                    changed = True

                if self.location and normalize_location_name(
                        self.location) != results['location']:
                    self.fail(
                        "Resource group '{0}' already exists in location '{1}' and cannot be "
                        "moved.".format(self.name, results['location']))
        except CloudError:
            self.log('Resource group {0} does not exist'.format(self.name))
            if self.state == 'present':
                self.log(
                    "CHANGED: resource group {0} does not exist but requested state is "
                    "'present'".format(self.name))
                changed = True

        self.results['changed'] = changed
        self.results['state'] = results
        self.results['contains_resources'] = contains_resources

        if self.check_mode:
            return self.results

        if changed:
            if self.state == 'present':
                if not rg:
                    # Create resource group
                    self.log("Creating resource group {0}".format(self.name))
                    if not self.location:
                        self.fail(
                            "Parameter error: location is required when creating a resource group."
                        )
                    if self.name_exists():
                        self.fail(
                            "Error: a resource group with the name {0} already exists in your subscription."
                            .format(self.name))
                    params = self.rm_models.ResourceGroup(
                        location=self.location, tags=self.tags)
                else:
                    # Update resource group
                    params = self.rm_models.ResourceGroup(
                        location=results['location'], tags=results['tags'])
                self.results['state'] = self.create_or_update_resource_group(
                    params)
            elif self.state == 'absent':
                if contains_resources and not self.force:
                    self.fail(
                        "Error removing resource group {0}. Resources exist within the group."
                        .format(self.name))
                self.delete_resource_group()

        return self.results
    def exec_module(self, **kwargs):

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

        results = dict()
        changed = False
        rg = None
        contains_resources = False

        try:
            self.log('Fetching resource group {0}'.format(self.name))
            rg = self.rm_client.resource_groups.get(self.name)
            self.check_provisioning_state(rg, self.state)
            contains_resources = self.resources_exist()

            results = resource_group_to_dict(rg)
            if self.state == 'absent':
                self.log("CHANGED: resource group {0} exists but requested state is 'absent'".format(self.name))
                changed = True
            elif self.state == 'present':
                update_tags, results['tags'] = self.update_tags(results['tags'])
                self.log("update tags %s" % update_tags)
                self.log("new tags: %s" % str(results['tags']))
                if update_tags:
                    changed = True

                if self.location and normalize_location_name(self.location) != results['location']:
                    self.fail("Resource group '{0}' already exists in location '{1}' and cannot be "
                              "moved.".format(self.name, results['location']))
        except CloudError:
            self.log('Resource group {0} does not exist'.format(self.name))
            if self.state == 'present':
                self.log("CHANGED: resource group {0} does not exist but requested state is "
                         "'present'".format(self.name))
                changed = True

        self.results['changed'] = changed
        self.results['state'] = results
        self.results['contains_resources'] = contains_resources

        if self.check_mode:
            return self.results

        if changed:
            if self.state == 'present':
                if not rg:
                    # Create resource group
                    self.log("Creating resource group {0}".format(self.name))
                    if not self.location:
                        self.fail("Parameter error: location is required when creating a resource group.")
                    if self.name_exists():
                        self.fail("Error: a resource group with the name {0} already exists in your subscription."
                                  .format(self.name))
                    params = self.rm_models.ResourceGroup(
                        location=self.location,
                        tags=self.tags
                    )
                else:
                    # Update resource group
                    params = self.rm_models.ResourceGroup(
                        location=results['location'],
                        tags=results['tags']
                    )
                self.results['state'] = self.create_or_update_resource_group(params)
            elif self.state == 'absent':
                if contains_resources and not self.force:
                    self.fail("Error removing resource group {0}. Resources exist within the group.".format(self.name))
                self.delete_resource_group()

        return self.results
Beispiel #6
0
    def exec_module(self, **kwargs):

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

        results = None
        changed = False
        nic = None
        nsg = None

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

        # parse the virtual network resource group and name
        self.virtual_network = self.parse_resource_to_dict(
            self.virtual_network)

        # if not set the security group name, use nic name for default
        self.security_group = self.parse_resource_to_dict(self.security_group
                                                          or self.name)

        # if application security groups set, convert to resource id format
        if self.ip_configurations:
            for config in self.ip_configurations:
                if config.get('application_security_groups'):
                    asgs = []
                    for asg in config['application_security_groups']:
                        asg_resource_id = asg
                        if isinstance(asg,
                                      str) and (not is_valid_resource_id(asg)):
                            asg = self.parse_resource_to_dict(asg)
                        if isinstance(asg, dict):
                            asg_resource_id = format_resource_id(
                                val=asg['name'],
                                subscription_id=self.subscription_id,
                                namespace='Microsoft.Network',
                                types='applicationSecurityGroups',
                                resource_group=asg['resource_group'])
                        asgs.append(asg_resource_id)
                    if len(asgs) > 0:
                        config['application_security_groups'] = asgs

        if self.state == 'present' and not self.ip_configurations:
            # construct the ip_configurations array for compatible
            self.deprecate(
                'Setting ip_configuration flatten is deprecated and will be removed.'
                ' Using ip_configurations list to define the ip configuration',
                version='2.9')
            self.ip_configurations = [
                dict(private_ip_address=self.private_ip_address,
                     private_ip_allocation_method=self.
                     private_ip_allocation_method,
                     public_ip_address_name=self.public_ip_address_name
                     if self.public_ip else None,
                     public_ip_allocation_method=self.
                     public_ip_allocation_method,
                     name='default',
                     primary=True)
            ]

        try:
            self.log('Fetching network interface {0}'.format(self.name))
            nic = self.network_client.network_interfaces.get(
                self.resource_group, self.name)

            self.log('Network interface {0} exists'.format(self.name))
            self.check_provisioning_state(nic, self.state)
            results = nic_to_dict(nic)
            self.log(results, pretty_print=True)

            nsg = None
            if self.state == 'present':
                # check for update
                update_tags, results['tags'] = self.update_tags(
                    results['tags'])
                if update_tags:
                    changed = True

                if self.create_with_security_group != bool(
                        results.get('network_security_group')):
                    self.log(
                        "CHANGED: add or remove network interface {0} network security group"
                        .format(self.name))
                    changed = True

                if self.enable_accelerated_networking != bool(
                        results.get('enable_accelerated_networking')):
                    self.log(
                        "CHANGED: Accelerated Networking set to {0} (previously {1})"
                        .format(self.enable_accelerated_networking,
                                results.get('enable_accelerated_networking')))
                    changed = True

                if self.enable_ip_forwarding != bool(
                        results.get('enable_ip_forwarding')):
                    self.log(
                        "CHANGED: IP forwarding set to {0} (previously {1})".
                        format(self.enable_ip_forwarding,
                               results.get('enable_ip_forwarding')))
                    changed = True

                # We need to ensure that dns_servers are list like
                dns_servers_res = results.get('dns_settings').get(
                    'dns_servers')
                _dns_servers_set = sorted(self.dns_servers) if isinstance(
                    self.dns_servers, list) else list()
                _dns_servers_res = sorted(dns_servers_res) if isinstance(
                    self.dns_servers, list) else list()
                if _dns_servers_set != _dns_servers_res:
                    self.log(
                        "CHANGED: DNS servers set to {0} (previously {1})".
                        format(", ".join(_dns_servers_set),
                               ", ".join(_dns_servers_res)))
                    changed = True

                if not changed:
                    nsg = self.get_security_group(
                        self.security_group['resource_group'],
                        self.security_group['name'])
                    if nsg and results.get(
                            'network_security_group') and results[
                                'network_security_group'].get('id') != nsg.id:
                        self.log(
                            "CHANGED: network interface {0} network security group"
                            .format(self.name))
                        changed = True

                if results['ip_configurations'][0]['subnet'][
                        'virtual_network_name'] != self.virtual_network['name']:
                    self.log(
                        "CHANGED: network interface {0} virtual network name".
                        format(self.name))
                    changed = True

                if results['ip_configurations'][0]['subnet'][
                        'resource_group'] != self.virtual_network[
                            'resource_group']:
                    self.log(
                        "CHANGED: network interface {0} virtual network resource group"
                        .format(self.name))
                    changed = True

                if results['ip_configurations'][0]['subnet'][
                        'name'] != self.subnet_name:
                    self.log(
                        "CHANGED: network interface {0} subnet name".format(
                            self.name))
                    changed = True

                # check the ip_configuration is changed
                # construct two set with the same structure and then compare
                # the list should contains:
                # name, private_ip_address, public_ip_address_name, private_ip_allocation_method, subnet_name
                ip_configuration_result = self.construct_ip_configuration_set(
                    results['ip_configurations'])
                ip_configuration_request = self.construct_ip_configuration_set(
                    self.ip_configurations)
                if ip_configuration_result != ip_configuration_request:
                    self.log(
                        "CHANGED: network interface {0} ip configurations".
                        format(self.name))
                    changed = True

            elif self.state == 'absent':
                self.log(
                    "CHANGED: network interface {0} exists but requested state is 'absent'"
                    .format(self.name))
                changed = True
        except CloudError:
            self.log('Network interface {0} does not exist'.format(self.name))
            if self.state == 'present':
                self.log(
                    "CHANGED: network interface {0} does not exist but requested state is 'present'"
                    .format(self.name))
                changed = True

        self.results['changed'] = changed
        self.results['state'] = results

        if self.check_mode:
            return self.results

        if changed:
            if self.state == 'present':
                subnet = self.network_models.SubResource(
                    id=
                    '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/virtualNetworks/{2}/subnets/{3}'
                    .format(self.virtual_network['subscription_id'],
                            self.virtual_network['resource_group'],
                            self.virtual_network['name'], self.subnet_name))

                nic_ip_configurations = [
                    self.network_models.NetworkInterfaceIPConfiguration(
                        private_ip_allocation_method=ip_config.get(
                            'private_ip_allocation_method'),
                        private_ip_address=ip_config.get('private_ip_address'),
                        name=ip_config.get('name'),
                        subnet=subnet,
                        public_ip_address=self.get_or_create_public_ip_address(
                            ip_config),
                        load_balancer_backend_address_pools=([
                            self.network_models.BackendAddressPool(
                                id=self.backend_addr_pool_id(bap_id))
                            for bap_id in ip_config.get(
                                'load_balancer_backend_address_pools')
                        ] if ip_config.get(
                            'load_balancer_backend_address_pools') else None),
                        load_balancer_inbound_nat_rules=([
                            self.network_models.InboundNatRule(
                                id=self.inbound_nat_rule_id(inr_id)) for inr_id
                            in ip_config.get('load_balancer_inbound_nat_rules')
                        ] if ip_config.get('load_balancer_inbound_nat_rules')
                                                         else None),
                        primary=ip_config.get('primary'),
                        application_security_groups=([
                            self.network_models.ApplicationSecurityGroup(
                                id=asg_id) for asg_id in ip_config.get(
                                    'application_security_groups')
                        ] if ip_config.get('application_security_groups') else
                                                     None))
                    for ip_config in self.ip_configurations
                ]

                nsg = self.create_default_securitygroup(
                    self.security_group['resource_group'], self.location,
                    self.security_group['name'], self.os_type, self.open_ports
                ) if self.create_with_security_group else None

                self.log('Creating or updating network interface {0}'.format(
                    self.name))
                nic = self.network_models.NetworkInterface(
                    id=results['id'] if results else None,
                    location=self.location,
                    tags=self.tags,
                    ip_configurations=nic_ip_configurations,
                    enable_accelerated_networking=self.
                    enable_accelerated_networking,
                    enable_ip_forwarding=self.enable_ip_forwarding,
                    network_security_group=nsg)
                if self.dns_servers:
                    dns_settings = self.network_models.NetworkInterfaceDnsSettings(
                        dns_servers=self.dns_servers)
                    nic.dns_settings = dns_settings
                self.results['state'] = self.create_or_update_nic(nic)
            elif self.state == 'absent':
                self.log('Deleting network interface {0}'.format(self.name))
                self.delete_nic()
                # Delete doesn't return anything. If we get this far, assume success
                self.results['state']['status'] = 'Deleted'

        return self.results