|  | 
|  | 1 | +// Script to create a service principal for the Microsoft Entra application | 
|  | 2 | +const { exec } = require('child_process'); | 
|  | 3 | +const util = require('util'); | 
|  | 4 | +const execPromise = util.promisify(exec); | 
|  | 5 | + | 
|  | 6 | +async function createServicePrincipal() { | 
|  | 7 | +  const appId = process.env.BOT_ID; | 
|  | 8 | +   | 
|  | 9 | +  if (!appId) { | 
|  | 10 | +    console.error('Error: BOT_ID environment variable is not set'); | 
|  | 11 | +    process.exit(1); | 
|  | 12 | +  } | 
|  | 13 | +   | 
|  | 14 | +  try { | 
|  | 15 | +    // Check if Azure CLI is installed and logged in | 
|  | 16 | +    await execPromise('az account show'); | 
|  | 17 | +     | 
|  | 18 | +    // Check if service principal already exists | 
|  | 19 | +    const checkCmd = `az ad sp list --filter "appId eq '${appId}'"`; | 
|  | 20 | +    const { stdout } = await execPromise(checkCmd); | 
|  | 21 | +     | 
|  | 22 | +    const existingSpList = JSON.parse(stdout); | 
|  | 23 | +    if (existingSpList && existingSpList.length > 0) { | 
|  | 24 | +      console.log(`Service principal for application ID ${appId} already exists. Skipping creation.`); | 
|  | 25 | +      process.exit(0); | 
|  | 26 | +    } | 
|  | 27 | +     | 
|  | 28 | +    // Create service principal | 
|  | 29 | +    const createCmd = `az ad sp create --id "${appId}"`; | 
|  | 30 | +    await execPromise(createCmd); | 
|  | 31 | +     | 
|  | 32 | +    console.log('Service principal created successfully.'); | 
|  | 33 | +  } catch (error) { | 
|  | 34 | +    console.error('Error:', error.message); | 
|  | 35 | +    if (error.message.includes('az: not found') || error.message.includes('not recognized as an internal or external command')) { | 
|  | 36 | +      console.error('Azure CLI is not installed or not in PATH. Please install it first.'); | 
|  | 37 | +    } else if (error.message.includes('Please run az login')) { | 
|  | 38 | +      console.error('You are not logged into Azure. Please run az login first.'); | 
|  | 39 | +    } else { | 
|  | 40 | +      console.error('Failed to create service principal. Please ensure you have the right permissions.'); | 
|  | 41 | +    } | 
|  | 42 | +    process.exit(1); | 
|  | 43 | +  } | 
|  | 44 | +} | 
|  | 45 | + | 
|  | 46 | +createServicePrincipal(); | 
0 commit comments