@Amit Singh Rawat Welcome to Microsoft Q&A Forum, Thank you for posting your query here!
I see that you are looking to create an Azure Function App programmatically via C# and .NET6. You have already published the Azure Function code via Visual Studio 2022 and want to replicate the same process as clicking the "Publish" button in Visual Studio for Azure, but through C# code.
The below code does the following:
- Create a resource group (if it doesn't exist)
- Create storage account required for func app if it doesnt exist
- Create a function app in azure
- Deploy the code to azure function app
Pre-Requisites:
- Read and understand the code.
- Read the comments carefully and uncomment the required lines.
- Ensure that the required packages are installed via nuget
- Create the Azure AD app and get the ClienTID, tennatID and Client Secret required for the app to run.
- Ensure that this Azure AD app has privileges to create a resource in the subscription ( Atleast Contributor role in your subscription)
Please Note: You need to update the below code and test it in a dev environment. Please don't copy / paste the code directly and execute, as it might not work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.Core;
using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Resources.Models;
using System.Security.Policy;
using Microsoft.Azure.Management.AppService.Fluent.Models;
using Microsoft.Azure.Management.Storage.Fluent.Models;
using Microsoft.Azure.Management.AppService.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using System.Net.Http.Headers;
using System.Net.Http;
using System.IO;
namespace FunctionAppCreate
{
internal class Program
{
public static async Task Main(string[] args)
{
var ClientId = "ad8a06b6-XXXXXXXXXX-28fd86b57777";
var ClientSecret = "5dY8Q~pPmXXXXXXXXXXXXXXXXXXkhS5aJo";
var TenantId = "72f988bf-XXXXXXXXXXXX-2d7cd011db47";
var credential = new DefaultAzureCredential();
// var resourceClient = new ResourceManagementClient(credential);
//var resourceGroupName = "myResourceGroup";
var functionAppName = "myFunctionApp";
var subscriptionId = "b83c1ed3-XXXXXXXXXXX-2b83a074c23f";
var storageAccountName = "StorageAccountName";
string resourceGroupName = "myRgName";
var region = "eastus";
var storageConnectionString = " ";
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(ClientId, ClientSecret, TenantId, AzureEnvironment.AzureGlobalCloud);
//UNCOMMENT THE BELOW LINES IF YOU WANT TO CREATE A NEW RESOURCE GROUP
//ArmClient client = new ArmClient(new DefaultAzureCredential());
//// Now we get a ResourceGroupResource collection for that subscription
//SubscriptionResource subscription = await client.GetDefaultSubscriptionAsync();
//ResourceGroupCollection resourceGroups = subscription.GetResourceGroups();
//// With the collection, we can create a new resource group with an specific name
//AzureLocation location = AzureLocation.WestUS2;
//ResourceGroupData resourceGroupData = new ResourceGroupData(location);
//ArmOperation<ResourceGroupResource> operation = await resourceGroups.CreateOrUpdateAsync(WaitUntil.Completed, resourceGroupName, resourceGroupData);
//var resourceGroup = operation.Value;
var azure = Microsoft.Azure.Management.Fluent.Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// UNCOMMENT THE BELOW LINES IF YOU WANT TO CREATE A NEW STORAGE ACCOUNT
//var storageAccount = await azure.StorageAccounts.Define(storageAccountName)
// .WithRegion(Region.USEast)
//.WithNewResourceGroup(resourceGroupName)
// .CreateAsync();
//// Uncomment the below to get the storage connection string
//var storageAccount = azure.StorageAccounts.GetByResourceGroup(resourceGroupName, storageAccountName);
//var storageKeys = storageAccount.GetKeys();
// storageConnectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageKeys[0].Value};EndpointSuffix=core.windows.net";
// The below code will create a new function app with new storage account and resource group.
IFunctionApp funcapp = azure.AppServices.FunctionApps.Define(functionAppName)
.WithRegion(region)
.WithNewResourceGroup(resourceGroupName)
.WithLocalGitSourceControl()
.Create();
// Deploy the code to newly created funcapp through web deploy.
//Ensure that you have zipped up your entire code and placed it in git or any other location
Console.WriteLine("Deploying a local function app to " + funcapp + " throuh web deploy...");
funcapp.Deploy()
.WithPackageUri("https://github.com/Azure/azure-libraries-for-net/raw/master/Samples/Asset/square-function-app-function-auth.zip")
.WithExistingDeploymentsDeleted(false)
.Execute();
Console.WriteLine("Deployment to function app " + funcapp.Name + " completed");
// Alternatively if you want to deploy using the zip deployment method directly by invoking the REST API
//Uncomment the below code:
//var deploymentUser = "";
//var zipFilePath = "";
//var appName = funcapp.Name;
//var client = new HttpClient();
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{deploymentUser}:")));
//var content = new StreamContent(File.OpenRead(zipFilePath));
//content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
//var response = await client.PostAsync($"https://{appName}.scm.azurewebsites.net/api/zipdeploy", content);
//if (response.IsSuccessStatusCode)
//{
// Console.WriteLine("Deployment successful.");
//}
//else
//{
// Console.WriteLine($"Deployment failed with status code {response.StatusCode}.");
//}
Console.ReadLine();
// If you want to delete the entire resource group you can uncomment the below
// azure.ResourceGroups.DeleteByName(resourceGroupName);
// Console.WriteLine("RG Deleted successfully.");
}
}
}
Hope this helps.
**
Please do not forget to "Accept the answer” and “up-vote” wherever the information provided helps you, this can be beneficial to other community members.