Azure API Permission Fix - python

When trying to create a security group through the azure python sdk, I get this permissions issue: msrest.exceptions.ValidationError: Parameter 'SecurityRule.access' can not be None. How should I fix this permissions issue through the azure web console?

According to my understanding, you want to use python sdk to create an Azure Network security group. 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

I am authenticating to azure through python to list down all my virtual machines and I am getting this error

I am getting this error when I try to list down all my vms on Azure through python
Code: AuthorizationFailed
Message: The client "XXXX" with object id "XXXX" does not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/XXXXX or the scope is invalid. If access was recently granted, please refresh your credentials.
my code is below:
from azure.mgmt.compute import ComputeManagementClient
from azure.identity import ClientSecretCredential
Subscription_Id = "XXXX"
Tenant_Id = "XXXXX"
Client_Id = "XXXXX"
Secret = "XXXXX"
credential = ClientSecretCredential(
client_id=Client_Id,
client_secret=Secret,
tenant_id=Tenant_Id
)
compute_client = ComputeManagementClient(credential, Subscription_Id)
vm_list = compute_client.virtual_machines.list_all()
pageobject1 = vm_list.by_page(continuation_token=None)
for page in pageobject1:
for j in page:
print(j)
Instead of passing your app registration applicationId/objectId you need to pass the service principal/appregistration name when you are trying to assign a particular role like virtualmachinecontributor to your Service principal as show in below.
Post providing the required access to the service principal/appregistration you will be able to pull the list of virtual machines in your subscription. we have checked the above python in our local environment which is also working fine.
Here is sample output screenshot for reference:
Updated Answer To pull list of VM's using Resource Management Client:
from azure.mgmt.resource import ResourceManagementClient
from azure.identity import ClientSecretCredential
Subscription_Id = "<subId>"
Tenant_Id = "<tenantid>"
Client_Id = "<appId>"
Secret = "<clientSecret>"
credential = ClientSecretCredential(
client_id=Client_Id,
client_secret=Secret,
tenant_id=Tenant_Id
)
resource_client=ResourceManagementClient(credential=credential,subscription_id=Subscription_Id)
resource_list=resource_client.resources.list()
for item in resource_list:
if(item.type == 'Microsoft.Compute/virtualMachines'):
print(item)

List all Azure Data factories in the subscription using Python

I am trying to list all Azure Datafactories in a subscription using below code. I know the "list" from factories operation class is not properly defined but I am not getting much info about its usage sample from documentation, if any one please advise. #newtopython
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.datafactory import DataFactoryManagementClient
from DataFactoryManagement import list
from azure.mgmt.datafactory.models import *
from datetime import datetime, timedelta
import time
credentials = ServicePrincipalCredentials(
client_id='#####################',
secret='###########',
tenant='#############################'
)
subscription_id = '################'
client = DataFactoryManagementClient(credentials, subscription_id)
adf = client.factories:list()
print (adf)
If you want to list all the ADFs in the subscription, you need to use the list method, it works fine on my side.
Sample:
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.datafactory import DataFactoryManagementClient
subscription_id = 'xxxxx'
credentials = ServicePrincipalCredentials(client_id='xxxxx', secret='xxxxx', tenant='xxxxx')
adf_client = DataFactoryManagementClient(credentials, subscription_id)
Factories = adf_client.factories.list()
for factory in Factories:
print(factory)

how to get public IP of azure scale set instance from python API azure sdk?

I have assigned to each instance public IP (no Load Balancer ), i tried to get it's public IP from the python code but no luck, what i try so far :
from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.network import NetworkManagementClient
credentials = ServicePrincipalCredentials(client_id=ID, secret=SECRET_KEY, tenant=TENANT_ID)
for net in NetworkManagementClient(credentials, SUBSCRIPTION_ID):
print net
the IP is not here .
i have also tried via scale set object that returned from this :
vmss = ComputeManagementClient(credentials, SUBSCRIPTION_ID).virtual_machine_scale_set_vms.list(resource_group_name=resource_group,
virtual_machine_scale_set_name=scale_set_name)
but i don't see property of public IP in it .
I wasn't sure of this myself so I had a look. Turns out there is an API under the virtual networks service that lists all public IP addresses of a scale set.
This code should work for you, it'll list all of the public IP addresses in use inside of a scale set.
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
# Your Azure Subscription ID
subscription_id = 'xxxx-xxxx-xxxx'
compute_client = ComputeManagementClient(credentials, subscription_id)
network_client = NetworkManagementClient(credentials, subscription_id)
rg = 'testscaleset-rg'
scaleset_name = 'testscaleset'
for i, vm in enumerate(compute_client.virtual_machine_scale_set_vms.list(resource_group_name=rg, virtual_machine_scale_set_name=scaleset_name)):
nic_name = (vm.network_profile.network_interfaces[0].id).split("/")[-1]
ip_config_name = vm.network_profile_configuration \
.network_interface_configurations[0]\
.ip_configurations[0]\
.name
ip_address_name = vm.network_profile_configuration \
.network_interface_configurations[0]\
.ip_configurations[0]\
.public_ip_address_configuration\
.name
print(vm.name, (network_client.public_ip_addresses.get_virtual_machine_scale_set_public_ip_address( \
resource_group_name=rg, \
virtual_machine_scale_set_name=scaleset_name,\
virtualmachine_index=i, \
network_interface_name=nic_name, \
ip_configuration_name=ip_config_name, \
public_ip_address_name=ip_address_name)).ip_address)
Should return
testscaleset_0 40.68.133.234

