Skip to content

Commit

Permalink
{Network} az network vnet-gateway packet-capture/vpn-client: Migrat…
Browse files Browse the repository at this point in the history
…e to atomic commands (#25314)
  • Loading branch information
ZengTaoxu authored Feb 9, 2023
1 parent 7739430 commit 721e29d
Show file tree
Hide file tree
Showing 20 changed files with 2,217 additions and 607 deletions.
36 changes: 0 additions & 36 deletions src/azure-cli/azure/cli/command_modules/network/_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from knack.util import CLIError
from azure.cli.core.azclierror import UnrecognizedArgumentError
from ._validators import read_base_64_file
from ._util import enum_check


# pylint: disable=protected-access
Expand Down Expand Up @@ -135,41 +134,6 @@ def get_action(self, values, option_string): # pylint: disable=no-self-use
return d


class NatRuleCreate(argparse._AppendAction):
def __call__(self, parser, namespace, values, option_string=None):
action = self.get_action(values, option_string)
super(NatRuleCreate, self).__call__(parser, namespace, action, option_string)

def get_action(self, values, option_string): # pylint: disable=no-self-use
try:
properties = defaultdict(list)
for (k, v) in (x.split('=', 1) for x in values):
properties[k].append(v)
properties = dict(properties)
except ValueError:
raise UnrecognizedArgumentError('usage error: {} [KEY=VALUE ...]'.format(option_string))
d = {}
for k in properties:
kl = k.lower()
v = properties[k]
if kl == 'type':
d['type'] = enum_check(v[0], ['Static', 'Dynamic'])
elif kl == 'name':
d['name'] = v[0]
elif kl == 'mode':
d['mode'] = enum_check(v[0], ['EgressSnat', 'IngressSnat'])
elif kl == 'internal-mappings':
d['internal_mappings'] = _split(v[0])
elif kl == 'external-mappings':
d['external_mappings'] = _split(v[0])
elif kl == 'ip-config-id':
d['ip_config_id'] = v[0]
else:
raise UnrecognizedArgumentError('key error: key must be one of type, mode, internal-mappings,'
'external-mappings, ip-config-id')
return d


class AddMappingRequest(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
action = self.get_action(values, option_string)
Expand Down
117 changes: 14 additions & 103 deletions src/azure-cli/azure/cli/command_modules/network/_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from azure.cli.command_modules.network._validators import (
dns_zone_name_type, validate_inbound_nat_rule_id_list,
validate_address_pool_id_list, validate_inbound_nat_rule_name_or_id,
validate_address_pool_name_or_id, load_cert_file, validate_metadata,
validate_address_pool_name_or_id, validate_metadata,
validate_dns_record_type, validate_private_ip_address,
get_servers_validator, get_public_ip_validator, get_nsg_validator, get_subnet_validator,
get_network_watcher_from_vm, get_network_watcher_for_pcap_creation, get_network_watcher_from_location, validate_capture_size_and_limit,
Expand All @@ -31,14 +31,13 @@
validate_waf_policy,
validate_user_assigned_identity, validate_virtul_network_gateway,
NWConnectionMonitorEndpointFilterItemAction, NWConnectionMonitorTestConfigurationHTTPRequestHeaderAction,
process_private_link_resource_id_argument, process_private_endpoint_connection_id_argument,
validate_vpn_connection_name_or_id)
process_private_link_resource_id_argument, process_private_endpoint_connection_id_argument)
from azure.cli.command_modules.network._completers import (
subnet_completion_list, get_lb_subresource_completion_list, get_ag_subresource_completion_list,
ag_url_map_rule_completion_list, tm_endpoint_completion_list)
from azure.cli.command_modules.network._actions import (
TrustedClientCertificateCreate,
SslProfilesCreate, NatRuleCreate, AddMappingRequest, WAFRulesCreate)
SslProfilesCreate, AddMappingRequest, WAFRulesCreate)
from azure.cli.core.util import get_json_object
from azure.cli.core.profiles import ResourceType

Expand All @@ -47,25 +46,23 @@
def load_arguments(self, _):

