Is it possible to create an azure function programmatically thru .NET and C# and creating through either Visual Studio UI nor Azure portal?

Swati Bhartiya 0 Reputation points Microsoft Employee
2024-11-12T22:03:33.2233333+00:00

I want to know if it is possible to create a new Azure function programmatically through C# code + .NET app.

Note: For my use case, I do not want to create the Azure function via

(1) Azure portal

(2) Using Visual Studio publish

This question is related to the following Learning Module

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,154 questions
Azure Training
Azure Training
Azure: A cloud computing platform and infrastructure for building, deploying and managing applications and services through a worldwide network of Microsoft-managed datacenters.Training: Instruction to develop new skills.
1,770 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Ryan Hill 28,731 Reputation points Microsoft Employee
    2024-11-13T02:10:14.3633333+00:00

    Hi @Swati Bhartiya

    If its from a deployment standpoint, you can use the Azure CLI or Azure Functions tools, i.e. az functionapp deploy or func azure functionapp publish <FunctionAppName>. These will create the resources for you.

    However, if you're talking about using a .NET app to create the resource(s), then you can use the Azure SDK to create the resource through say the ResourceManagementClientClass, see the docs for more info.

    Here's a sample program:

    using System;
    using System.Threading.Tasks;
    using Azure.Identity;
    using Azure.ResourceManager;
    using Azure.ResourceManager.AppService;
    using Azure.ResourceManager.Resources;
    
    namespace CreateFunctionApp
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                // Authenticate using DefaultAzureCredential
                var credential = new DefaultAzureCredential();
    
                // Create a management client
                var armClient = new ArmClient(credential);
    
                // Define the resource group and function app names
                string subscriptionId = "<your-subscription-id>";
                string resourceGroupName = "myResourceGroup";
                string functionAppName = "myFunctionApp";
    
                // Get the subscription
                var subscription = await armClient.GetSubscriptionAsync(subscriptionId);
    
                // Create or get the resource group
                var resourceGroup = await subscription.GetResourceGroups().CreateOrUpdateAsync(resourceGroupName, new ResourceGroupData("EastUS"));
    
                // Define the function app settings
                var functionAppData = new FunctionAppData("EastUS")
                {
                    ServerFarmId = "<your-app-service-plan-id>",
                    SiteConfig = new SiteConfig
                    {
                        AppSettings = new[]
                        {
                            new NameValuePair("AzureWebJobsStorage", "<your-storage-account-connection-string>"),
                            new NameValuePair("FUNCTIONS_EXTENSION_VERSION", "~4"),
                            new NameValuePair("WEBSITE_RUN_FROM_PACKAGE", "1")
                        }
                    }
                };
    
                // Create the function app
                var functionApp = await resourceGroup.GetFunctionApps().CreateOrUpdateAsync(functionAppName, functionAppData);
    
                Console.WriteLine($"Function App {functionAppName} created successfully.");
            }
        }
    }
    

  2. Khadeer Ali 1,130 Reputation points Microsoft Vendor
    2024-11-13T04:16:01.9966667+00:00

    Hi @Swati Bhartiya,

    Welcome to the Microsoft Q&A Platform!
    Thank you for reaching out regarding your question on creating an azure function programmatically without using Visual Studio UI nor Azure portal!

    Yes, it is possible to create an Azure Function programmatically using C# and .NET without using the Azure portal or Visual Studio UI. You can achieve this by using the Azure Functions Core Tools and the Azure SDK for .NET.

    1. Install the .NET SDK. I hope which you might have it already.
    2. Install the Azure Functions Core Tools:
      You can install the Azure Functions Core Tools using npm (Node.js package manager). If you don’t have Node.js installed, you can download it from the Node.js website.
      Once Node.js is installed, open a terminal or command prompt and run the following command:
      npm install -g azure-functions-core-tools@4 --unsafe-perm true
    3. Create a Local Function Project:
      Use the Azure Functions Core Tools to create a new function project.
         func init MyFunctionApp --worker-runtime dotnet-isolated --target-framework net8.0
         cd MyFunctionApp
      
    4. Create a new function within your project.

    func new --name MyHttpTrigger --template "HTTP trigger" --authlevel "anonymous"

    1. Implement your function logic in the generated MyHttpTrigger.cs file.
    2. Test your function locally using the Azure Functions Core Tools.
    func start
    

    Deploy the Function to Azure

    please refer the below reference on the same :

    https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-csharp?tabs=windows%2Cazure-cli

    If this answers your query, do click Accept Answer and Yes for was this answer helpful. And, if you have any further query do let us know.

    0 comments No comments

  3. Pinaki Ghatak 4,765 Reputation points Microsoft Employee
    2024-11-20T09:44:24.2833333+00:00

    Yes, it is possible to create an Azure Function programmatically through C# code + .NET app. You can use the Azure Management Libraries for .NET to create and manage Azure resources programmatically. Here's an example of how to create an Azure Function using C# code:

    using Microsoft.Azure.Management.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
    using Microsoft.Azure.Management.AppService.Fluent;
    using Microsoft.Azure.Management.AppService.Fluent.Models;
    
    var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
    var azure = Azure.Configure().Authenticate(credentials).WithDefaultSubscription();
    var resourceGroup = azure.ResourceGroups.Define("myResourceGroup")
    	.WithRegion(Region.USWest)
    	.Create(); 
    var appServicePlan = azure.AppServices.AppServicePlans
    	.Define("myAppServicePlan")
    	.WithRegion(Region.USWest)
    	.WithExistingResourceGroup(resourceGroup)
    	.WithPricingTier(PricingTier.BasicB1)
    	.Create(); 
    var functionApp = azure.AppServices.FunctionApps
    	.Define("myFunctionApp")
    	.WithRegion(Region.USWest)
    	.WithExistingResourceGroup(resourceGroup)
    	.WithExistingAppServicePlan(appServicePlan)
    	.WithRuntimeVersion("~3")
    	.Create(); 
    
    var storageAccount = azure.StorageAccounts
    	.Define("myStorageAccount")
    	.WithRegion(Region.USWest)
    	.WithExistingResourceGroup(resourceGroup)
    	.Create(); 
    
    //Apply
    functionApp.Update()
    	.WithAppSetting("AzureWebJobsStorage", $"DefaultEndpointsProtocol=https;AccountName={storageAccount.Name};AccountKey={storageAccount.GetKeys().First().Value};EndpointSuffix=core.windows.net")
    	.Apply();
    

    This code creates a new resource group, app service plan, function app, and storage account in the US West region, and then sets the AzureWebJobsStorage app setting for the function app to use the newly created storage account. You can modify this code to suit your specific needs.


    I hope that this response has addressed your query and helped you overcome your challenges. If so, please mark this response as Answered. This will not only acknowledge our efforts, but also assist other community members who may be looking for similar solutions.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.