def test_remediate_success(self): client = Mock() client.network_security_groups.get.return_value = NetworkSecurityGroup( id="nsg", security_rules=[ SecurityRule( protocol="All", access="Allow", direction="Inbound", source_address_prefix="*", destination_port_ranges=["22-30", "3380-3390"], ), SecurityRule( protocol="All", access="Allow", direction="Inbound", source_address_prefix="*", destination_port_range="3380-3395", ), SecurityRule( protocol="All", access="Allow", direction="Inbound", source_address_prefix="*", destination_port_range="3389", ), SecurityRule( protocol="All", access="Allow", direction="Inbound", source_address_prefix="*", destination_port_range="35", ), ], ) action = NetworkSecurityGroupClosePort3389() assert action.remediate(client, "security_group_name", "resource_group") == 0 assert client.network_security_groups.create_or_update.call_count == 1 call_args = client.network_security_groups.create_or_update.call_args updated_sg = call_args.args[2] security_rules = updated_sg.security_rules assert len(security_rules) == 3 assert security_rules[0].destination_port_ranges == [ "22-30", "3380-3388", "3390" ] assert security_rules[1].destination_port_ranges == [ "3380-3388", "3390-3395" ] assert security_rules[1].destination_port_range is None assert security_rules[2].destination_port_range == "35"
def create_ssh_security_group(self, location, resource_group_name, network_security_group_name): ssh_rule = SecurityRule( name='default-allow-ssh', protocol='Tcp', source_port_range='*', destination_port_range=22, direction='Inbound', source_address_prefix='*', destination_address_prefix='*', access='Allow', priority=1000, ) security_group = NetworkSecurityGroup(location=location, security_rules=[ssh_rule]) try: return self.network_client.network_security_groups.create_or_update( resource_group_name, network_security_group_name, security_group, ) except ClientException as exc: raise AzureBackendError(exc)
def _prepare_security_group_rule(self, rule_data, destination_addr, priority, access="Allow"): """Convert inbound rule data into appropriate Azure client model :param rule_data: cloudshell.cp.azure.models.rule_data.RuleData instance :param destination_addr: Destination IP address/CIDR :return: azure.mgmt.network.models.SecurityRule instance """ if rule_data.port: port_range = str(rule_data.port) else: port_range = "{}-{}".format(rule_data.from_port, rule_data.to_port) return SecurityRule(access=access, direction="Inbound", source_address_prefix=RouteNextHopType.internet, source_port_range=SecurityRuleProtocol.asterisk, name="rule_{}".format(priority), destination_address_prefix=destination_addr, destination_port_range=port_range, priority=priority, protocol=rule_data.protocol)
def create_nsg_rule(resource_group_name, network_security_group_name, security_rule_name, protocol, source_address_prefix, destination_address_prefix, access, direction, source_port_range, destination_port_range, description=None, priority=None): settings = SecurityRule( protocol=protocol, source_address_prefix=source_address_prefix, destination_address_prefix=destination_address_prefix, access=access, direction=direction, description=description, source_port_range=source_port_range, destination_port_range=destination_port_range, priority=priority, name=security_rule_name) ncf = _network_client_factory() return ncf.security_rules.create_or_update(resource_group_name, network_security_group_name, security_rule_name, settings)
def create_netsec_group_port_allow(self, secgroup_name, protocol, source_address_prefix, destination_address_prefix, access, direction, resource_group=None, **kwargs): resource_group = resource_group or self.resource_group self.logger.info( "Attempting to Create New Azure Security Group " "Rule '%s'.", secgroup_name) parameters = NetworkSecurityGroup(location=self.region) parameters.security_rules = [ SecurityRule(protocol, source_address_prefix, destination_address_prefix, access, direction, **kwargs) ] nsg = self.network_client.network_security_groups operation = nsg.create_or_update(resource_group, secgroup_name, parameters) operation.wait() self.logger.info("Network Security Group Rule is created.") return operation.status()
def _create_nsg_rule(cli_ctx, resource_group_name, network_security_group_name, security_rule_name, priority, description=None, protocol=None, access=None, direction=None, source_port_range='*', source_address_prefix='*', destination_port_range=80, destination_address_prefix='*'): settings = SecurityRule( protocol=protocol, source_address_prefix=source_address_prefix, destination_address_prefix=destination_address_prefix, access=access, direction=direction, description=description, source_port_range=source_port_range, destination_port_range=destination_port_range, priority=priority, name=security_rule_name) network_client = _get_network_client_factory(cli_ctx) poller = network_client.security_rules.begin_create_or_update( resource_group_name, network_security_group_name, security_rule_name, settings) LongRunningOperation(cli_ctx)(poller)
def create_security_rule(rule): """Returns a SecurityRule instance. Args: rule: A ':' seperate str instance to represent priority, access, direction, protocol, port range, and name. The format is PRIORITY:ACCESS:DIR:PROTO:PORT_RANGE:NAME, where PRIORITY: The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. ACCESS: The network traffic is allowed or denied. Possible values include: 'Allow', 'Deny'. DIR: The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. Possible values include: 'Inbound', 'Outbound'. PROTO: Network protocol this rule applies to. Possible values include: 'Tcp', 'Udp', 'Icmp', 'Esp', '*', 'Ah'. PORT_RANGE: The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. NAME: The name of the resource that is unique within a resource group. This name can be used to access the resource. """ args = rule.split(':') security_rule = SecurityRule( priority=int(args[0]), access=args[1], direction=args[2], protocol=args[3], source_address_prefix='*', destination_address_prefix='*', source_port_range='*', destination_port_range=args[4], name=args[5], ) return security_rule
def create_nsg(self): print("Creating NSG") params_create = NetworkSecurityGroup( location=self.location, security_rules=[ SecurityRule( name='Port_29876-29877', access=SecurityRuleAccess.allow, description='Batch Node Management', destination_address_prefix="*", destination_port_range='29876-29877', direction=SecurityRuleDirection.inbound, priority=1040, protocol=SecurityRuleProtocol.tcp, source_address_prefix='BatchNodeManagement', source_port_range="*", ), ], ) result_create_NSG = self.network_client.network_security_groups.create_or_update( self.rg_name, self.nsg_name, params_create, ) return result_create_NSG.result()
def create_security_rule(call=None, kwargs=None): # pylint: disable=unused-argument ''' Create a security rule (aka, firewall rule) ''' global netconn # pylint: disable=global-statement,invalid-name if not netconn: netconn = get_conn(NetworkManagementClient, NetworkManagementClientConfiguration) if kwargs is None: kwargs = {} if kwargs.get('resource_group') is None: kwargs['resource_group'] = config.get_cloud_config_value( 'resource_group', {}, __opts__, search_global=True) if kwargs.get('security_group') is None: kwargs['security_group'] = config.get_cloud_config_value( 'security_group', {}, __opts__, search_global=True) if kwargs.get('name') is None: kwargs['name'] = config.get_cloud_config_value('name', {}, __opts__, default='default', search_global=True) rule_params = SecurityRule( protocol=kwargs['protocol'], # Can be 'Tcp', 'Udp', or '*' source_address_prefix=kwargs['source_address'], # '*', 'VirtualNetwork', 'AzureLoadBalancer', 'Internet', '0.0.0.0/24', etc pylint: disable=line-too-long source_port_range=kwargs[ 'source_ports'], # '*', int, or range (0-65535) destination_address_prefix=kwargs['destination_address'], # '*', 'VirtualNetwork', 'AzureLoadBalancer', 'Internet', '0.0.0.0/24', etc pylint: disable=line-too-long destination_port_range=kwargs[ 'destination_ports'], # '*', int, or range (0-65535) access=kwargs['access'], # 'Allow' or 'Deny' direction=kwargs['direction'], # 'Inbound' or 'Outbound' priority=kwargs['priority'], # Unique number between and 100-4096 ) netconn.security_rules.create_or_update( resource_group_name=kwargs['resource_group'], network_security_group_name=kwargs['security_group'], security_rule_name=kwargs['name'], security_rule_parameters=rule_params, ) count = 0 while True: try: return show_security_rule(kwargs=kwargs) except CloudError: count += 1 if count > 120: raise ValueError( 'Timed out waiting for operation to complete.') time.sleep(5)
def set_allowed(name: str, sources: NetworkSecurityGroupConfig) -> Union[None, Error]: resource_group = get_base_resource_group() nsg = get_nsg(name) if not nsg: return Error( code=ErrorCode.UNABLE_TO_FIND, errors=["cannot update nsg rules. nsg %s not found" % name], ) logging.info( "setting allowed incoming connection sources for nsg: %s %s", resource_group, name, ) all_sources = sources.allowed_ips + sources.allowed_service_tags security_rules = [] # NSG security rule priority range defined here: # https://docs.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview min_priority = 100 # NSG rules per NSG limits: # https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-subscription-service-limits?toc=/azure/virtual-network/toc.json#networking-limits max_rule_count = 1000 if len(all_sources) > max_rule_count: return Error( code=ErrorCode.INVALID_REQUEST, errors=[ "too many rules provided %d. Max allowed: %d" % ((len(all_sources)), max_rule_count), ], ) priority = min_priority for src in all_sources: security_rules.append( SecurityRule( name="Allow" + str(priority), protocol="*", source_port_range="*", destination_port_range="*", source_address_prefix=src, destination_address_prefix="*", access=SecurityRuleAccess.ALLOW, priority=priority, # between 100 and 4096 direction="Inbound", )) # Will not exceed `max_rule_count` or max NSG priority (4096) # due to earlier check of `len(all_sources)`. priority += 1 nsg.security_rules = security_rules return update_nsg(nsg)
def test_remediate_success(self): client = Mock() action = RestrictUdpAccessFromInternet() security_rule1 = SecurityRule( id="/subscriptions/d687b1a3-9b78-43b1-a17b-7de297fd1fce/resourceGroups/accelerators-team-resources/providers/Microsoft.Network/networkSecurityGroups/port_rules_testing_2/securityRules/Port_23", name="Port_23", protocol="TCP", source_port_range="*", destination_port_range="23", source_address_prefix="*", source_address_prefixes=[], access="Allow", priority=110, direction="Inbound", ) security_rule2 = SecurityRule( id="/subscriptions/d687b1a3-9b78-43b1-a17b-7de297fd1fce/resourceGroups/accelerators-team-resources/providers/Microsoft.Network/networkSecurityGroups/port_rules_testing_2/securityRules/Port_23", name="Port_21", protocol="UDP", source_port_range="*", destination_port_range="21", source_address_prefix="*", source_address_prefixes=[], access="Allow", priority=100, direction="Inbound", ) client.network_security_groups.get.return_value = NetworkSecurityGroup( id="/subscriptions/d687b1a3-9b78-43b1-a17b-7de297fd1fce/resourceGroups/accelerators-team-resources/providers/Microsoft.Network/networkSecurityGroups/port_rules_testing_2", location="eastus", security_rules=[security_rule1, security_rule2], ) assert ( action.remediate(client, "resource_group", "network_security_group_name") == 0 ) assert client.security_rules.begin_delete.call_count == 1 assert client.network_security_groups.get.call_count == 1
def create_security_group(self): """ Creates firewall rules :return: """ with open(f'WebApp/DeploymentLogs/{self.protocol_name}.log', 'a+') as output_file: print('Creating security groups', file=output_file) parameters = NetworkSecurityGroup() parameters.location = 'useast1' parameters.security_rules = [ SecurityRule(description='AllIn', protocol='Tcp', source_port_range='*', destination_port_range='*', access='Allow', direction='Inbound', priority=100, name='AllIn'), SecurityRule(description='AllIn', protocol='Tcp', source_port_range='*', destination_port_range='*', access='Allow', direction='Outbound', priority=100, name='AllIn') ] self.network_client.network_security_groups.create_or_update( self.resource_group, "test-nsg", parameters) with open(f'WebApp/DeploymentLogs/{self.protocol_name}.log', 'a+') as output_file: print( 'Done creating security groups, you will redirect to the deployment in few seconds..', file=output_file)
def create_nsg_allow_rule( self, rule_name, rule_priority, resource_group_name, nsg_name, src_address=RouteNextHopType.internet, dst_address=SecurityRuleProtocol.asterisk, src_port_range=SecurityRuleProtocol.asterisk, dst_port_range=SecurityRuleProtocol.asterisk, protocol=SecurityRuleProtocol.asterisk, ): """Create NSG Allow Rule. :param str rule_name: :param str rule_priority: :param str resource_group_name: :param str nsg_name: :param str src_address: :param str dst_address: :param str src_port_range: :param str dst_port_range: :param str protocol: :return: """ self._logger.info( f"Creating security rule {rule_name} on NSG {nsg_name}...") rule = SecurityRule( name=rule_name, access=SecurityRuleAccess.allow, direction=self.INBOUND_RULE_DIRECTION, source_address_prefix=src_address, source_port_range=src_port_range, destination_address_prefix=dst_address, destination_port_range=dst_port_range, priority=rule_priority, protocol=protocol, ) self._azure_client.create_nsg_rule( resource_group_name=resource_group_name, nsg_name=nsg_name, rule=rule)
def create_rule_instance(rule): ''' Create an instance of SecurityRule from a dict. :param rule: dict :return: SecurityRule ''' return SecurityRule( protocol=rule['protocol'], source_address_prefix=rule['source_address_prefix'], destination_address_prefix=rule['destination_address_prefix'], access=rule['access'], direction=rule['direction'], id=rule.get('id', None), description=rule.get('description', None), source_port_range=rule.get('source_port_range', None), destination_port_range=rule.get('destination_port_range', None), priority=rule.get('priority', None), provisioning_state=rule.get('provisioning_state', None), name=rule.get('name', None), etag=rule.get('etag', None))
def create_default_securitygroup(self, resource_group, location, name, os_type, open_ports): ''' Create a default security group <name>01 to associate with a network interface. If a security group matching <name>01 exists, return it. Otherwise, create one. :param resource_group: Resource group name :param location: azure location name :param name: base name to use for the security group :param os_type: one of 'Windows' or 'Linux'. Determins any default rules added to the security group. :param ssh_port: for os_type 'Linux' port used in rule allowing SSH access. :param rdp_port: for os_type 'Windows' port used in rule allowing RDP access. :return: security_group object ''' security_group_name = name + '01' group = None self.log("Create security group {0}".format(security_group_name)) self.log("Check to see if security group {0} exists".format( security_group_name)) try: group = self.network_client.network_security_groups.get( resource_group, security_group_name) except CloudError: pass if group: self.log("Security group {0} found.".format(security_group_name)) self.check_provisioning_state(group) return group parameters = NetworkSecurityGroup() parameters.location = location if not open_ports: # Open default ports based on OS type if os_type == 'Linux': # add an inbound SSH rule parameters.security_rules = [ SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow SSH Access', source_port_range='*', destination_port_range='22', priority=100, name='SSH') ] parameters.location = location else: # for windows add inbound RDP and WinRM rules parameters.security_rules = [ SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow RDP port 3389', source_port_range='*', destination_port_range='3389', priority=100, name='RDP01'), SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow WinRM HTTPS port 5986', source_port_range='*', destination_port_range='5986', priority=101, name='WinRM01'), ] else: # Open custom ports parameters.security_rules = [] priority = 100 for port in open_ports: priority += 1 rule_name = "Rule_{0}".format(priority) parameters.security_rules.append( SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', source_port_range='*', destination_port_range=str(port), priority=priority, name=rule_name)) self.log( 'Creating default security group {0}'.format(security_group_name)) try: poller = self.network_client.network_security_groups.create_or_update( resource_group, security_group_name, parameters) except Exception as exc: self.fail("Error creating default security rule {0} - {1}".format( security_group_name, str(exc))) return self.get_poller_result(poller)
def test_remediate_success(self): compute_client = Mock() nw_profile = NetworkProfile(network_interfaces=[ NetworkInterfaceReference( id= "/subscriptions/subscription_id/resourceGroups/resource_group/providers/Microsoft.Network" "/networkInterfaces/vm_nameVMNic ") ]) compute_client.virtual_machines.get.return_value = VirtualMachine( id= "/subscriptions/subscription_id/resourceGroups/resource_group/providers/Microsoft.Compute" "/virtualMachines/vm_name", location="eastus", network_profile=nw_profile, ) nw_client = Mock() nw_client.network_interfaces.get.return_value = NetworkInterface( id= "/subscriptions/subscription_id/resourceGroups/resource_group/providers/Microsoft.Network" "/networkInterfaces/vm_nameVMNic", network_security_group=NetworkSecurityGroup( id= "/subscriptions/subscription_id/resourceGroups/resource_name/providers/Microsoft.Network" "/networkSecurityGroups/vm_nameNSG "), ) nw_client.network_security_groups.get.return_value = NetworkSecurityGroup( id= "/subscriptions/subscription_id/resourceGroups/resource_name/providers/Microsoft.Network" "/networkSecurityGroups/vm_nameNSG", security_rules=[ SecurityRule( protocol="All", access="Allow", direction="Inbound", source_address_prefix="*", destination_port_ranges=["22", "3389"], ), SecurityRule( protocol="All", access="Allow", direction="Inbound", source_address_prefix="*", destination_port_ranges=["20-30", "3389"], ), SecurityRule( protocol="All", access="Allow", direction="Inbound", source_address_prefix="*", destination_port_range="22", ), ], ) action = VMSecurityGroupClosePort22() assert (action.remediate(compute_client, nw_client, "resource_name", "vm_name") == 0) assert nw_client.network_security_groups.create_or_update.call_count == 1 call_args = nw_client.network_security_groups.create_or_update.call_args updated_sg = call_args.args[2] security_rules = updated_sg.security_rules assert len(security_rules) == 2 assert security_rules[0].destination_port_ranges == ["3389"] assert security_rules[1].destination_port_ranges == [ "20-21", "23-30", "3389" ]
def _create_management_rules(self, group_name, management_vnet, sandbox_vnet_cidr, network_client, security_group_name, additional_mgmt_networks, logger): """Creates NSG management rules NOTE: NSG rules must be created only one by one, without concurrency :param str group_name: resource group name (reservation id) :param str management_vnet: management network :param azure.mgmt.network.NetworkManagementClient network_client: :param str security_group_name: NSG name from the Azure :param list additional_mgmt_networks: list of additional management networks :param logging.Logger logger: """ used_priorities = [] all_symbol = SecurityRuleProtocol.asterisk # rule 0 priority = 3950 used_priorities.append(priority) logger.info( "Creating NSG rule to deny inbound traffic from other subnets with priority {}..." .format(priority)) operation_poller = self.security_group_service.create_network_security_group_custom_rule( network_client=network_client, group_name=group_name, security_group_name=security_group_name, rule=SecurityRule(access=SecurityRuleAccess.allow, direction="Inbound", source_address_prefix=sandbox_vnet_cidr, source_port_range=all_symbol, name="rule_{}".format(priority), destination_address_prefix=sandbox_vnet_cidr, destination_port_range=all_symbol, priority=priority, protocol=all_symbol), async=True) # can't create next rule while previous is in the deploying state operation_poller.wait() # Rule 1 priority = 4000 used_priorities.append(priority) logger.info( "Creating NSG rule to deny inbound traffic from other subnets with priority {}..." .format(priority)) operation_poller = self.security_group_service.create_network_security_group_custom_rule( network_client=network_client, group_name=group_name, security_group_name=security_group_name, rule=SecurityRule(access=SecurityRuleAccess.deny, direction="Inbound", source_address_prefix='VirtualNetwork', source_port_range=all_symbol, name="rule_{}".format(priority), destination_address_prefix=all_symbol, destination_port_range=all_symbol, priority=priority, protocol=all_symbol), async=True) # can't create next rule while previous is in the deploying state operation_poller.wait() # Rule 2: source_address_prefix = management_vnet.address_space.address_prefixes[ 0] priority = 3900 used_priorities.append(priority) logger.info( "Creating (async) NSG rule to allow management subnet traffic with priority {}" .format(priority)) operation_poller = self.security_group_service.create_network_security_group_custom_rule( network_client=network_client, group_name=group_name, security_group_name=security_group_name, rule=SecurityRule(access=SecurityRuleAccess.allow, direction="Inbound", source_address_prefix=source_address_prefix, source_port_range=all_symbol, name="rule_{}".format(priority), destination_address_prefix=all_symbol, destination_port_range=all_symbol, priority=priority, protocol=all_symbol), async=True) operation_poller.wait() # free priorities for additional NSG rules mgmt_rules_priorities = (priority for priority in xrange(3900, 4001, 5) if priority not in used_priorities) # create NSG rules for additional management networks logger.info( "Creating NSG rules to allow traffic from additional management networks..." ) for additional_network, priority in zip(additional_mgmt_networks, mgmt_rules_priorities): logger.info( "Creating NSG rule for additional management network {} with priority {} ..." .format(additional_network, priority)) self.security_group_service.create_network_security_group_custom_rule( network_client=network_client, group_name=group_name, security_group_name=security_group_name, rule=SecurityRule(access=SecurityRuleAccess.allow, direction="Inbound", source_address_prefix=additional_network, source_port_range=all_symbol, name="rule_{}".format(priority), destination_address_prefix=all_symbol, destination_port_range=all_symbol, priority=priority, protocol=all_symbol), async=False)
def vm_open_port(resource_group_name, vm_name, network_security_group_name=None, apply_to_subnet=False): """ Opens a VM to all inbound traffic and protocols by adding a security rule to the network security group (NSG) that is attached to the VM's network interface (NIC) or subnet. The existing NSG will be used or a new one will be created. The rule name is 'open-port-cmd' and will overwrite an existing rule with this name. For multi-NIC VMs, or for more fine grained control, use the appropriate network commands directly (nsg rule create, etc). """ from azure.mgmt.network import NetworkManagementClient network = get_mgmt_service_client(NetworkManagementClient) vm = _vm_get(resource_group_name, vm_name) location = vm.location nic_ids = list(vm.network_profile.network_interfaces) if len(nic_ids) > 1: raise CLIError('Multiple NICs is not supported for this command. Create rules on the NSG ' 'directly.') elif not nic_ids: raise CLIError("No NIC associated with VM '{}'".format(vm_name)) # get existing NSG or create a new one nic = network.network_interfaces.get(resource_group_name, os.path.split(nic_ids[0].id)[1]) if not apply_to_subnet: nsg = nic.network_security_group else: from azure.cli.core.commands.arm import parse_resource_id subnet_id = parse_resource_id(nic.ip_configurations[0].subnet.id) subnet = network.subnets.get(resource_group_name, subnet_id['name'], subnet_id['child_name']) nsg = subnet.network_security_group if not nsg: from azure.mgmt.network.models import NetworkSecurityGroup nsg = LongRunningOperation('Creating network security group')( network.network_security_groups.create_or_update( resource_group_name=resource_group_name, network_security_group_name=network_security_group_name, parameters=NetworkSecurityGroup(location=location) ) ) # update the NSG with the new rule to allow inbound traffic from azure.mgmt.network.models import SecurityRule rule = SecurityRule(protocol='*', access='allow', direction='inbound', name='open-port-cmd', source_port_range='*', destination_port_range='*', priority=900, source_address_prefix='*', destination_address_prefix='*') nsg_name = nsg.name or os.path.split(nsg.id)[1] LongRunningOperation('Adding security rule')( network.security_rules.create_or_update( resource_group_name, nsg_name, 'open-port-cmd', rule) ) # update the NIC or subnet if not apply_to_subnet: nic.network_security_group = nsg return LongRunningOperation('Updating NIC')( network.network_interfaces.create_or_update( resource_group_name, nic.name, nic) ) else: from azure.mgmt.network.models import Subnet subnet.network_security_group = nsg return LongRunningOperation('Updating subnet')( network.subnets.create_or_update( resource_group_name=resource_group_name, virtual_network_name=subnet_id['name'], subnet_name=subnet_id['child_name'], subnet_parameters=subnet ) )
def add_nsg_rule( self, rg_name=None, location=None, nsg_name=None, protocol="Tcp", direction="Inbound", access="Allow", description="Test automation rule", source_port_range="*", destination_port_range=None, priority=700, name="test_automation", source_address_prefix="*", destination_address_prefix="*", ): """ Add new rule to Azure Network Security Group. Args: rg_name (str): Azure resource group name location (str): Azure resource group location nsg_name (str): Azure NSG name protocol (str): protocol for rule (Tcp, Udp) direction (str): web traffic direction (Inbound, Outbound) access (str): access policy for rule (Allow, Deny) description (str): rule description source_port_range (str): source port range for rule destination_port_range (str): destination port range for rule priority (int): rule priority name (str): rule name source_address_prefix (str): source address prefix destination_address_prefix (str): destination address prefix """ parameters = NetworkSecurityGroup() parameters.location = location try: parameters.security_rules = self.get_nsg(rg_name, nsg_name).security_rules except CloudError: parameters.security_rules = [] parameters.security_rules.append( SecurityRule( protocol=protocol, direction=direction, access=access, description=description, source_port_range=source_port_range, destination_port_range=destination_port_range, priority=priority, name=name, source_address_prefix=source_address_prefix, destination_address_prefix=destination_address_prefix, ) ) try: poller_obj = self.network_client.network_security_groups.create_or_update( rg_name, nsg_name, parameters ) except CloudError as cloud_err: self.colored_print(cloud_err.__repr__(), level="error") raise poller_obj.wait()