skip to Main Content

azure functions created in one cloud location for example south India should be able to create resource group in location central US

I want a clear step by step approach if this is possible.

const { ResourceManagementClient } = require("@azure/arm-resources");

module.exports = async function (context, req) {
    const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"];
    const credentials = new DefaultAzureCredential();
    const resourceClient = new ResourceManagementClient(credentials, subscriptionId);

    const resourceGroupName = "demoDiffResourceGroup";
    const resourceGroupParameters = {
        location: "centralus"
    };

    context.log(`Creating resource group: ${resourceGroupName} in Central US`);

    try {
        const result = await resourceClient.resourceGroups.createOrUpdate(resourceGroupName, resourceGroupParameters);
        context.res = {
            body: `Resource group created successfully: ${result.name}`
        };
    } catch (err) {
        context.res = {
            status: 500,
            body: `Error creating resource group: ${err.message}`
        };
    }
};

2

Answers


  1. Chosen as BEST ANSWER

    This can be done by

    1. In azure portal, create new Function app example in location central us
    2. In the function app settings turn turn on the system-assigned managed identity.
    3. Assign the managed identity the role of 'Contributor' or a custom role with necessary permissions on the subscription or resource group where you want to create resources.

    In my case, my function app is in location south India which should be able to create resource group to a different location After setting up permissions you can trigger the following code will directly create resource group in a different location from a function which is in other location, use the code snippet:

    const { ResourceManagementClient } = require("@azure/arm-resources");
    
    module.exports = async function (context, req) {
        context.log('JavaScript HTTP trigger function processed a request.');
       const subscriptionId = <subscriptionIdOfFunctionApp;
        const resourceGroupName = <resourceGroupName;
        const location = <location>;
    
       if (req.body.resourceGroupName && req.body.location) {
           const { resourceGroupName, location } = req.body;
       }
        else{
            context.res = {
                status: 400,
                body: "Please pass a resourceGroupName on the query string or in the request body"
            };
            return;
        }
    
        try {
            const credentials = new DefaultAzureCredential();
            console.log(credentials)
            const client = new ResourceManagementClient(credentials, subscriptionId);
            console.log(client)
            const result = await client.resourceGroups.createOrUpdate(resourceGroupName, {
                location: location
            });
    
            context.res = {
                status: 200,
                body: `Resource group '${resourceGroupName}' created in '${location}'`
            };
        } catch (error) {
            context.log.error("Error creating resource group:", error);
            context.res = {
                status: 500,
                body: "Error creating resource group"
            };
        }
    };
    

  2. I have used below code to create Resource group and Function App in different regions:

    Resource group location: Central US
    Function App location: South India
    

    Code Snippet:

    • createResourceGroup function creates a resource group in the specified region.
    • createFunctionApp function creates an App Service Plan in the defined region and then creates a Function App in the same region.
    • Orchestrating the creation of both the resource group and the function app in the main function.
    const { DefaultAzureCredential } = require('@azure/identity');
    const { ResourceManagementClient } = require('@azure/arm-resources');
    const { WebSiteManagementClient } = require('@azure/arm-appservice');
    
    const subscriptionId = "<Subscription_id>";
    const resourceGroupName = "kprg";
    const functionAppName = 'kpfnode';
    const resourceGroupLocation = 'CentralUS';
    const functionAppLocation = 'southindia';
    
    const credential = new DefaultAzureCredential();
    
    const resourceClient = new ResourceManagementClient(credential, subscriptionId);
    const webSiteClient = new WebSiteManagementClient(credential, subscriptionId);
    
    // Creation of Resource group in Central US region
    
    async function createResourceGroup() {
        const resourceGroupParams = { location: resourceGroupLocation };
        console.log(`Creating resource group: ${resourceGroupName}`);
        const resourceGroup = await resourceClient.resourceGroups.createOrUpdate(resourceGroupName, resourceGroupParams);
        console.log(`Resource group created: ${resourceGroup.name}`);
    }
    
    // Creation of App Service Plan
    async function createAppServicePlan() {
      const appServicePlanName = `${functionAppName}Plan`;
      const appServicePlanParams = {
          location: functionAppLocation,
          sku: {
              name: 'Y1',
              tier: 'Dynamic',
              size: 'Y1',
              family: 'Y',
              capacity: 0,
          },
      };
      
      console.log(`Creating App Service Plan: ${appServicePlanName}`);
      const appServicePlan = await webSiteClient.appServicePlans.beginCreateOrUpdateAndWait(resourceGroupName, appServicePlanName, appServicePlanParams);
      console.log(`App Service Plan created: ${appServicePlan.name}`);
    }
    
    // Creation of functionapp in South India region
    
    async function createFunctionApp() {
      const siteParams = {
          location: functionAppLocation,
          serverFarmId: `/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.Web/serverfarms/${functionAppName}Plan`,
          siteConfig: {
              appSettings: [
                  {
                      name: 'FUNCTIONS_EXTENSION_VERSION',
                      value: '~3'
                  },
                  {
                      name: 'WEBSITE_NODE_DEFAULT_VERSION',
                      value: '14'
                  },
              ],
          },
          kind: 'functionapp',
      };
    
      console.log(`Creating Function App: ${functionAppName}`);
      const functionApp = await webSiteClient.webApps.beginCreateOrUpdateAndWait(resourceGroupName, functionAppName, siteParams);
      console.log(`Function App created: ${functionApp.name}`);
    }
    
    async function main() {
      try {
          await createResourceGroup();
          await createAppServicePlan();
          await createFunctionApp();
      } catch (err) {
          console.error('Error creating resources:', err);
      }
    }
    
    main();
    

    Console response:

    C:Usersunamenodeapp> node app.js
    Creating resource group: kprg
    Resource group created: kprg
    Creating App Service Plan: kpfnodePlan
    App Service Plan created: kpfnodePlan
    Creating Function App: kpfnode
    Function App created: kpfnode
    

    Update:

    • Use the below updated NodeJs code to achieve your requirement.
    const { DefaultAzureCredential } = require("@azure/identity");
    const { ResourceManagementClient } = require("@azure/arm-resources");
    
    module.exports = async function (context, req) {
      
        const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"];
        const resourceGroupName = "myResourceGroup";
        const location = "centralus";
    
        // Authenticate with Azure
        const credential = new DefaultAzureCredential();
        const client = new ResourceManagementClient(credential, subscriptionId);
    
        try {
            // Creation of resource group
            const result = await client.resourceGroups.createOrUpdate(resourceGroupName, {
                location: location
            });
            context.res = {
                status: 200,
                body: `Resource group created successfully: ${result.id}`
            };
        } catch (error) {
            context.res = {
                status: 500,
                body: `Error creating resource group: ${error.message}`
            };
        }
    };
    
    

    Resource group got created in Central US region:

    enter image description here

    Function App got created in South India region:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search