how to update azure vm firewall inbound port rules using python - python

I want to bind/update/white listing my IP address in inbound port rules using python(automate).
I went through this url! and what
I understood
credentials = ServicePrincipalCredentials(
client_id=os.environ['AZURE_CLIENT_ID'],
secret=os.environ['AZURE_CLIENT_SECRET'],
tenant=os.environ['AZURE_TENANT_ID']
)
resource_client = ResourceManagementClient(credentials, subscription_id)
compute_client = ComputeManagementClient(credentials, subscription_id)
storage_client = StorageManagementClient(credentials, subscription_id)
network_client = NetworkManagementClient(credentials, subscription_id)
# Create VNet
print('Create Vnet')
async_vnet_creation = network_client.virtual_networks.create_or_update(
GROUP_NAME,
VNET_NAME,
{
'location': LOCATION,
'address_space': {
'address_prefixes': ['10.0.0.0/16']
}
}
)
async_vnet_creation.wait()
# Create Subnet
async_subnet_creation = network_client.subnets.create_or_update(
GROUP_NAME,
VNET_NAME,
SUBNET_NAME,
{'address_prefix': '10.0.0.0/24'}
)
subnet_info = async_subnet_creation.result()
# Creating NIC
print('Creating NetworkInterface 1')
back_end_address_pool_id = lb_info.backend_address_pools[0].id
inbound_nat_rule_1_id = lb_info.inbound_nat_rules[0].id
async_nic1_creation = network_client.network_interfaces.create_or_update(
GROUP_NAME,
VMS_INFO[1]['nic_name'],
create_nic_parameters(
subnet_info.id, back_end_address_pool_id, inbound_nat_rule_1_id)
)
inbound_nat_rule_2_id = lb_info.inbound_nat_rules[1].id
print('Creating NetworkInterface 2')
async_nic2_creation = network_client.network_interfaces.create_or_update(
GROUP_NAME,
VMS_INFO[2]['nic_name'],
create_nic_parameters(
subnet_info.id, back_end_address_pool_id, inbound_nat_rule_2_id)
)
nic1_info = async_nic1_creation.result()
nic2_info = async_nic2_creation.result()
But I didn't find a place to add ip which I want to whitelisting.
please help on this
or please tell how to whitelist my IP using python azure SDK ?

If you want to create a new inbound rule for an existing NSG, you can use the following script:
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
from azure.mgmt.resource.resources import ResourceManagementClient
subscription_id = 'xxxxxxxxx-xxxxxxxxxxxxxxxxxxxx'
credentials = ServicePrincipalCredentials(
client_id = 'xxxxxx-xxxx-xxx-xxxx-xxxxxxx',
secret = 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx',
tenant = 'xxxxxx-xxxxxxx'
)
network_client = NetworkManagementClient(
credentials,
subscription_id
)
resource_client = ResourceManagementClient(
credentials,
subscription_id
)
resource_client.providers.register('Microsoft.Network')
resource_group_name = 'test-rg'
async_security_rule = network_client.security_rules.create_or_update(
resource_group_name,
security_group_name,
new_security_rule_name,
{
'access':azure.mgmt.network.v2017_03_01.models.SecurityRuleAccess.allow,
'description':'New Test security rule',
'destination_address_prefix':'*',
'destination_port_range':'123-3500',
'direction':azure.mgmt.network.v2017_03_01.models.SecurityRuleDirection.inbound,
'priority':400,
'protocol':azure.mgmt.network.v2017_03_01.models.SecurityRuleProtocol.tcp,
'source_address_prefix':'*',
'source_port_range':'655',
}
)
security_rule = async_security_rule.result()
For more details, please refer to the link

Related

How to get the data instead of <azure.mgmt.compute.v2017_09_01.models.resource_sku_restrictions_py3.ResourceSkuRestrictions object at 0x071D8A10>?

I'm trying to fetch all the virtual machines details using from azure.mgmt.compute module ComputeManagementClient. As such I'm getting a json result of the data but at some places I'm getting this value . How do I get data from this object? Or please could you please explain what this means?
I haven't tried much because I'm not sure how to proceed forward with this kind of data
from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials
def trial(cred, subscription_id):
GROUP_NAME = 'please provide the resource group name of your subscription'
compute_client = ComputeManagementClient(cred, subscription_id)
temp = {}
for rsku in compute_client.resource_skus.list():
temp[rsku.name] = {
"tier": rsku.tier,
"size": rsku.size,
"family": rsku.family,
"kind": rsku.kind,
"capacity": rsku.capacity,
"locations": rsku.locations[0],
"costs": rsku.costs,
"restrictions": rsku.restrictions
}
print(temp, "\n")
def authenticate():
subscription_id = '0000000000000000000000000'
try:
credentials = ServicePrincipalCredentials(
client_id = '00000000000000000000',
secret = '0000000000000000000000',
tenant = '00000000000000000000000'
)
return credentials, subscription_id
except :
return ("We are stuck")
if __name__ == "__main__":
cred, subscription_id = authenticate()
trial(cred, subscription_id)
'restrictions': [<azure.mgmt.compute.v2017_09_01.models.resource_sku_restrictions_py3.ResourceSkuRestrictions object at 0x071D8A10>]}
Hi there so figured out where I went wrong.
As such the output that was coming was a location of object.
So, I user
print(dir(rsku))
which gave out all the functions available for the object. The most relevant was value.
so I used
print(rsku.restriction.value)
Hope this helps

