Creating KeyVault in Azure with no user - azure

Is there a way in Azure to create keyvault without any user? I am trying to follow the documentation but dont see any command that will achieve this in one line?
New-AzureRmKeyVault -VaultName my-test -ResourceGroupName abc -Location "Brazil South"
Any powershell command I can add above to not create any access policy or principal user?

You can use a template to create a vault with no access policy - see: https://github.com/Azure/azure-quickstart-templates/blob/master/101-key-vault-create/azuredeploy.json and just remove this: https://github.com/Azure/azure-quickstart-templates/blob/master/101-key-vault-create/azuredeploy.json#L105-L114
You can deploy that with PowerShell using New-AzureRMResourceGroupDeployment.

The New-AzureRmKeyVault create keyvault with access policy by default, if you want to achieve this in one line, you could use powershell pipeline, try the command below, it works fine on my side.
New-AzureRmKeyVault -VaultName '<VaultName>' -ResourceGroupName '<ResourceGroupName>' -Location 'East US' | Remove-AzureRmKeyVaultAccessPolicy -ObjectId "<ObjectId of your signin user or service principal>"
Update:
I suppose you create the keyvault via a user account, you could get the ObjectId via Get-AzureRmADUser,-UserPrincipalName is your account.
Complete command:
$ObjectId = (Get-AzureRmADUser -UserPrincipalName "xxxx#xxxx.com").Id
New-AzureRmKeyVault -VaultName '<VaultName>' -ResourceGroupName '<ResourceGroupName>' -Location 'East US' | Remove-AzureRmKeyVaultAccessPolicy -ObjectId $ObjectId

Related

Creating Azure Storage account from PowerShell giving error

I have Azure subscription where I am the owner of it. So, I have access to manage all resources.
I successfully login to Azure Account from PowerShell using command Connect-AzAccount
Now, I am trying to create a storage account using script like below:
New-AzStorageAccount -ResourceGroupName $resourceGroupName -Name
$my_storage_Acc -Location $location -SkuName Standard_LRS
But after executing the above command, I am getting the error like this:
The client with my_object_id does not have authorization to perform
action over scope(code:Authorization Failed)
Can anyone help me why I'm getting this error though I've owner role for subscription and how to get rid of that error?
As per the error, it said that you don't have enough permission to do this action. It's an authorization issue. But you said that you are the owner of this subscription. I have a question, what have you declared in the my_object_id?
To create Azure Storage Account you can use this script.
# Variables
$ResourceGroup="MyResourceGroup007"
$StorageName="webappstorage007"
$Location="West US"
# Create a Resource Group
New-AzResourceGroup -Name $ResourceGroup -Location $Location
# Create Storage Account
New-AzStorageAccount -Name $StorageName -ResourceGroupName $ResourceGroup -Location $Location -SkuName Standard_LRS
This script can create a storage account successfully. Check the following Screenshot.

Is there any Poweshell Script or az command to get the list of Products and its Subscription IDs for API Management?

We are using the Azure API Management Product subscription id in our Front End applications and there is no track on which frontend application is using which id as the product is having multiple subscription id and the one API has multiple products attached to it.
Sometimes we need to add the header policies where the front-end developer will give us the subscription id they are using and it becomes difficult to check in the portal UI to get the name of the product from the subscription id.
Looking for a Powershell script or az command which can give the list of products with subscription id so that it will be easy and useful.
Thanks
List products: https://learn.microsoft.com/en-us/powershell/module/az.apimanagement/get-azapimanagementproduct?view=azps-5.5.0
List subscriptions: https://learn.microsoft.com/en-us/powershell/module/az.apimanagement/get-azapimanagementsubscription?view=azps-5.5.0
Get subscription key: https://learn.microsoft.com/en-us/powershell/module/az.apimanagement/get-azapimanagementsubscriptionkey?view=azps-5.5.0
APIM az reference: https://learn.microsoft.com/en-us/cli/azure/apim?view=azure-cli-latest
I do it like this. Unfortunately, I don't know yet how to extract the secret keys of the apim subscriptions, which do not appear here:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force
Connect-AzAccount
Select-AzSubscription -SubscriptionName 'my-playground'
$apimContext = New-AzApiManagementContext -ResourceGroupName "my-
playground" -ServiceName "my-apim-playground"
Get-AzApiManagementSubscription -Context $apimContext | Format-Table -
Property Name, SubscriptionId

