This script is written in PowerShell and is used for managing Azure resources. It's designed to automate the process of creating an application registration in Azure Active Directory, granting it permissions to a Key Vault in Azure, and handling various checks and error scenarios along the way. Here's a breakdown:
-
Setting up Parameters and Preferences:
- It starts by defining mandatory parameters that need to be passed when the script is called:
$AppClientDisplayName
,$KeyVaultName
, and$ResourceGroupName
. $ErrorActionPreference = "Stop"
: This line sets the preference for how to handle errors in the script. "Stop" means that the script will stop executing as soon as there's an error.
- It starts by defining mandatory parameters that need to be passed when the script is called:
-
Checking Resource Group Existence:
- The script checks if the specified Azure Resource Group exists. If it doesn't, the script throws an error and stops execution.
-
Checking for Existing Application and Key Vault:
- It checks whether an Azure AD application with the specified display name already exists.
- It verifies if the specified Key Vault exists within the given resource group.
- If the application already exists, or if the Key Vault doesn't exist, an error is thrown, stopping the script.
-
Creating Application and Service Principal:
- If the application doesn't exist, it creates a new application in Azure AD with the provided display name.
- It creates a new service principal for the application. This is an identity for the application to be used in Azure.
- It creates a new secret (password) for the application and sets it to expire in one year.
-
Handling Key Vault Permissions:
-
The script checks if the Key Vault uses RBAC (Role-Based Access Control) or access policies for permissions.
-
If RBAC is used:
- A custom role is created for the Key Vault with the following permissions:
- Actions:
write
andread
access to secrets in the Key Vault.
- Data Actions:
- Permissions to
delete
,purge
,update
,get
,set
secrets, andread
their metadata.
- Permissions to
- This role is then assigned to the application at the scope of the specified Key Vault.
- Actions:
- A custom role is created for the Key Vault with the following permissions:
-
If access policies are used:
- The script retrieves the service principal of the newly created application.
- It sets a new access policy for the Key Vault granting the application permissions to
get
,set
,list
,delete
, andpurge
secrets.
-
-
Outputting Results:
- If the secret (password) for the app was created successfully, the script prints a success message along with the application's client ID and the new secret.
The role that's being created in Azure (when RBAC is used) is a custom role specifically for managing secrets within a specific Key Vault. The permissions associated with this role allow the application to read, write, delete, and perform other operations related to secrets stored in the Azure Key Vault.