|
| 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 | + console.log(`Creating service principal for AAD application with ID: ${appId}`); |
| 15 | + |
| 16 | + try { |
| 17 | + // Check if Azure CLI is installed and logged in |
| 18 | + await execPromise('az account show'); |
| 19 | + |
| 20 | + // Check if service principal already exists |
| 21 | + const checkCmd = `az ad sp list --filter "appId eq '${appId}'"`; |
| 22 | + const { stdout } = await execPromise(checkCmd); |
| 23 | + |
| 24 | + const existingSpList = JSON.parse(stdout); |
| 25 | + if (existingSpList && existingSpList.length > 0) { |
| 26 | + console.log(`Service principal for application ID ${appId} already exists. Skipping creation.`); |
| 27 | + process.exit(0); |
| 28 | + } |
| 29 | + |
| 30 | + // Create service principal |
| 31 | + const createCmd = `az ad sp create --id "${appId}"`; |
| 32 | + await execPromise(createCmd); |
| 33 | + |
| 34 | + console.log('Service principal created successfully.'); |
| 35 | + } catch (error) { |
| 36 | + console.error('Error:', error.message); |
| 37 | + if (error.message.includes('az: not found') || error.message.includes('not recognized as an internal or external command')) { |
| 38 | + console.error('Azure CLI is not installed or not in PATH. Please install it first.'); |
| 39 | + } else if (error.message.includes('Please run az login')) { |
| 40 | + console.error('You are not logged into Azure. Please run az login first.'); |
| 41 | + } else { |
| 42 | + console.error('Failed to create service principal. Please ensure you have the right permissions.'); |
| 43 | + } |
| 44 | + process.exit(1); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +createServicePrincipal(); |
0 commit comments