(ApplicationGatewayProtocol,
ApplicationGatewayRequestRoutingRuleType, ApplicationGatewaySkuName, ApplicationGatewaySslProtocol, AuthenticationMethod,
Direction, VpnAuthenticationType,
ApplicationGatewayRequestRoutingRuleType, ApplicationGatewaySkuName, ApplicationGatewaySslProtocol,
Direction,
FlowLogFormatType, HTTPMethod, IPAllocationMethod,
IPVersion, ProbeProtocol, ProcessorArchitecture, Protocol, PublicIPAddressSkuName, PublicIPAddressSkuTier,
IPVersion, ProbeProtocol, Protocol, PublicIPAddressSkuName, PublicIPAddressSkuTier,
SecurityRuleAccess, SecurityRuleProtocol, SecurityRuleDirection, TransportProtocol,
VirtualNetworkGatewaySkuName, VirtualNetworkGatewayType, VpnClientProtocol, VpnType,
ConnectionMonitorEndpointFilterType, ConnectionMonitorTestConfigurationProtocol,
PreferredIPVersion, HTTPConfigurationMethod, OutputType, DestinationPortBehavior, CoverageLevel, EndpointType,
VpnNatRuleType, VpnNatRuleMode, PacketCaptureTargetType) = self.get_models(
PacketCaptureTargetType) = self.get_models(
'ApplicationGatewayProtocol',
'ApplicationGatewayRequestRoutingRuleType', 'ApplicationGatewaySkuName', 'ApplicationGatewaySslProtocol', 'AuthenticationMethod',
'Direction', 'VpnAuthenticationType',
'ApplicationGatewayRequestRoutingRuleType', 'ApplicationGatewaySkuName', 'ApplicationGatewaySslProtocol',
'Direction',
'FlowLogFormatType', 'HTTPMethod', 'IPAllocationMethod',
'IPVersion', 'ProbeProtocol', 'ProcessorArchitecture', 'Protocol', 'PublicIPAddressSkuName', 'PublicIPAddressSkuTier',
'IPVersion', 'ProbeProtocol', 'Protocol', 'PublicIPAddressSkuName', 'PublicIPAddressSkuTier',
'SecurityRuleAccess', 'SecurityRuleProtocol', 'SecurityRuleDirection', 'TransportProtocol',
'VirtualNetworkGatewaySkuName', 'VirtualNetworkGatewayType', 'VpnClientProtocol', 'VpnType',
'ConnectionMonitorEndpointFilterType', 'ConnectionMonitorTestConfigurationProtocol',
'PreferredIPVersion', 'HTTPConfigurationMethod', 'OutputType', 'DestinationPortBehavior', 'CoverageLevel', 'EndpointType',
'VpnNatRuleType', 'VpnNatRuleMode', 'PacketCaptureTargetType')
'PacketCaptureTargetType')

ZoneType = self.get_models('ZoneType', resource_type=ResourceType.MGMT_NETWORK_DNS)

Expand Down Expand Up @@ -675,13 +672,6 @@ def load_arguments(self, _):
c.argument('threshold', help='The number of consecutive probe failures before an instance is deemed unhealthy.')
# endregion

# region VnetGateway
for item in ['vnet-gateway']:
with self.argument_context('network {}'.format(item)) as c:
c.argument('asn', type=int, arg_group='BGP Peering', help='Autonomous System Number to use for the BGP settings.')
c.argument('peer_weight', arg_group='BGP Peering', help='Weight (0-100) added to routes learned through BGP peering.')
# endregion

# region NetworkInterfaces (NIC)
with self.argument_context('network nic') as c:
c.argument('enable_accelerated_networking', min_api='2016-09-01', options_list=['--accelerated-networking'], help='Enable accelerated networking.', arg_type=get_three_state_flag())
Expand Down Expand Up @@ -1387,95 +1377,16 @@ def load_arguments(self, _):
# endregion