Issues with Network security group deployment using python : NetworkSecurityGroup' object has no attribute 'lower'

Thanks in advance, I'm trying to create NSG using python and getting an issue with
Message=Unable to build a model: Unable to deserialize to object:
type, AttributeError: 'NetworkSecurityGroup' object has no attribute
'lower', DeserializationError: Unable to deserialize to object: type,
AttributeError: 'NetworkSecurityGroup' object has no attribute 'lower'
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute.models import DiskCreateOption
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
import azure.mgmt.network.models
SUBSCRIPTION_ID = 'XXXXX'
GROUP_NAME = 'AQRG'
LOCATION = 'westus'
VM_NAME = 'myVM'
def get_credentials():
credentials = ServicePrincipalCredentials(
client_id = 'xxxx',
secret = 'xxxx',
tenant = 'xxxx'
)
return credentials
def create_network_security_group(network_client):
params_create = azure.mgmt.network.models.NetworkSecurityGroup(
location=LOCATION,
security_rules=[
azure.mgmt.network.models.SecurityRule(
name='rdp rule',
access=azure.mgmt.network.models.SecurityRuleAccess.allow,
description='test security rule',
destination_address_prefix='*',
destination_port_range='3389',
direction=azure.mgmt.network.models.SecurityRuleDirection.inbound,
priority=500,
protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp,
source_address_prefix='*',
source_port_range='*',
),
],
),
result_create = network_client.network_security_groups.create_or_update(
GROUP_NAME,
'nsg-vm',
params_create,
)
return result_create.result()
# creation_result = create_network_security_group(network_client)
# print("------------------------------------------------------")
# print(creation_result)
# input('Press enter to continue...')
if __name__ == "__main__":
credentials = get_credentials()
resource_group_client = ResourceManagementClient(
credentials,
SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
credentials,
SUBSCRIPTION_ID
)
compute_client = ComputeManagementClient(
credentials,
SUBSCRIPTION_ID
)
creation_result = create_network_security_group(network_client)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')
I'm new to python and created this piece of code after few hours. I'm getting this error while deploying NSG and will have to work on the linking NSG to subnet
def attach_network_security_group(network_client):
params_create = azure.mgmt.network.models.Subnet(
network_security_group='nsg-vm',
)
result_create = network_client.subnets.create_or_update(
GROUP_NAME,
VNET,
SUBNET,
params_create,
)
return result_create.result()
For your issue, it's just a little mistake. You just need to delete the , and then the code will like below:
params_create = azure.mgmt.network.models.NetworkSecurityGroup(
location=LOCATION,
security_rules=[
azure.mgmt.network.models.SecurityRule(
name='rdp rule',
access=azure.mgmt.network.models.SecurityRuleAccess.allow,
description='test security rule',
destination_address_prefix='*',
destination_port_range='3389',
direction=azure.mgmt.network.models.SecurityRuleDirection.inbound,
priority=500,
protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp,
source_address_prefix='*',
source_port_range='*',
),
],
)

How to get output from paging container into a variable | Getting single virtual network from resource group

Thanks in advance, I have variable at the top of my code, LOCATION, VNET_NAME, SUBNET, SUBNETRANGE. I want to fill this information from the output of function List_VNET. Using this function I'm getting virtual network from resource group on azure (I've only single virtual network per resource group). And then wanted to populate it into the variable but it is giving output as paging container. I mostly work on powershell hence i know about arrays and we can get an instance using array[0].
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute.models import DiskCreateOption
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
import azure.mgmt.network.models
SUBSCRIPTION_ID = 'xxx'
GROUP_NAME = 'AQRG'
LOCATION = ''
VM_NAME = 'myVM'
VNET_NAME = ''
SUBNET_NAME = ''
SUBNETRANGE = ''
def List_VNET(network_client):
result_create = network_client.virtual_networks.list(
GROUP_NAME,
)
SUBNET_NAME = result_create
return SUBNET_NAME
def get_credentials():
credentials = ServicePrincipalCredentials(
client_id = 'xxxx',
secret = 'xxxx',
tenant = 'xxxx'
)
return credentials
if __name__ == "__main__":
credentials = get_credentials()
resource_group_client = ResourceManagementClient(
credentials,
SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
credentials,
SUBSCRIPTION_ID
)
creation_result = List_VNET(network_client)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')
Getting output as below
<azure.mgmt.network.v2018_12_01.models.virtual_network_paged.VirtualNetworkPaged object at 0x0000023776C13908>
Update: Define the VNET_NAME as global in the function List_VNET:
SUBSCRIPTION_ID = 'xxx'
GROUP_NAME = 'AQRG'
LOCATION = ''
VM_NAME = 'myVM'
VNET_NAME = ''
SUBNET_NAME = ''
SUBNETRANGE = ''
def List_VNET(network_client):
result_create = network_client.virtual_networks.list(
GROUP_NAME
)
global VNET_NAME
for re in result_create:
VNET_NAME=re.name
return VNET_NAME
After the code: creation_result = List_VNET(network_client)
add the following code:
for re in creation_result:
print(re.name)
Then you can get all the virtual networks' name.

