I'm trying to pull some secrets from an Azure KeyVault for a project involving machine offboarding via Intune. My architect suggested using Azure KeyVault to fetch credentials instead of hardcoding them, which sounds logical to me, but I'm still new to this. While testing my script based on Microsoft's documentation, I'm not getting any output, which makes me think I've messed up somewhere in the access logic. The goal here is to connect using managed identity, but I'm getting a login error when running my script, specifically: "No Azure login detected. Please run 'Connect-AzAccount' to log in." I would appreciate any advice on how to fix this issue or point me in the right direction. Here's the relevant snippet of my script:
```powershell
# OFFBOARDING SCRIPT FOR REMOVING DEVICES NO LONGER OWNED
$ErrorActionPreference = "SilentlyContinue"
# Phase 0: Install required Modules and configure access
Install-Module Az -Force
$tenantId = "tenant-id-guid"
$appId = "client-id-of-managed-identity"
$keyVaultName = "KEYVAULT-NAME"
$resourceGroup = "RESOURCE-GROUP-NAME"
$resourceName = "name-of-managed-identity"
$subId = "subscription-id-that-is-parent-of-resource-group"
Select-AzSubscription -SubscriptionId "$subId"
$identity = Get-AzUserAssignedIdentity -ResourceGroupName "$resourceGroup" -Name "$resourceName"
Connect-AzAccount -Identity -AccountId $identity.ClientId
$keyVault = Get-AzKeyVault -VaultName "$keyVaultName" -ResourceGroupName "$resourceGroup"
if (-not $keyVault) {
Write-Host "Key Vault '$keyVaultName' not found in resource group '$resourceGroup'."
exit
}
# Attempt to retrieve secret
$secret_mut = Get-AzKeyVaultSecret -VaultName $keyVault.VaultName -Name "M-uninstallToken"
```
Any insights would be super helpful!
3 Answers
Consider using a service principal with certificate authentication to connect. Here's an example to connect:
```powershell
Connect-AzAccount -Tenant 'REDACTED' -ApplicationId 'REDACTED' -CertificateThumbprint 'REDACTED' -ServicePrincipal | Out-Null
```
This might solve your connection issue without needing the manual account log-in.
It looks like you're missing the `-AsPlainText` parameter in your `Get-AzKeyVaultSecret` command. Adding that should make your retrieval work better! Give this a try:
```powershell
$secret_mut = Get-AzKeyVaultSecret -VaultName $keyVault.VaultName -Name "M-uninstallToken" -AsPlainText
```
You really need to run `Connect-AzAccount` at the start of your script. Syntax can be tricky when working with managed identities, so double-check your login command. If you run into issues, share your updated code here and we can debug together!
Can `Connect-AzAccount` even be used with a managed identity? I'm trying the approach from CodeMaster99 for now.
Thanks for the suggestion, I'll give that a shot and update on my progress!