# region VirtualNetworkGateways
vnet_gateway_type = CLIArgumentType(help='The gateway type.', arg_type=get_enum_type(VirtualNetworkGatewayType), default=VirtualNetworkGatewayType.vpn.value)
vnet_gateway_sku_type = CLIArgumentType(help='VNet gateway SKU.', arg_type=get_enum_type(VirtualNetworkGatewaySkuName), default=VirtualNetworkGatewaySkuName.basic.value)
vnet_gateway_routing_type = CLIArgumentType(help='VPN routing type.', arg_type=get_enum_type(VpnType), default=VpnType.route_based.value)
edge_zone_vnet_id = CLIArgumentType(help='The Extended vnet resource id of the local gateway', min_api='2021-02-01')
with self.argument_context('network vnet-gateway') as c:
c.argument('virtual_network_gateway_name', options_list=['--name', '-n'], help='Name of the VNet gateway.', completer=get_resource_name_completion_list('Microsoft.Network/virtualNetworkGateways'), id_part='name')
c.argument('cert_name', help='Root certificate name', options_list=['--name', '-n'])
c.argument('gateway_name', help='Virtual network gateway name')
c.argument('gateway_type', vnet_gateway_type)
c.argument('gateway_default_site', help='Name or ID of a local network gateway representing a local network site with default routes.')
c.argument('sku', vnet_gateway_sku_type)
c.argument('vpn_type', vnet_gateway_routing_type)
c.argument('bgp_peering_address', arg_group='BGP Peering', help='IP address to use for BGP peering.')
c.argument('public_ip_address', options_list=['--public-ip-addresses'], nargs='+', help='Specify a single public IP (name or ID) for an active-standby gateway. Specify two space-separated public IPs for an active-active gateway.', completer=get_resource_name_completion_list('Microsoft.Network/publicIPAddresses'))
c.argument('address_prefixes', help='Space-separated list of CIDR prefixes representing the address space for the P2S Vpnclient.', nargs='+', arg_group='VPN Client')
c.argument('radius_server', min_api='2017-06-01', help='Radius server address to connect to.', arg_group='VPN Client')
c.argument('radius_secret', min_api='2017-06-01', help='Radius secret to use for authentication.', arg_group='VPN Client')
c.argument('client_protocol', min_api='2017-06-01', help='Protocols to use for connecting', nargs='+', arg_group='VPN Client', arg_type=get_enum_type(VpnClientProtocol))
c.argument('custom_routes', min_api='2019-02-01', help='Space-separated list of CIDR prefixes representing the custom routes address space specified by the customer for VpnClient.', nargs='+', arg_group='VPN Client')
c.argument('vpn_auth_type', min_api='2020-11-01', nargs='+', help='VPN authentication types enabled for the virtual network gateway.', arg_type=get_enum_type(VpnAuthenticationType))

with self.argument_context('network vnet-gateway', arg_group='AAD Authentication', min_api='2020-11-01') as c:
c.argument('aad_tenant', help='The AAD Tenant URI of the VirtualNetworkGateway.')
c.argument('aad_audience', help='The AADAudience ID of the VirtualNetworkGateway.')
c.argument('aad_issuer', help='The AAD Issuer URI of the VirtualNetworkGateway.')

with self.argument_context('network vnet-gateway', arg_group='Root Cert Authentication', min_api='2020-11-01') as c:
c.argument('root_cert_data', help='Base64 contents of the root certificate file or file path.', type=file_type, completer=FilesCompleter())
c.argument('root_cert_name', help='Root certificate name')

with self.argument_context('network vnet-gateway', arg_group='Nat Rule', min_api='2021-02-01') as c:
c.argument('nat_rule', nargs='+', action=NatRuleCreate)

with self.argument_context('network vnet-gateway update') as c:
c.argument('gateway_type', vnet_gateway_type, default=None)
c.argument('sku', vnet_gateway_sku_type, default=None)
c.argument('vpn_type', vnet_gateway_routing_type, default=None)

with self.argument_context('network vnet-gateway create') as c:
vnet_help = "Name or ID of an existing virtual network which has a subnet named 'GatewaySubnet'."
c.argument('virtual_network', options_list='--vnet', help=vnet_help)
c.argument('vpn_gateway_generation', arg_type=get_enum_type(['Generation1', 'Generation2']), min_api='2019-07-01', help='The generation for the virtual network gateway. vpn_gateway_generation should not be provided if gateway_type is not Vpn.')
c.argument('edge_zone', edge_zone, min_api='2021-02-01')
c.argument('edge_zone_vnet_id', edge_zone_vnet_id)

with self.argument_context('network vnet-gateway update') as c:
c.argument('enable_bgp', help='Enable BGP (Border Gateway Protocol)', arg_group='BGP Peering', arg_type=get_enum_type(['true', 'false']))
c.argument('virtual_network', virtual_network_name_type, options_list='--vnet', help="Name or ID of a virtual network that contains a subnet named 'GatewaySubnet'.")
c.extra('address_prefixes', options_list='--address-prefixes', help='List of address prefixes for the VPN gateway. Prerequisite for uploading certificates.', nargs='+')

with self.argument_context('network vnet-gateway aad assign', min_api='2019-04-01') as c:
c.argument('aad_tenant', options_list='--tenant', help='The AADTenant URI of the VirtualNetworkGateway.')
c.argument('aad_audience', options_list='--audience', help='The AADAudience ID of the VirtualNetworkGateway.')
c.argument('aad_issuer', options_list='--issuer', help='The AADIssuer URI of the VirtualNetworkGateway.')

with self.argument_context('network vnet-gateway root-cert create') as c:
c.argument('public_cert_data', help='Base64 contents of the root certificate file or file path.', type=file_type, completer=FilesCompleter(), validator=load_cert_file('public_cert_data'))
c.argument('cert_name', help='Root certificate name', options_list=['--name', '-n'])
c.argument('gateway_name', help='Virtual network gateway name')

