I am attempting to retrieve and add function/host keys for an Azure Government function app via Python. I am currently working with the information from this question and the corresponding API page. While these are not specific to Azure Government, I would think the process would be similar after updating the URLs to the Azure Government versions. However, I am receiving the error "No route registered for '/api/functions/admin/token'" when running the jwt part of the given code. Is this approach feasible for what I am trying to do?
I also found somewhere that I instead might want to try a GET request like this:
resp = requests.get("https://management.usgovcloudapi.net/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Web/sites/<function-app-name>/functions/admin/masterkey?api-version=20XX-XX-XX", headers={"Authorization": f"Bearer {something}"})
This gives me the error "{"error":{"code":"InvalidAuthenticationToken","message":"The access token is invalid."}}", though. If this is indeed the correct approach, then what format should the Bearer token take?
Bit late answering but it may be useful for someone else in the future, it took me a while to find out how to do this.
If you want to retrieve the keys of a specific function within a function app then you can use list_function_keys() function from the Python SDK
Working with the Az management API directly may be a bit annoying and since the Azure CLI is written in Python whatever operation you do with the CLI you can do it directly in a Python script.
Here's an example of how you can retrieve the keys
from azure.identity import DefaultAzureCredential
from azure.mgmt.web import WebSiteManagementClient
# Your subscription ID
SUB_ID = "00000000-0000-0000-0000-000000000000"
fn_name = "some_function" # Name of your function
app_name = "some_app" # Name of your site/function app
rg_name = "some_rg" # Resource group name to which the function belongs
web_client = WebSiteManagementClient(subscription_id=SUB_ID, credential=DefaultAzureCredential())
keys = web_client.web_apps.list_function_keys(rg_name, app_name, fn_name)
# Your keys will be accessible in the additional_properties param
print(keys.additional_properties)
Hope it helps! I'm new on Azure so if I'm doing something wrong, please don't hesitate to point out my mistake and share your correction
Related
I'd like to create virtual networks in every location in Azure that can support them, using Azure python SDK.
In the code below I'm limiting only to location germanynorth, but that is just to help reproduce the issue.
from azure.common.client_factory import get_client_from_auth_file
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.subscription import SubscriptionClient
from azure.mgmt.network import NetworkManagementClient
get_client_from_auth_file(ComputeManagementClient)
for location in get_client_from_auth_file(SubscriptionClient).subscriptions.list_locations(get_subscription_id()):
if location.name == 'germanynorth':
get_client_from_auth_file(NetworkManagementClient).virtual_networks.create_or_update(
resource_group_name=RESOURCE_GROUP_NAME,
virtual_network_name='test-network',
parameters={'location': location.name, 'address_space': {'address_prefixes': ['10.0.0.0/16']}, }
)
When running this I get the error:
msrestazure.azure_exceptions.CloudError: Azure Error: LocationNotAvailableForResourceType
Message: The provided location 'germanynorth' is not available for resource type 'Microsoft.Network/virtualNetworks'. List of available regions for the resource type is 'westus,eastus,northeurope,westeurope,eastasia,southeastasia,northcentralus,southcentralus,centralus,eastus2,japaneast,japanwest,brazilsouth,australiaeast,australiasoutheast,centralindia,southindia,westindia,canadacentral,canadaeast,westcentralus,westus2,ukwest,uksouth,koreacentral,koreasouth,francecentral,australiacentral,southafricanorth,uaenorth,switzerlandnorth,germanywestcentral,norwayeast'.
Very helpfully, the error includes a list of all the regions where virtualNetworks could be created, but of course this list will change over time.
What API in Azure can I use to figure out what locations (regions?) support virtual networks?
Thanks!
You can use Azure resource providers and types. You can refer the Microsoft article on the resource provider.
PowerShell script to get all supported azure regions to create Azure key Vault.
$locations = (((Get-AzResourceProvider -ProviderNamespace Microsoft.KeyVault)| Where-Object RegistrationState -eq "Registered").ResourceTypes | Where-Object ResourceTypeName -eq vaults).Locations
I actually figured out my own bounty.
https://learn.microsoft.com/en-us/rest/api/resources/providers/get
"Gets the specified resource provider."
I don't think this describes what it actually does, which is why I didn't find it. I had to just basically test a bunch of APIs to see what returned what.
This API will return a list of available locations for the provided resource type (in your subscription).
I just wish it didn't only return a list (East US) but also with the with a short code (code:location), for example (eastus:East US).
So to answer the actual question, if you can't use your python library for this, an option would be to use this REST API:
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Network?api-version=2021-04-01
Your list of locations will be under the json path: {response}.resourceTypes[0].locations, where resourceType eq "virtualNetworks"
To actually get the locationCode (short location code) you can query this API:
https://learn.microsoft.com/en-us/rest/api/resources/subscriptions/list-locations
then map your location from above with this response to get the short code ('East US' -> 'eastus'), which can be used in other rest APIs to create for example a virtual network.
There is an API with which we can list out all the available location under a given subscription id (I am not sure if there is an equivalent version of this API that can filter by resource type) -
API -
GET https://management.azure.com/subscriptions/{subscriptionId}/locations?api-version=2020-01-01
Quoting the documentation
This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list.
Perhaps, you can iterate through the list of available locations in your subscription and put it in a try/except block to create Vnet against all available regions in your subscription?
EDIT: Apologies, I realized it late, you are already iterating through the list of locations under your subscription id. I guess it's a matter of writing the code beneath the for loop in a try/except block, wherein you can except that particular error type and continue with your loop?
I'm attempting to programmatically register Service Principals in Azure AD using Python. It looks like I should be using the ServicePrincipalsOperations class, however the documentation does not clearly outline what is needed for the parameters. It appears that it is expecting data from other classes within azure.graphrbac, but the documentation is unclear.
I think I should be using the azure.graphrbac.GraphRbacManagementClient to generate the client parameter for ServicePrincipalsOperations, but that's just a guess at this point.
Similarly, I suspect that I would need to use azure.graphrbac.models.ServicePrincipalCreateParameters for the config parameter.
Has anyone successfully registered a Service Principal using Python that may be able to shed more light on these parameters?
Thanks in advance!
So you can use this test as a reference, but the documents do specify what you need to pass in to the method to create a service principal.
Sample code:
self.graphrbac_client.service_principals.create({
'app_id': app.app_id, # Do NOT use app.object_id
'account_enabled': False
})
More reading: Create service principal programmatically in Azure Python API
Using the Alexa Custom skills, and AWS Lambda Functions, I want to be able to just get the user's name from their account. I already set up permissions and account linking and verified that it works. However, there are no resources available for python 3.6 methods for retrieving the actual user info.
There is this page which has the method I need to use (get_profile_name()):
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/master/docs/en/SERVICE_CLIENTS.rst#upsserviceclient
However, it does not give me info on how I can access that method inside a Lambda Function.
My main function runs from:
def lambda_handler(event, context):
Event only has the JSON from the user input from the custom Alexa skill, which does not include a name, so I'm stuck on how to access anything that has the get_profile_name()
The only example I can possibly find is from this:
https://forums.developer.amazon.com/questions/181267/new-sdk-and-python-36-progressive-response-sample.html
which uses
handler_input.service_client_factory.get_profile_name()
But I cannot figure out how the handler_input is different from my "event"
I figured it would be simple to just get a name, but this is pretty complex. Has anyone done this before?
Please see the Alexa Customer Profile API documentation to get customers' name, email address and phone number.
This documentation details the request process -- here's an example from this documentation to get the phone number:
Host: api.amazonalexa.com
Accept: application/json
Authorization: Bearer MQEWY...6fnLok
GET https://api.amazonalexa.com/v2/accounts/~current/settings/Profile.name
Note you must obtain an access token to use as part of the request (how to obtain a token is also detailed on that page).
If the ASK Python SDK does not contain built-in support for the Alexa Customer Profile API it seems that you can just create a RESTful request as detailed.
Your code needs to have handler classes for your skill's intents with two methods:
can_handle(self, handler_input)
and
handle(self, handler_input)
This is how you get the handler_input via parameter.
There's a similar example here but to retrieve the address.
I'm a beginner at Python and I've been working to geocode a database using Pandas and Geocoder on Jupyter.
Since the df is a little long (around 3000 rows), I'd like to use Google's Geocoding API.
I've already created a free key, but I have no idea what I'm supposed to do with it. Help?
By the way, my code looks like this:
import geocoder
import pandas as pd
geo = geocoder
df=pd.read_excel('hsp2.xlsx')
df['Coordinates']=df['Address'].apply(geo.google).apply(lambda x: x.latlng if x != None else None)
df.to_csv('output.csv', sep='|', encoding='iso8859_15')
You need to set the environment variable before you import geocoder:
import os
os.environ["GOOGLE_API_KEY"] = "api_key_from_google_cloud_platform"
import geocoder
geo = geocoder.google(address)
latlong = geo.latlng
Note:
As Murmel mentioned in the comments, environment variables containing keys (and in general) should not be set inside of your code.
If you are deploying this somewhere then set up enviroment variables in your configuration file. Or even better, as a secret in something like Kubernetes.
Else set the environment variable in bash with
export GOOGLE_API_KEY=api_key_from_google_cloud_platform
Basically there are 2 options:
passing the API KEY as environment variable:
GOOGLE_API_KEY=YOUR-API-KEY-HERE python your_program.py
passing the API KEY as argument:
geocoder.google('some address', key='YOUR-API-KEY-HERE')
Details
You are using the python library called geocoder, which itself is a wrapper around multiple geocoding services.
If you look at the pypi page of geocoder, you can (ignoring the rendering problems) find the docs for geocoder. In your case you probably want to have a look at the Google related part of the docs.
For basic usage this seams to work even without an API KEY, but you can specify one using 2 variants:
Environment variable: Like Roman already showed. This approach is meant to be used to not have the API KEY in code - for security reasons. (Probably you want to upload your code into a public repository, but without exposing your API KEY to everyone.)
"Key" parameter: You can also provide your API KEY by specifying it using the key parameter, like:
geocoder.google('some address', key='YOUR-API-KEY-HERE')
I am agree with Roman answer. You can use that and it is working. I am bit afraid if I use geocoder in loop then google will definately block my ip address ,so I go through git hub code and found that geocoder get google api key from os.environ.get('GOOGLE_API_KEY'). You can see that in the picture:
I have been working for a while, trying to install SimpleAuth on Google App Engine and I am running in to trouble. First off in the bottom of the sample code they have this:
def _get_consumer_info_for(self, provider):
"""Should return a tuple (key, secret) for auth init requests.
For OAuth 2.0 you should also return a scope, e.g.
('my app id', 'my app secret', 'email,user_about_me')
The scope depends solely on the provider.
See example/secrets.py.template
"""
return secrets.AUTH_CONFIG[provider]
and I don't see the secrets file anywhere nor what it is supposed to do.
Then in addition to that small problem I am curious how I am supposed to render the providers and their login URLs to the user. This page: https://github.com/crhym3/simpleauth/blob/master/example/handlers.py has a great description of the general setup but it doesn't have any description of what we actually need to pass to the user to let them login.
Thanks!
First off, please take into account that it's just an example, so some code parts were simplified for the demo purposes.
secrets is a separate module. The README file says to copy secrets.py.template into secrets.py and set proper client/consumer ids and secrets. Again, see README for info on where to get client/secrets for different providers.
The rendering is up to you. What I did as an example is this:
<p>Try logging in with one of these:</p>
Google
Facebook
Yahoo! (OpenID)
Twitter
LinkedIn
Windows Live
Those /auth/... links should get routed to your handler (normally webapp2.RequestHandler or some subclass) that's mixed in with SimpleAuthHandler.
You can see the example app live at https://simpleauth.appspot.com, hopefully it'll clarify things.