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

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

Related

Get-AzSubscription won't show my subscription

I have a subscription I want to pause/resume with a PowerShell script (Azure Analysis Services). I use this exact same script to pause my Embedded Capacity and that works fine, but when I run my script for my new subscription it wont work. This is the script I use:
$userPassword = "myappsecret"
$userPassword2 = ConvertTo-SecureString -String $userPassword -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "appid", $userPassword2
Connect-AzAccount -ServicePrincipal -TenantId "tenantid" -Credential $Credential
Select-AzSubscription -SubscriptionId "subscriptionname here"
Get-AzPowerBIEmbeddedCapacity -ResourceGroupName "groupnamehere" -Name "namehere"
Suspend-AzPowerBIEmbeddedCapacity -Name "namehere" -ResourceGroupName "groupnamehere" -PassThru
To check why this won't work I tried to simply use Get-AzSubscription to see if something was wrong and it wont show any subscription.
If I try the same for my Embedded Capacity it works just fine.
What could be wrong?
To get the list of all Azure Ad subscriptions by using Get-AzSubscription, make sure that you have owner/admin role.
You can make use of the below command to get Azure Ad subscriptions for a specific tenant:
Make sure to connect-azaccount with Administrator details.
Get-AzSubscription -TenantId "your_tenant_id"
Get-AzContext command list the information of the Azure Subscription that is currently selected.
To use a specific subscription, you can make use of below command:
Get-AzSubscription -SubscriptionId "xxxx-xxxx-xxxx-xxxx" -TenantId "yyyy-yyyy-yyyy-yyyy" | Set-AzContext
Or please modify your code by adding the below snippet:
$subscriptionId = 'Your_Subscription_ID';
Select-AzSubscription -SubscriptionId $subscriptionId
You can check the Subscription Id via Azure Portal too.
Reference:
Get-AzSubscription (Az.Accounts) | Microsoft Docs

Secure way to save ClientId and ClientSecret to authenticate to Azure using Connect-AzAccount

I am looking for a secure way to have a script running on a local machine and authenticate using these commands in Azure :
$Password = ConvertTo-SecureString -AsPlainText "my_secret" -Force
$Credential = New-Object System.Management.Automation.PSCredential ("my_client_id", $Password)
$TenantId = "my_tenant_id"
Connect-AzAccount -ServicePrincipal -Credential $Credential -Tenant $TenantId
The issue is that I do not want to save the secret as plain text in the script. The only solution I have found was to encrypt SecureString password and save it in a file that can be decrypted using a key. This way, the secret is never in plain text.
Is there any other "clean" way to do this?
Thanks !
Create a credential object one time and use Export-Clixml to store it for the current user/machine.
You can then use Import-Clixml to read them back in to your script.
Sample
# Set credentials
$Credentials = Get-Credential # Set your id and secret
$Credentials | Export-Clixml -Path $PSScriptRoot\Access.xml -Confirm:$false
# Read the credentials
$Credentials = Import-Clixml -Path $PSScriptRoot\Access.xml

Access Azure App Service files from Azure CLI

I would like to move a file within an Azure App Service from a script. I thought that Azure CLI with az webapp command could be used for that, but could not find a way to access the files.
I know that there is Kudu REST API for file access, but I want to run the script during an Azure Devops Pipeline, so authentication for the REST API seems like an issue - I don't want to store the credentials in the pipeline. The same holds for FTP access.
However, there is an Azure CLI task with authorization through configured Service connections, so I thought this might be the way.
So, the core question is - How to move a file within Azure App Service from a command line?
So, it turned out that I can use Azure CLI to get Publishing profile for a particular App service (or even slot) and then use the user name and password from it to access Kudu REST API.
I used this Powershell 6 script
function Get-PublishingProfile($resourceGroupName, $webAppName, $slotName) {
if ([string]::IsNullOrWhiteSpace($slotName)) {
$xml = Get-AzWebAppPublishingProfile -ResourceGroupName $resourceGroupName -Name $webAppName
}
else {
$xml = Get-AzWebAppSlotPublishingProfile -ResourceGroupName $resourceGroupName -Name $webAppName -Slot $slotName
}
return $xml |
Select-Xml -XPath "publishData/publishProfile[1]" |
Select-Object -ExpandProperty Node |
Select-Object -Property publishUrl, msdeploySite, userName, userPWD, destinationAppUrl
}
$profile = Get-PublishingProfile $resourceGroupName $webAppName $slotName
$securePassword = ConvertTo-SecureString -String $profile.userPWD -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential($profile.userName, $securePassword)
$fileUri = "https://$($profile.publishUrl)/api/vfs/site/wwwroot/some_file.txt"
$headers = #{
"If-Match" = "*"
}
Invoke-RestMethod -Uri $fileUri -Method Get -Credential $credentials -Authentication Basic -Headers $headers

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 :

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

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

Resources