python script for azure activity log

from azure.monitor import MonitorClient
#from azure.mgmt.monitor import MonitorMgmtClient
from azure.mgmt.monitor import MonitorManagementClient
from azure.common.credentials import UserPassCredentials
import datetime
# Replace this with your subscription id
subscription_id = '************'
# See above for details on creating different types of AAD credentials
credentials = UserPassCredentials(
'****', # Your user
'****', # Your password
)
client = MonitorClient(
credentials,
subscription_id
)
monitor_mgmt_client = MonitorManagementClient(
credentials,
subscription_id
)
after running this code its giving error:
raise error
msrest.exceptions.AuthenticationError: , InvalidClientIdError: (invalid_request) AADSTS900144: The request body must contain the following parameter: 'client_id'
It seems you should not use UserPassCredentials anymore, it has been deprecated.
See this link:
In previous version of the SDK, ADAL was not yet available and we provided a UserPassCredentials class. This is considered deprecated and should not be used anymore.
For Authenticate with token credentials, you could try the code below.
from azure.common.credentials import ServicePrincipalCredentials
# Tenant ID for your Azure Subscription
TENANT_ID = 'ABCDEFGH-1234-1234-1234-ABCDEFGHIJKL'
# Your Service Principal App ID
CLIENT = 'a2ab11af-01aa-4759-8345-7803287dbd39'
# Your Service Principal Password
KEY = 'password'
credentials = ServicePrincipalCredentials(
client_id = CLIENT,
secret = KEY,
tenant = TENANT_ID
)
If you need more control, it is recommended to use ADAL and the SDK ADAL wrapper.
import adal
from msrestazure.azure_active_directory import AdalAuthentication
from msrestazure.azure_cloud import AZURE_PUBLIC_CLOUD
# Tenant ID for your Azure Subscription
TENANT_ID = 'ABCDEFGH-1234-1234-1234-ABCDEFGHIJKL'
# Your Service Principal App ID
CLIENT = 'a2ab11af-01aa-4759-8345-7803287dbd39'
# Your Service Principal Password
KEY = 'password'
LOGIN_ENDPOINT = AZURE_PUBLIC_CLOUD.endpoints.active_directory
RESOURCE = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id
context = adal.AuthenticationContext(LOGIN_ENDPOINT + '/' + TENANT_ID)
credentials = AdalAuthentication(
context.acquire_token_with_client_credentials,
RESOURCE,
CLIENT,
KEY
)
For more details, you could refer to this link : Authenticate with the Azure Management Libraries for Python.
If you don't have an AD App, follow this link to create it. To get the client id(client id is the same with application id) and key, follow this link.

Azure Python SDK Error

I have written python code to get azure resources for a subscription using azure-python sdk,
the function to list all the resources inside a resource group is not working, this was working fine a week before, may be the microsoft have changed their api??
I am getting an attribute error,
AttributeError: 'ResourceGroupsOperations' object has no attribute 'list_resources'
Please Find the code below,
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource.resources import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
subscription_id = ''
credentials = ServicePrincipalCredentials(
client_id = '',
secret = '',
tenant = '',
)
resource_client = ResourceManagementClient(credentials,subscription_id)
resource_client.providers.register('Microsoft.Batch')
def get_resources():
for rg in resource_client.resource_groups.list():
for item in resource_client.resource_groups.list_resources(rg.name):
print "%s,%s,%s,%s,"%(item.name,item.type,item.location,rg.name)
get_resources()
Plz do help on this! thanks in advance !
Just an summary , you can find a description of the list_resources method has been removed in 2017-05-04 from SDK source code version statement.
resource_groups.list_resources has been moved to resources.list_by_resource_group
Python SDK upgrade should be the reason for your issue.
Please modify your code as below and it will work.
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource.resources import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
subscription_id = ''
credentials = ServicePrincipalCredentials(
client_id = '',
secret = '',
tenant = '',
)
resource_client = ResourceManagementClient(credentials,subscription_id)
resource_client.providers.register('Microsoft.Batch')
def get_resources():
for rg in resource_client.resource_groups.list():
for item in resource_client.resources.list_by_resource_group(rg.name):
print "%s,%s,%s,%s,"%(item.name,item.type,item.location,rg.name)
get_resources()
Thats because there is no such operation, you are looking for list_by_resource_group operation.
https://learn.microsoft.com/es-es/python/api/azure.mgmt.resource.resources.v2017_05_10.operations.resourcesoperations?view=azure-python#azure_mgmt_resource_resources_v2017_05_10_operations_ResourcesOperations_list_by_resource_group

Categories