The Resource (SQL Server) under resource group was not found - azure

When I'm trying to fetch DB in elastic pool getting error as:
The Resource 'Microsoft.Sql/servers/dbserver.database.windows.net/databases/db_name' under resource group 'rg_name' was not found.
But for other DB servers and resource group, this script works.
The script I'm trying:
Import-Module Az.Accounts
Import-Module Az.Sql
#Connect-AzAccount -SubscriptionId $subscriptionId
$passwd = ConvertTo-SecureString <PASSWORD> -AsPlainText -Force
$pscredential = New-Object System.Management.Automation.PSCredential('<Application ID>/<Service Principle ID>', $passwd)
Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId
#-SubscriptionId $subscriptionId
$rg = Get-AzResourceGroup -Name $resourceGroupName
Set-AzSqlDatabase -DatabaseName $DatabaseName -ElasticPoolName $PoolName -ResourceGroupName $rg.ResourceGroupName -ServerName $serverName
Read-Host -Prompt "Press Enter to exit "
I verified the permissions, resources and their names/ids all are correct.

According to the error message, I can see that you are providing the -ServerName as dbserver.database.windows.net
Please provide the -ServerName as only dbserver instead of dbserver.database.windows.net

Related

How to get the certifcate from Key vaults using power shell script?

I need help on this scenario. we have a cert in azure key vault which needs to be download to a windows VM for our .net application to run on iis. I am able to upload the cert to Azure keyvault with out issues. I am running a azure devops powershell tasks inline powershell script.
it will connect to azure using conenct-azaccount with appropriate login creds.enter code here
we run invoke-azvmssruncommand and specific the script path and variable which needs to be passed as parameters.
in the PowerShell script we have script to get the cert from azure keyvualt once its connected to azure vm
below is the error
error: an error occurred while sending request. need your thoughts on it.
Invoke-AzVmssVMRunCommand -VMScaleSetName dev-CTUS -ResourceGroupName RG -InstanceId $instanceid -CommandId 'RunPowerShellScript'-ScriptPath "path"\downloadcertfromkeyvault.ps1" -Parameter #{"vaultname"= "keyvault name";"certname"="app-DEV";"password"= "jdksjkdjalksd";"said"="";"sapuserid"; password"="password";"devSubscriptionId"="ZXXXXXXXXXX"} -Debug
this is the command which i used in azure devops powershell inline script .
inside powershell script
$SecurePassword = "$sapassword" | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $said, $SecurePassword
Connect-AzAccount -Credential $Credential -Tenant "XXXXXXXXXXXX-a68c-41e5-XXXXXXXX"
Write-log "setting subscription to retrive certs"
Set-AzContext $devSubscriptionId
$password = "$password"
$password = ConvertTo-SecureString -String "$password" -AsPlainText -Force
$cert = Get-AzKeyVaultCertificate -VaultName $vaultname -Name $certname
$secret = Get-AzKeyVaultSecret -VaultName $vaultname -Name $cert.Name
$pfxpath = [System.Environment]::GetFolderPath("Desktop")
$secretByte = [Convert]::FromBase64String($secret.SecretValueText)
$x509Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($secretByte, "", "Exportable,PersistKeySet")
$type = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx
$pfxFileByte = $x509Cert.Export($type, $password)
# Write to a file
[System.IO.File]::WriteAllBytes("$pfxpath\$certname.pfx", $pfxFileByte)
$certificate= Get-ChildItem -path cert:\LocalMachine\My` `
Write-Log $certificate

Azure PowerShell Set-AzKeyVaultAccessPolicy command setting access policy to data factory

