import { ResourceManagementClient } from "@azure/arm-resources" ; import { loginWithServicePrincipalSecret } from "@azure/ms-rest-nodeauth" ; import { logger } from "../../logger" ; let client ; export interface ResourceGroupItem { id : string ; name : string ; location : string ; } param servicePrincipalId param servicePrincipalPassword param servicePrincipalTenantId param subscriptionId const getClient = async ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId , subscriptionId ) : Promise < ResourceManagementClient > => { if ( client ) { return client ; } const creds = await loginWithServicePrincipalSecret ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId ) ; client = new ResourceManagementClient ( creds , subscriptionId , { } ) ; return client ; } ; param servicePrincipalId param servicePrincipalPassword param servicePrincipalTenantId param subscriptionId export const getResourceGroups = async ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId , subscriptionId ) : Promise < ResourceGroupItem [ ] > => { logger . info ( "attempting to get resource groups" ) ; await getClient ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId , subscriptionId ) ; const groups = await client . resourceGroups . list ( ) ; logger . info ( "Successfully acquired resource groups" ) ; return groups . map ( ( g ) => { return { id : g . id as string , location : g . location as string , name : g . name as string , } ; } ) ; } ; param servicePrincipalId param servicePrincipalPassword param servicePrincipalTenantId param subscriptionId param name export const isExist = async ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId , subscriptionId , name ) : Promise < boolean > => { const groups = await getResourceGroups ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId , subscriptionId ) ; return ( groups || [ ] ) . some ( ( g ) => g . name === name ) ; } ; param servicePrincipalId param servicePrincipalPassword param servicePrincipalTenantId param subscriptionId param name param location export const create = async ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId , subscriptionId , name , location ) : Promise < boolean > => { logger . info ( `attempting to create resource group ${ name }` ) ; const exist = await isExist ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId , subscriptionId , name ) ; if ( exist ) { logger . info ( `Resource group ${ name } already existed` ) ; return false ; } await getClient ( servicePrincipalId , servicePrincipalPassword , servicePrincipalTenantId , subscriptionId ) ; await client . resourceGroups . createOrUpdate ( name , { location , } ) ; logger . info ( `Successfully create resource group ${ name }.` ) ; return true ; } ;