Azure function how to use DefaultAzureCredential for development using Visual studio - azure

I creating an Azure Function app with ServiceBusTrigger. I am running Visual Studio under an account which is also used to logging into Visual Studio.
I have added this user account under Service Bus Access Control & assigned Azure Service Bus Data Receiver and Azure Service Bus Data Sender roles.
[FunctionName("Function1")]
public void Run([ServiceBusTrigger("topic-one", "sub-one", Connection = "ServiceBusConnString")]string mySbMsg)
{
var credentail = new DefaultAzureCredential();
_logger.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
}
This is how local.settings.json file look:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"ServiceBusConnString__serviceUri": "https://sb-test-three.servicebus.windows.net/",
"ServiceBusConnString__fullyQualifiedNamespace": "https://sb-test-three.servicebus.windows.net/",
"ServiceBusConnString": "https://sb-test-three.servicebus.windows.net/ManagedIdentity",
"ConnectionString": "https://sb-test-three.servicebus.windows.net/"
}
}
I am getting below error when running the app locally using Visual Studio.
How can I run Azure function from Visual Studio using managed identity? I am not sure how to use DefaultAzureCredential class

Looks like you only need ServiceBusConnString__fullyQualifiedNamespace for the managed identity and you can remove the below configs
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"ServiceBusConnString__serviceUri": "https://sb-test-three.servicebus.windows.net/",
"ConnectionString": "https://sb-test-three.servicebus.windows.net/"
You only need the below
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"ServiceBusConnString__fullyQualifiedNamespace": "sb-test-three.servicebus.windows.net",
And make sure you identity is having the below Roles
Azure Service Bus Data Receiver
Azure Service Bus Data Owner
Refer the official docs

Related

Why I am not seeing all properties available in local.settings.json file after deploying Azure function

I created an Azure function using Visual Studio. Local.setting.json file had following properties:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"ServiceBusConnString": "Endpoint=sb://sb-new-two.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=9FygKPHH2eJVp3GmAiUxtT7sGnddsaddadNIrciM0=",
"Test": "sb-new-two.servicebus.windows.net"
}
}
This is how my function looks:
[FunctionName("Function1")]
public void Run([ServiceBusTrigger("topic-one", "sub-one", Connection = "ServiceBusConnString")] string mySbMsg)
{
_logger.LogInformation("Processing message");
_logger.LogInformation($"Message : {mySbMsg}");
Console.WriteLine(mySbMsg);
}
After deploying the azure function, I do not see the test property. I am not using it in my code. But wondering why is this property missing?
Check in your .gitignore file if it includes the local.settings.json. Better yet add the value of your Test config manually in the Configuration section of your Azure function. Go to your function app in Azure, under Settings > Configuration > New Application setting, then add your Test config.
One of the workarounds to publish the app settings from local.settings.json to the Azure Portal Function App Configuration is:
Before publishing the function project to the Azure Portal, below is the configuration of my Function App:
Azure Functions Core Tools cmdlet:
func azure functionapp publish KrishSbFunApp01 --publish-local-settings -i
Before running this cmdlet, you have to change the value of AzureWebJobsStorage to the Azure Storage account connection string.
Also, you can overwrite the app settings by using the parameter --overwrite-settings -y, available in MS Doc Source.

Blob Storage based Azure Function Trigger is not working with Storage Explorer/Emulator

I need to write an azure function that compress any files uploaded in the azure blob storage.
With this Connection String
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;DefaultEndpointsProtocol=http;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
it throws the following error
[2022-05-26T21:44:56.133Z] An unhandled exception has occurred. Host is shutting down.
[2022-05-26T21:44:56.138Z] Azure.Storage.Blobs: The value for one of the HTTP headers is not in the correct format.
RequestId:4ddeb612-680e-40f0-8d62-ac754fe791e7
Time:2022-05-26T21:44:55.988Z
[2022-05-26T21:44:56.141Z] Status: 400 (The value for one of the HTTP headers is not in the correct format.)
It works fine with Azure Storage Account Connection string. What am I missing in the local emulator?
For the local emulator, you don't really require a "Connection String". You can set AzureWebJobsStorage to "UseDevelopmentStorage=true". Here is how my local.settings.json look like -
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
REFERENCES:
Use Azurite emulator for local Azure Storage development

C# Azure Functions project with ServiceBusTrigger connection issue