While trying to give access policy (Azure key vault) to my Azure data factory through PowerShell, I am getting error below:
Set-AzKeyVaultAccessPolicy : Operation returned an invalid status code
'BadRequest' At line:64 char:1
Set-AzKeyVaultAccessPolicy -VaultName $keyvaultname -ServicePrincipal ...
+ CategoryInfo : CloseError: (:) [Set-AzKeyVaultAccessPolicy], Gr aphErrorException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.SetAzureKeyVau ltAccessPolicy
Any help would be really appreciated. Thanks in advance.
This is the script I am trying to execute:
## select subcription
$subcription='Visual Studio Enterprise – MPN'
Select-AzSubscription $subcription
## create a new resource group
$resourcegroupname=”gho-rg-dev”
$location="eastus"
$rg=New-AzResourceGroup `
-Name $resourcegroupname `
-Location $location
## create the storage account
$storageAccountName = "ghostoragelab"
$skuName = "Standard_LRS"
$storageAccount = New-AzStorageAccount -ResourceGroupName $resourcegroupname `
-Name $storageAccountName `
-Location $location `
-SkuName $skuName
$storageaccountkey=(Get-AzStorageAccountkey -ResourceGroupName $resourcegroupname -Name $storageAccount.StorageAccountName).Value[0]
##create azure data factory
$datafactoryname='lab-factory-dev'
$df= New-AzDataFactoryV2 `
-ResourceGroupName $resourcegroupname -Name $datafactoryname -Location $location
## creating the azure key vault
$keyvaultname="labkeydev"
$keyvault=New-AzKeyVault -ResourceGroupName $resourcegroupname -Name $keyvaultname `
-Location $location
# creating the secret key in keyvault
Set-AzKeyVaultSecret -VaultName $keyvaultname -Name "secret-access-key"`
-SecretValue(ConvertTo-SecureString -String $storageaccountkey -AsPlainText -Force)
#Give access policy to the datafactory thorugh keyvault
*## this is where script is failing*
Set-AzKeyVaultAccessPolicy -VaultName $keyvaultname -ServicePrincipalName $df.DataFactoryId -PermissionsToSecrets Get
I suppose you want to add the MSI (Managed Service Identity) of the Data Factory to the Access policies of your keyvault.
You got the error because you used the -ServicePrincipalName $df.DataFactoryId in this
command Set-AzKeyVaultAccessPolicy, the $df.DataFactoryId is the resource id of the data factory, what you need is the Application ID(Client ID) of the MSI.
So if you want to use -ServicePrincipalName parameter, your command should be:
$appId = (Get-AzADServicePrincipal -ObjectId $df.Identity.PrincipalId).ApplicationId
Set-AzKeyVaultAccessPolicy -VaultName joykeyvault -ServicePrincipalName $appId -PermissionsToSecrets get
The command above needs the permission to get service principal in your Azure AD. If you don't have this permission, you could use the command (I recommend you to use this one):
Set-AzKeyVaultAccessPolicy -VaultName joykeyvault -ObjectId $df.Identity.PrincipalId -PermissionsToSecrets get -BypassObjectIdValidation
If your data factory has already been created, you could use Get-AzDataFactoryV2 to get it, then add it to the access policies.
$datafactory = Get-AzDataFactoryV2 -ResourceGroupName <group name> -Name <factory name>
Set-AzKeyVaultAccessPolicy -VaultName joykeyvault -ObjectId $datafactory.Identity.PrincipalId -PermissionsToSecrets get -BypassObjectIdValidation

Spinning up VM from Powershell with multiple admins

I have a script which spins up an Azure VM and specifies an admin username and password.
Is it possible to have the script setup a second admin? The reason for this is so that more than one user can be on the machine at the same time.
Do you have access to the vm with Invoke-Command?
If yes, might this helps: How to Manage Local Users and Groups using PowerShell
According to my research, two users can access Azure windows VM concurrently. A maximum of two concurrent connections are supported unless the server is configured as a Remote Desktop Services session host. Regarding how to add local user to Azure VM, you use the the VM Access extension in Azure PowerShell. For more details, please refer to the document
For example
Connect-AzAccount
$vm = Get-AzVM -ResourceGroupName jimtest -Name jimtest
$name = "jimtest1"
$password = "Pass***!"
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycred= New-Object System.Management.Automation.PSCredential ($name, $secpasswd)
Set-AzVMAccessExtension -Credential $mycred -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -Location $vm.Location -Name VMAccessAgent -TypeHandlerVersion "2.0"
You can use this PowerShell command below to add an admin account to your VM :
$adminName = "testadmin"
$passstr = "password123!"
$Password = ConvertTo-SecureString -String $passstr -AsPlainText -Force
New-LocalUser $adminName -Password $Password -FullName $adminName -Description "test admin account"
Add-LocalGroupMember -Group "Administrators" -Member $adminName
And you can use the Powershell command below to run your custom Powershell command on your Azure VMs(get started with azure powershell see here):
Connect-AzAccount
$vm = Get-AzVM -Name "<your vm name>" -ResourceGroupName "<your vm resource group>"
Invoke-AzVMRunCommand -VM $vm -CommandId 'RunPowerShellScript' -ScriptPath "<path of adding admin account command>"
so just save the first part command as a .ps1 file , and copy the path as value of you can add an local admin account to your VM.
Result :

Adding Access Policy for Managed Service Identity