with self.argument_context('network vnet-gateway revoked-cert create') as c:
c.argument('thumbprint', help='Certificate thumbprint.')

with self.argument_context('network vnet-gateway packet-capture start') as c:
c.argument('filter_data', options_list=['--filter'], help='Data filter.')

with self.argument_context('network vnet-gateway packet-capture stop') as c:
c.argument('sas_url', options_list=['--sas-url'],
help='The SAS url to be used for packet capture.')

with self.argument_context('network vnet-gateway vpn-client') as c:
c.argument('processor_architecture', help='Processor architecture of the target system.', arg_type=get_enum_type(ProcessorArchitecture))
c.argument('authentication_method', help='Method used to authenticate with the generated client.', arg_type=get_enum_type(AuthenticationMethod))
c.argument('processor_architecture', help='Processor architecture of the target system.', arg_type=get_enum_type(['Amd64', 'X86']))
c.argument('authentication_method', help='Method used to authenticate with the generated client.', arg_type=get_enum_type(['EAPMSCHAPv2', 'EAPTLS']))
c.argument('radius_server_auth_certificate', help='Public certificate data for the Radius server auth certificate in Base-64 format. Required only if external Radius auth has been configured with EAPTLS auth.')
c.argument('client_root_certificates', nargs='+', help='Space-separated list of client root certificate public certificate data in Base-64 format. Optional for external Radius-based auth with EAPTLS')
c.argument('use_legacy', min_api='2017-06-01', help='Generate VPN client package using legacy implementation.', arg_type=get_three_state_flag())

with self.argument_context('network vnet-gateway disconnect-vpn-connections') as c:
c.argument('vpn_connection_ids', options_list=['--vpn-connections'], nargs='+',
help='List of Name or ID of VPN connections.',
validator=validate_vpn_connection_name_or_id)

with self.argument_context('network vnet-gateway nat-rule', min_api='2021-02-01') as c:
c.argument('name', help='The name of the resource that is unique within a resource group. This name can be used to access the resource.')
c.argument('rule_type', options_list='--type', help='The type of NAT rule for VPN NAT.', arg_type=get_enum_type(VpnNatRuleType))
c.argument('mode', help='The Source NAT direction of a VPN NAT.', arg_type=get_enum_type(VpnNatRuleMode))
c.argument('internal_mappings', nargs='+', help='The private IP address internal mapping for NAT.')
c.argument('external_mappings', nargs='+', help='The private IP address external mapping for NAT.')
c.argument('ip_config_id', help='The IP Configuration ID this NAT rule applies to.')
# endregion

# region VirtualNetworkGatewayConnections
Expand Down Expand Up @@ -1547,7 +1458,7 @@ def load_arguments(self, _):
with self.argument_context('network routeserver create') as c:
c.argument('virtual_hub_name', id_part=None)

for scope in ['vpn-connection', 'vnet-gateway', 'vnet-gateway vpn-client']:
for scope in ['vpn-connection']:
with self.argument_context('network {} ipsec-policy'.format(scope), arg_group='Security Association') as c:
c.argument('sa_data_size_kilobytes', options_list=['--sa-max-size'], type=int, help='The payload size in KB for P2S client.')
c.argument('sa_life_time_seconds', options_list=['--sa-lifetime'], type=int, help='The lifetime in seconds for P2S client.')
Expand Down
14 changes: 0 additions & 14 deletions src/azure-cli/azure/cli/command_modules/network/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,20 +105,6 @@ def _validate_vpn_gateway_generation(namespace):
raise CLIError('vpn_gateway_generation should not be provided if gateway_type is not Vpn.')


def validate_vpn_connection_name_or_id(cmd, namespace):
if namespace.vpn_connection_ids:
from msrestazure.tools import is_valid_resource_id, resource_id
for index, vpn_connection_id in enumerate(namespace.vpn_connection_ids):
if not is_valid_resource_id(vpn_connection_id):
namespace.vpn_connection_ids[index] = resource_id(
subscription=get_subscription_id(cmd.cli_ctx),
resource_group=namespace.resource_group_name,
namespace='Microsoft.Network',
type='connections',
name=vpn_connection_id
)


def validate_ddos_name_or_id(cmd, namespace):
if namespace.ddos_protection_plan:
from msrestazure.tools import is_valid_resource_id, resource_id
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from azure.cli.core.aaz import *


@register_command_group(
"network vnet-gateway packet-capture",
)
class __CMDGroup(AAZCommandGroup):
"""Manage packet capture on a virtual network gateway.
"""
pass


__all__ = ["__CMDGroup"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from .__cmd_group import *
from ._start import *
from ._stop import *
Loading

0 comments on commit 721e29d

Please sign in to comment.