I have creating some Azure Functions in a C# project that are working fine locally. An example of the definition of a function is the following:
[FunctionName("createBankTransactionFromServiceBus")]
public async Task Run(
[ServiceBusTrigger("vspan.sbus.xerobanktransaction.requests", "requests",
Connection = "AccountingServiceBusConnection")] string myQueueItem)
{
}
Nothing different than usual. The problem is when I deploy this function on Azure. On Azure, the Azure Functions can't find the connection string. So, I added a new one in the local.settings.json but now I have two AccountingServiceBusConnection with the same value, one for my local machine and one for Azure.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"AccountingServiceBusConnection": "connectionString"
},
"AccountingServiceBusConnection": "connectionString"
}
I tried to replace the connection in the signature of the function like:
[FunctionName("createBankTransactionFromServiceBus")]
public async Task Run(
[ServiceBusTrigger("vspan.sbus.xerobanktransaction.requests", "requests",
Connection = "%Values:AccountingServiceBusConnection%")] string myQueueItem)
{
}
but locally I have a warning (with or without %).
Warning: Cannot find value named
'Values:AccountingServiceBusConnection' in local.settings.json that
matches 'connection' property set on 'serviceBusTrigger' in
'C:\Projects\fun\bin\Debug\netcoreapp3.1\createBankTransactionFromServiceBus\function.json'.
You can run 'func azure functionapp fetch-app-settings
' or specify a connection string in
local.settings.json.
Also, I tried to move AccountingServiceBusConnection under ConnectionStrings with the same result.
Update
Screenshot of Kudu and local.settings.json
Screenshot of Azure Functions configuration
How can you configure a pipeline in DevOps? How do you store the configuration from DevOps in the configuration in your Azure Functions?
There's no local.settings.json on Azure, you must add the settings to your Azure App Services settings:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings
EDIT:
for Key Vault Integration you must assign a managed identity to your function:
Then use Key Vault Ingegration:
#Microsoft.KeyVault(SecretUri={theSecretUri})
More info:
https://medium.com/statuscode/getting-key-vault-secrets-in-azure-functions-37620fd20a0b
By default, the local.settings.json file is NOT deployed with your code to an Azure Function. See the documentation here:
By default, these settings are not migrated automatically when the
project is published to Azure. Use the --publish-local-settings switch
when you publish to make sure these settings are added to the function
app in Azure. Note that values in ConnectionStrings are never
published.
You have a few options:
Explicitly publish your local.settings.json file with the aforementioned command line arg.
Add this setting (and any other settings needed) to your Azure Function's Configuration. Those values defined in your app settings in the Azure Portal take precedence over everything else.
I don't recommend option #1, because it requires you to place production values in your source code, which is in general a bad idea.
Updated - how to configure with Azure DevOps
For Azure DevOps, we've taken a two pronged approach.
We place the bare minimum key/value pairs in the Azure Function configuration. These are added into our yaml deployment pipeline. Some variable values (like connection strings) are read from other resources at deploy time so that sensitive info isn't included in our yaml script that is checked into revision control. Here's some example yaml for deploying an Azure Function:
{
"apiVersion": "2016-03-01",
"type": "Microsoft.Web/sites",
"name": "FooBarFunction",
"location": "[resourceGroup().location]",
"kind": "functionapp",
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms', "YourHostingPlanName")]"
],
"properties": {
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', "YourHostingPlanName)]",
"siteConfig": {
"appSettings": [
{
"name": "WEBSITE_CONTENTSHARE",
"value": "FooBarFunctionContentShare"
},
{
"name": "FUNCTIONS_WORKER_RUNTIME",
"value": "dotnet"
}
]
}
}
}
We use Azure App Configuration service to hold all of our other app settings. This gives us the advantage of defining different config profiles, and also having hot reload of our app settings without having to recycle the Azure Function. It also plays nicely with Keyvault for sensitive settings.

Azure Functions: Configuration file for referenced assembly

We have a referenced project in azure function app project. The referenced assembly is a data service project which is referred to by web api project too.
When referenced in web-api project the data service project automatically refers to web.config file for connection strings and app settings. While in azure functions app the data service project is not able to locate the connection strings stored in local.settings.json file.
How to address this issue locally?
How to address the issue in production?
NOTE: Would like to have DRY approach here.
As Jan V said, you could add a data connection string in json file. Besides, you could set a break point to see whether you get the 'str' value (Debug).
var str = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
Code in local.settings.jons file:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage":
"your storage account connection string",
"AzureWebJobsDashboard":
"your storage account connection string"
},
"ConnectionStrings": {
"ConnectionStringName": "Data Source=tcp:database server name,1433;Initial Catalog=database name;Integrated Security=False;User Id=user name;Password= your Password;Encrypt=True;TrustServerCertificate=False;MultipleActiveResultSets=True" // Refer to Azure portal>SQL database> connection string
}
}
For more details about how to use Azure Functions to connect to an Azure SQL Database ,you could read this article.

How to Access Emulated Azure storage on local PC

I am beginning development with Azure functions. Ive been able to connect to my actual azure Storage account Queue for testing how to program with Azure functions. Now my next step is to use the Microsoft Azure Storage Explorer to use the Local storage account so I do not have to be connected to azure. I saw how to do it in this article: https://learn.microsoft.com/en-us/azure/storage/storage-configure-connection-string#create-a-connection-string-to-the-storage-emulator
in the appsettings.json I changed my values to this exactly:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==",
"AzureWebJobsDashboard": "",
"StorageConnectionString": "UseDevelopmentStorage=true"
}
}
When i start up the Azure Fuctions CLI using Visual Studio i get this error message:
ScriptHost initialization failed Microsoft.WindowsAzure.Storage: The
remote server returned an error: (403) Forbidden.
Has anyone encountered this?
Please change the following line of code:
"AzureWebJobsStorage": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="
to either:
"AzureWebJobsStorage": "UseDevelopmentStorage=true"
or:
"AzureWebJobsStorage": "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;
AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;
BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;
TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;
QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;"
That should take care of 403 error.
Basically storage emulator has different endpoints than the cloud storage account. For example, the default blob endpoint for a cloud storage account is http://[youraccount].blob.core.windows.net while the blob endpoint for storage emulator is http://127.0.0.1:10000. When you just specify the storage account name and key for the storage emulator in your connection string, storage client library treats it like a cloud storage account and tries to connect to http://devstoreaccount1.blob.core.windows.net using the account key you provided. Since the key for devstoreaccount1 in the cloud is not the one you provided, you are getting 403 error.

Resources