As part of Powershell script I am provisioning FunctionApp and KeyVault. Script also enables the MSI on function app. I need to add access policy on keyvault for the functionApp. How can I add this access policy? I could not find an example to do this on MSDN.
New-AzResource -ResourceType 'Microsoft.Web/Sites' -ResourceName $FuncAppName -Kind 'functionapp' -Location $defaultRegion -ResourceGroupName $defaultRG -Properties #{ } -Force
set-AzWebApp -ResourceGroupName $defaultRG -AssignIdentity $true -Name $FuncAppName -HttpsOnly $true | Out-Null
$KeyVault = New-AzKeyVault -Name $KeyVaultName -ResourceGroupName $defaultRG -Location $defaultRegion
Set-AzKeyVaultAccessPolicy -VaultName $KeyVault.VaultName -UserPrincipalName $settingsServiceAccountName -PermissionsToSecrets set, get -PassThru | Out-Null
I am able to add a user principle but am not aware how to add a function app.
You could use the -ObjectId parameter, it is the object id of your MSI.
Set-AzKeyVaultAccessPolicy -VaultName 'Contoso03Vault' -ObjectId 34595082-9346-41b6-8d6b-295a2808b8db -PermissionsToSecrets Get,Set
To get the object id of the MSI, use the command as below. Make sure you have
already enabled the MSI.
$objectid = (Get-AzWebApp -ResourceGroupName <ResourceGroupName> -Name <functionname>).Identity.PrincipalId

How to remove a storage account from Azure through Azure DevOps

When I run the Remove-AzureRmStorageAccount command in the Azure PowerShell task I get this error:
2019-01-24T13:07:29.0148404Z ==============================================================================
2019-01-24T13:07:29.0148533Z Task : Azure PowerShell
2019-01-24T13:07:29.0148602Z Description : Run a PowerShell script within an Azure environment
2019-01-24T13:07:29.0148688Z Version : 3.1.18
2019-01-24T13:07:29.0148847Z Author : Microsoft Corporation
2019-01-24T13:07:29.0148947Z Help : [More Information](https://go.microsoft.com/fwlink/?LinkID=613749)
2019-01-24T13:07:29.0149050Z ==============================================================================
2019-01-24T13:07:30.2233628Z ##[command]Import-Module -Name C:\Program Files\WindowsPowerShell\Modules\AzureRM\6.13.1\AzureRM.psd1 -Global
2019-01-24T13:07:42.1447157Z ##[command]Clear-AzureRmContext -Scope Process
2019-01-24T13:07:42.7204663Z ##[command]Disable-AzureRmContextAutosave -ErrorAction SilentlyContinue
2019-01-24T13:07:43.0466903Z ##[command]Add-AzureRMAccount -ServicePrincipal -Tenant *** -Credential System.Management.Automation.PSCredential -Environment AzureCloud #processScope
2019-01-24T13:07:44.1568578Z ##[command] Select-AzureRMSubscription -SubscriptionId XXXXX -TenantId ***
2019-01-24T13:07:44.5546953Z ##[command]& 'D:\a\_temp\XXXXX.ps1'
2019-01-24T13:07:44.6950579Z ##[command]Disconnect-AzureRmAccount -Scope Process
2019-01-24T13:07:45.1149833Z ##[command]Clear-AzureRmContext -Scope Process
2019-01-24T13:07:45.5569262Z ##[error]Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.
This is the script I run:
Remove-AzureRmStorageAccount `
-ResourceGroupName "myResourceGroupName" `
-AccountName "mystorageaccountname"
-Force
Note that I can create the storage account and the blob container in the same way without errors. This script works without any errors:
if(Get-AzureRmStorageAccountNameAvailability -Name "mystorageaccountname")
{
New-AzureRmStorageAccount `
-ResourceGroupName "myResourceGroupName" `
-AccountName "mystorageaccountname" `
-Location "West Europe" `
-SkuName "Standard_LRS"
New-AzureRmStorageContainer `
-ResourceGroupName "myResourceGroupName" `
-AccountName "mystorageaccountname" `
-ContainerName "my-blob-container" `
-PublicAccess "Blob"
}
How do I get the remove to work without errors through the Azure DevOps pipeline?
that happens because its asking to confirm deletion (##[error]Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available), you are missing: `.
Remove-AzureRmStorageAccount `
-ResourceGroupName "myResourceGroupName" `
-AccountName "mystorageaccountname" ` <<<<< here
-Force
just retested it, it works without prompts if you supply -Force

Resources