Python Function App connections using managed identity - python

Unable to set up connection information for service bus with Python Azure functions for managed identity.
I have the following settings in function.json
{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "msg",
"type": "serviceBusTrigger",
"direction": "in",
"queueName": "myinputqueue",
"connection": "MySvcConn"
}
]
}
and in Application settings in Azure portal i have set
"MySvcConn__fullyQualifiedNamespace":"mysvcns.servicebus.windows.net"
I get the message
"Microsoft.Azure.ServiceBus: Value for the connection string
parameter name 'mysvcns.servicebus.windows.net' was not found. (Parameter 'connectionString').
Version of Runtime used ~4
host.json configuration
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[2.*, 3.0.0)"
}
}

To connect to service bus using a managed Identity we have first add servicebus data receiver role to the access control.
Then add the connection setting to application setting under the name
ServiceBusConnection__fullyQualifiedNamespace and add the connection value as <Name_of_servicebus>.servicebus.windows.net.
The above setting will connect the function app to the service bus using managed identity without the use of connection string.
Refer this documentation

Was able to figure this out, need to set up application settings in function app for the following
ServiceBusConnection__clientID:<managedidenity client id>
ServiceBusConnection__credential:managedidentity
ServiceBusConnection__fullyQualifiedNamespace:<servicebusname>.servicebus.windows.net
"ServiceBusConnection" in the above settings being the connection name in function.json file.

Related

Azure Functions Python App - enable IdentityModelEventSource.ShowPII Property

I'm having some issues with the AAD authentication of my Python API which is hosted in Azure Functions.
The official documentation suggests to "enable PII to see the values removed from the message" in order to be able to check the Issuer & ValidIssuer. The documentation only references the .NET extension however. The search on learn.microsoft.com also only shows hits for .NET developers. How can I activate it for my Python API application?
The error code / return JSON I am stuck on:
{
"code": 401,
"message": "IDX10205: Issuer validation failed. Issuer: '[PII of type 'System.String' is hidden.
For more details, see https://aka.ms/IdentityModel/PII.]'.
Did not match: validationParameters.ValidIssuer:
'[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'
or validationParameters.ValidIssuers: '[PII of type 'System.String'
is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
For more details, see https://aka.ms/IdentityModel/issuer-validation. "
}
host.json file:
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": ""
}
}
}
local.settings.json file:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "python"
}
}
MyApp/function.json file:
{
"scriptFile": "__init__.py", # see below for contents
"disabled": false,
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
],
"route": "{*route}"
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
MyApp/__ init __.py file:
from ..FastAPIApp import app # see below for contents
nest_asyncio.apply()
logger = logging.getLogger()
#app.get("/status")
async def index() -> Dict:
return {
"info": "API is working normally.",
}
FastAPIApp/__ init __.py file:
import fastapi
app = fastapi.FastAPI()

How can I change localhost IP of azure function code when running it locally?

I am new to azure function.
I want to run my azure function code locally (in an azure virtual machine).
I'm running my code using this line in a linux VM terminal:
. env/bin/activate && func host start
It was successful with this output.
Azure Functions Core Tools
Core Tools Version: 4.0.4785 Commit hash: N/A (64-bit)
Function Runtime Version: 4.10.4.19213
Functions:
update-info: [GET,POST] http://localhost:7071/update-info
However, I wonder if it is possible to change localhost:7071 to the IP of my virtual machine so that it will be available online. Is it? If yes, how?; if not, how can I run HTTPS request/response program in a VM?
Another question if it is possible is can I change it from http to https? If yes, how?
Edited: - Adding Settings from the config files.
function.json
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
host.json
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[2.*, 3.0.0)"
},
"extensions": {
"http": {
"routePrefix": ""
}
}
}
Btw, I already figured out how to run it using https. I had to add --useHTTPS on the command like this: . env/bin/activate && func host start --useHttps
I just need to know how to change the localhost to the VM IP address.
Created the Azure Linux VM > Hosted Azure Functions Python Project (Http Trigger Function) on it.
Enabled the Ports HTTP, HTTPS & RDP for checking using the browser by enabling the XRDP & installed the Firefox browser
Glad that enabling the HTTPS flag is resolved by yourself.
I'm able to get the Function App Result with the local host and private IP address in Azure Linux VM:

How to access Azure Service Bus using Function App identity