Assign Key Vault Secrets to an Azure Function using Azure PowerShell

I am trying to automate the creation of certain azure resources via an Azure PowerShell script that is triggered from an Azure DevOps release pipeline. I want to create a function app, and automatically integrate reading right access to secrets in an already existing Key Vault. This Key Vault is in the same Azure subscription.
While I can create most resources following the documentation, there seems to be a lack of documentation regarding the creation of certain resources using Azure PowerShell (or I can't find it).
If I follow the sample from this link, I can accomplish it without a problem by using the UI in the Azure Portal, but I can't find any documentation on Microsoft Docs to do it using PowerShell.
Write-Host "Creating Function App..."
$fnApp = New-AzFunctionApp -Name $functionAppName `
-ResourceGroupName $emailFunctionRg `
-Location "$(AzureRegion)" `
-StorageAccount $storageName `
-Runtime dotnet `
-FunctionsVersion '3' `
-IdentityType SystemAssigned
Write-Host "Function App created!"
Write-Host "Assigning Key Vault access..."
$appId = Get-AzADServicePrincipal -DisplayName $functionAppName
Set-AzKeyVaultAccessPolicy -VaultName EmailSettings -ServicePrincipalName $appId -PermissionsToSecrets Get,List
Write-Host "Key Vault access granted!"
Running Set-AzKeyVaultAccessPolicy fails with "Insufficient privileges to complete the operation.". But I am not sure if this is the right path to follow, it was just a guess, based on the available functions in the documentation.
Any ideas?
Two potential issues to check out here:
your app creation assigns the result to $fnApp. perhaps $fnApp or as commented above, $fnApp.ApplicationId is what you should be using for the -ServicePrincipalName parameter on the access policy grant.
you don't have privileges to assign RBAC roles. Go to the Key Vault, choose Access Control, then click the Role Assignments tab and verify that your user appears in the list as an Administrator, User Access Administrator, or Owner.
Edit: With respect to the RBAC privilege, since this is running in Azure Powershell from Azure DevOps, you need to check the role assignment for the Service Connection's service principal - under Azure Active Directory in the Azure Portal, look up the principal used to create the service connection, and make sure THAT gets the correct Role on the key vault.
After a little of trial and error I just came to the conclusion I was not using the right parameter for the Set-AzKeyVaultAccessPolicy cmdlet.
The following script will work (if the service principle running it has the appropriate role, like WaitingForGuacamole mentioned in his/her answer):
Write-Host "Creating Function App..."
$fnApp = New-AzFunctionApp -Name <FnAppName> `
-ResourceGroupName <ResourceGroupName> `
-Location <AzureRegion> `
-StorageAccount <StorageAccount> `
-Runtime dotnet `
-FunctionsVersion '3' `
-IdentityType SystemAssigned
Write-Host "Function App created!"
Write-Host "Assigning Key Vault access..."
Set-AzKeyVaultAccessPolicy -VaultName <NameOfTheKeyVault> -ObjectId (Get-AzADServicePrincipal -DisplayName <FnAppName>).Id -PermissionsToSecrets <Get, List, etc...>
Write-Host "Key Vault access granted!"

Moving secret between azure key vaults from different subscription using DevOps

I have 2 different subscriptions (Dev & Prod) and each subscription we are using separate key vault. So, for Dev- keyvault: az-kv-dev & for Prod- keyvault: az-kv-prod.
Now, we want to read the secrets from Dev and needs to write all to Prod key vault using Azure DevOps release pipeline. Please note, we do not hard-code the password inside devops.
Is there any way to do that?
I'm not familiar with DevOps. But It seems you could move the key vault(az-kv-dev) to Prod subscription first, then copy all secrets to az-kv-prod.
Moving Key Vault to a new subscription:
If the two subscriptions are in the same tenant, you could move just in the portal. Navigate to your key vault -> Overview -> "Move" button. If you move key vault to a subscription in a new tenant, you could use Powershell.
Select-AzSubscription -SubscriptionId <your-subscriptionId>
$vaultResourceId = (Get-AzKeyVault -VaultName myvault).ResourceId
$vault = Get-AzResource –ResourceId $vaultResourceId -ExpandProperties
$vault.Properties.TenantId = (Get-AzContext).Tenant.TenantId
$vault.Properties.AccessPolicies = #()
Set-AzResource -ResourceId $vaultResourceId -Properties $vault.Properties
Clear-AzContext
Connect-AzAccount
Copy all secrets from new-az-kv-dev to az-kv-prod:
Param(
[Parameter(Mandatory)]
[string]$sourceVaultName,
[Parameter(Mandatory)]
[string]$destVaultName
)
$secretNames = (Get-AzKeyVaultSecret -VaultName $sourceVaultName).Name
$secretNames.foreach{
Set-AzKeyVaultSecret -VaultName $destVaultName -Name $_ `
-SecretValue (Get-AzKeyVaultSecret -VaultName $sourceVaultName -Name $_).SecretValue
}
For more details about moving to another subscription, see here.

Azure storage account key updation using RM module

I am trying to setup a powershell code which would update the storage account credentials every once in a while and below is the script that I have come across and it works perfectly fine.
function setupContext(){
Add-AzureRmAccount
Save-AzureRmContext -Path “path\to\json\file”
}
#setupContext
Import-AzureRmContext -Path “path\to\json\file”
$subscriptionId='***********************************'
Select-AzureRMSubscription -SubscriptionId $subscriptionId -WarningAction SilentlyContinue
$resourceGroup="**************"
$storageAccountName="******************"
$BLOBKey= New-AzureRmStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName -KeyName key2
Write-Host "BLOB Key:"$BLOBKey.Keys[0]
The above code does the required work, however it requires us to login to the azure-rm account which basically defeats the idea of automating this process since I would need keep updating this generated profile.
Note: I am not allowed to use az module as of now since the environment in which I work has some .NET version limitations.
So if there any other solution which could overcome the azure rm login issue, please suggest.
Use Azure Automation. This automatically sets up something called RunAs account. Which simply said is just Azure AD Service Principal.
Then assign this principal privileges on the storage account just like any other user and you are done.
And in the Automation Runbook do
$connection = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzureRmAccount `
-ServicePrincipal `
-Tenant $connection.TenantID `
-ApplicationID $connection.ApplicationID `
-CertificateThumbprint $connection.CertificateThumbprint
$AzureContext = Select-AzureRmSubscription -SubscriptionId $connection.SubscriptionID
... run rest of the code ...
If you want to run this from outside of Azure like on-prem server then set up manually service principal. Here is guide
https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal
And just log into this app from powershell instead of the user.
Looks you want to use a non-interactive way to do that automatically. To access the azure resource with a non-interactive way, your best option currently is to use the service principal(AD App).
An Azure service principal is an identity created for use with applications, hosted services, and automated tools to access Azure resources.
The other reply is for azure automation runbook, you could follow my steps to automate it in other places else.
1.Create an Azure Active Directory application and create a secret for the app, save the secret and get values for signing in.
2.Navigate to the storage account(or the subscription which the storage account located) in the portal -> Access control (IAM) -> Add -> Add role assignment -> search your service principal(AD App) with name and add it as a role(e.g. Owner/Contributor) -> Save.
Note: To give the role, you need to use an account which is an Owner of the specific scope(storage account/subscription).
3.Then use the script as below, replace the specific properties with the values in step 1.
function setupContext(){
$azureAplicationId ="<application id>"
$azureTenantId= "<tenant id>"
$azurePassword = ConvertTo-SecureString "<client secret>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
Save-AzureRmContext -Path “path\to\json\file”
}
#setupContext
Import-AzureRmContext -Path “path\to\json\file”
$subscriptionId='***********************************'
Select-AzureRMSubscription -SubscriptionId $subscriptionId -WarningAction SilentlyContinue
$resourceGroup="**************"
$storageAccountName="******************"
$BLOBKey= New-AzureRmStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName -KeyName key2
Write-Host "BLOB Key:"$BLOBKey.Keys[0]
Besides, if you want to learn more about the service principal, you could take a look at this link - Application and service principal objects in Azure Active Directory

Resources