Getting all the properties of a vnet using python | List function only gives name

Thanks in advance, I wanted to get the region property of a vnet but using list function it only gives name property. Do we have to use another function to get the full details? currently i cannot do re.region. it only works with re.name
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute.models import DiskCreateOption
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
import azure.mgmt.network.models
SUBSCRIPTION_ID = 'xxxx'
GROUP_NAME = 'AQRG'
LOCATION = ''
VM_NAME = 'myVM'
VNET_NAME = ''
SUBNET = ''
def List_VNET(network_client):
result_create = network_client.virtual_networks.list(
GROUP_NAME,
)
global VNET_NAME
for re in result_create:
VNET_NAME = re.name
Region = re.region // This is not valid
return VNET_NAME
def get_credentials():
credentials = ServicePrincipalCredentials(
client_id = 'xxx',
secret = 'xxx',
tenant = 'xxxx'
)
return credentials
if __name__ == "__main__":
credentials = get_credentials()
resource_group_client = ResourceManagementClient(
credentials,
SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
credentials,
SUBSCRIPTION_ID
)
compute_client = ComputeManagementClient(
credentials,
SUBSCRIPTION_ID
)
creation_result_listvnet = List_VNET(network_client)
print("------------------------------------------------------")
print(creation_result_listvnet)
input('Press enter to continue...')
it should be re.location instead of re.region.
and I just found that you can fetch all the properties of virtual network with print(re). Then you can use any properties in the output.
FYI: The doc of VirtualNetwork class, which lists the properties.

Attaching NSG to Subnet using python

I'm trying to create NSG and then attach it to a existing subnet.
I've successfully able to create the NSG but it throws an error while attaching it to subnet. Stating that the address prefix cannot be null. Do we have to pass the address prefix as well? in below function?
params_create = azure.mgmt.network.models.Subnet(
Below is the full code snippet.
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute.models import DiskCreateOption
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
import azure.mgmt.network.models
SUBSCRIPTION_ID = 'xxx'
GROUP_NAME = 'xxxx'
LOCATION = 'xxxx'
VM_NAME = 'myVM'
VNET = 'existingvnet'
SUBNET = 'default'
def get_credentials():
credentials = ServicePrincipalCredentials(
client_id = 'xxx',
secret = 'xxxx',
tenant = 'xxxx'
)
return credentials
def create_network_security_group(network_client):
params_create = azure.mgmt.network.models.NetworkSecurityGroup(
location=LOCATION,
security_rules=[
azure.mgmt.network.models.SecurityRule(
name='rdprule',
access=azure.mgmt.network.models.SecurityRuleAccess.allow,
description='test security rule',
destination_address_prefix='*',
destination_port_range='3389',
direction=azure.mgmt.network.models.SecurityRuleDirection.inbound,
priority=500,
protocol=azure.mgmt.network.models.SecurityRuleProtocol.tcp,
source_address_prefix='*',
source_port_range='*',
),
],
)
result_create_NSG = network_client.network_security_groups.create_or_update(
GROUP_NAME,
'nsg-vm',
params_create,
)
return result_create_NSG.result()
def attach_network_security_group(network_client,creation_result_nsg):
params_create = azure.mgmt.network.models.Subnet(
network_security_group= creation_result_nsg,
)
result_create = network_client.subnets.create_or_update(
GROUP_NAME,
VNET,
SUBNET,
params_create,
)
return result_create.result()
if __name__ == "__main__":
credentials = get_credentials()
resource_group_client = ResourceManagementClient(
credentials,
SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
credentials,
SUBSCRIPTION_ID
)
compute_client = ComputeManagementClient(
credentials,
SUBSCRIPTION_ID
)
creation_result_nsg = create_network_security_group(network_client)
print("------------------------------------------------------")
print(creation_result_nsg)
input('Press enter to continue...')
creation_result = attach_network_security_group(network_client,creation_result_nsg)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')
that means you are not passing it the address prefix it should use. According to the docs you need to pass in address_prefix parameter. so add it to your params_create, something like this:
params_create = Subnet(
address_prefix = "10.0.0.0/24",
network_security_group = azure.mgmt.network.models.NetworkSecurityGroup(xxx)
)

Categories