I am following the steps listed here, but for python code:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-identity-based-connections-tutorial-2
Objective is to create a simple (hello world) function app which is triggered by Azure Service Bus message queue using identity-based connection. Function app works fine when ASB is reference via connection string, but gives this error when trying to connect via managed service identity of function app (used the specific configuration pattern __fullyQualifiedNamespace). MSI has been granted Role (Azure Service Bus Data Receiver) on ASB.
Microsoft.Azure.WebJobs.ServiceBus: Microsoft Azure WebJobs SDK ServiceBus connection string 'ServiceBusConnection__fullyQualifiedNamespace' is missing or empty.
Function code (autogenerated)
import logging
import azure.functions as func
def main(msg: func.ServiceBusMessage):
logging.info('Python ServiceBus queue trigger processed message: %s',
msg.get_body().decode('utf-8'))
function.json (connection value modified based on ms docs)
{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "msg",
"type": "serviceBusTrigger",
"direction": "in",
"queueName": "erpdemoqueue",
"connection": "ServiceBusConnection"
}
]
}
host.json (version modified based on ms docs)
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[3.3.0, 4.0.0)"
}
}
To use a managed identity, you'll need to add a setting that identifies the fully qualified namespace of your Service Bus instance.
For example, in your local.settings.json file for local development:
{
"Values": {
"<connection_name>__fullyQualifiedNamespace": "<service_bus_namespace>.servicebus.windows.net"
}
}
Or in the application settings for your function when deployed to Azure:
<connection_name>__fullyQualifiedNamespace=<service_bus_namespace>.servicebus.windows.net
This is mentioned only briefly in the tutorial that you linked. The Microsoft.Azure.WebJobs.Extensions.ServiceBus documentation does covers this a bit better in the Managed identity authentication section.

Azure Python Function Retry Limitting not Working in Logic Apps

I've tried two methods to limit the retries of a "failed" function and neither have worked (described below). I'm developmentally challenged, so any and all help would be appreciated.
The context: the function is placed in a logic app, which is triggered by an email, after the email attachment is saved to blob. After the file is saved, the function performs successfully but the logic app returns "BadRequest. Http request failed: the server did not respond within the timeout limit" after a run-time of 2-3 minutes. Then the logic app retries the function 4 additional times.
Method 1: I placed retry into the host.json:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[1.*, 2.0.0)"
},
"retry": {
"strategy": "fixedDelay",
"maxRetryCount": 0,
"delayInterval": "00:00:05"
}
}
Methods 2: I placed the same snippet into the function.json:
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
],
"retry": {
"strategy": "fixedDelay",
"maxRetryCount": 0,
"delayInterval": "00:00:10"
}
}
The retry policy is defined by azure logic app, you should not configure it in functions, but configure a retry policy in azure logic app actions. You can refer to Retry policies:
For the most basic exception and error handling, you can use a retry policy in any action or trigger where supported, for example, see HTTP action. A retry policy specifies whether and how the action or trigger retries a request when the original request times out or fails, which is any request that results in a 408, 429, or 5xx response. If no other retry policy is used, the default policy is used.
If you want to configure the number of retries to 0, please follow the steps below.
You can click ··· in the upper right corner of the Http action, then click Settings, and select None under Retry Policy:

Azure Error: data protection system cannot create a new key because auto-generation of keys is disabled

I am trying to run an azure function on my local machine using Visual Studio Code.
My main.py looks like this:
import logging
import azure.functions as func
def main(event: func.EventHubEvent):
logging.info('Python EventHub trigger processed an event: %s', event.get_body().decode('utf-8'))
My host.json file looks like this:
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[1.*, 2.0.0)"
}
}
My function.json looks something like this:
{
"scriptFile": "main.py",
"bindings": [
{
"type": "eventHubTrigger",
"name": "event",
"direction": "in",
"eventHubName": "myhubName",
"connection": "myHubConnection",
"cardinality": "many",
"consumerGroup": "$Default"
}
]
}
The problem is when I run this, it throws me the following error:
A host error has occurred at
Microsoft.AspNetCore.DataProtection: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information. Microsoft.AspNetCore.DataProtection: The key ring does not contain a valid default protection key. The data protection system cannot create a new key because auto-generation of keys is disabled.
Value cannot be null.
Parameter name: provider
I am not sure what I am I missing ? Any help is appreciated
The problem was with the Azure Storage account:
Make sure the local.settings.json has the correct credentials for the storage account
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "MyStorageKey",
"FUNCTIONS_WORKER_RUNTIME": "python",
}
}

Categories