I have a powershell task that is used to run a script which involves creating azure resources (Example: Resource group, Azure Key Vault, Function App...). When the pipeline is being run and it arrives to the powershell task in the deploy stage, it shows the following message:
The problem here, it says Finishing:Powershell but it didn't execute the script and did not create any azure resource.
Here is a sample of the powershell script:
$vaultName = "key vault name"
$blobstorageName = "blob storage name"
$Location = "Location Name"
$resourceGroupName = "Resource Group Name"
try {
#Creation of Resource Group
$resourceGroup = Get-AzResourceGroup -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
if($null -eq $resourceGroup)
{
New-AzResourceGroup -Name $resourceGroupName -Location $Location
}
else
{
Write-Host "The ResourceGroup with the name: $resourceGroupName already exists."
}
# Creation of Storage Account
$checkBlobStorage = (Get-AzStorageAccountNameAvailability -Name $blobstorageName) | Select-Object NameAvailable
if ($checkBlobStorage.NameAvailable)
{
New-AzStorageAccount -ResourceGroupName $resourceGroupName -AccountName $blobstorageName -Location $Location -SkuName Standard_LRS -Kind StorageV2 -AccessTier Hot
}
else
{
Write-Host "The name $blobStorageName is not available. Suggest a new globally unique name!"
}
catch
{
}
Does anyone have a clue what is wrong ? Am I missing something in the powershell script (Maybe I don't have direct access to the azure portal from azure devops) or maybe something is missing in
the Yaml file ?
Two major issues:
you seem to be using the Powershell Task, which is not designed for communication with Azure. You should use the Azure Powershell task for this kind of script, because it already has the right modules loaded and the authentication prepared.
your script is swallowing the error so it is hiding what went wrong. It's usually more useful not to catch exceptions; if your script is erroring then let it error, and let the pipeline show you in its log what has happened.
Related
we have a problem with a Microsoft bot hosted in Azure.
As long as we haven't resolved it, we want to periodically restart it.
We found 3 sets of powershell commands and spent the full day on it without making it work.
Solution 1:
we found the cmdlets : Get-AzCloudService Restart-AzCloudService.
We didn't understand from the documentation what module to install.
It returns : The term 'Restart-AzCloudService' is not recognized as the name of a cmdlet.
They talk about an obscure "extended support" to have access to it.
Solution 2:
We are able to list the cloud service using:
Connect-AzAccount
get-azresource -name $serviceName -resourcetype
"Microsoft.BotService/botServices"
But we do not find the cmdlet to restart the resource.
Solution 3:
Reset-AzureRoleInstance -serviceName $serviceName -Slot "production" -InstanceName $serviceName
Error : No default subscription has been designated. Use Select-AzureSubscription -Default
We are using MFA. Login-AzureRmAccount systematically fails , evenly saying that our account is disabled.
We did no manager to run the sequence:
Login-AzureRmAccount
Select-AzureSubscription -Default
Reset-AzureRoleInstance -serviceName $serviceName -Slot "production" -InstanceName $serviceName
The idea is to run this script twice a day, either from a VM or from an Azure Runbook.
We managed to run this code using an automation Account but we are still missing the last command that would restart the bot (that we consider a cloud service).
Param()
$automationAccount = "xxx"
$resourceGroup = "xxx"
$serviceName = "xxx"
$subscriptionname ="xxx"
$subscriptionid ="xxx"
# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process | Out-Null
# Connect using a Managed Service Identity
try {
$AzureContext = (Connect-AzAccount -Identity).context
}
catch{
Write-Output "There is no system-assigned user identity. Aborting.";
exit
}
#Set-AzureSubscription -SubscriptionId $subscriptionid
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription `
-DefaultProfile $AzureContext
get-azresource -name $serviceName -resourcetype "Microsoft.BotService/botServices"
So, I'm told if you import your Azure Subscription Publish Setting file into PowerShell...you can use the certificate in the Publish Setting file to create objects in your Azure Subscription.
However, I am getting the following exception trying to create a Resource Group:
New-AzureRmResourceGroup : Run Connect-AzureRmAccount to login.
+ CategoryInfo : CloseError: (:) [New-AzureRmResourceGroup], PSInvalidOperationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupCmdlet
I Do The Following In My Script:
"Import" the Subscription
"Select" the Subscription
"Get" the Subscription (to view it)
...the subscription is both "Default & Current" (see attached image).
...and yet I still get that message.
SAMPLE CODE:
This code is edited so as not to "give away the farm"...
#Set Subscription
$Subscription_Id = "<not shown>"
Select-AzureSubscription -SubscriptionId $Subscription_Id
Get-AzureSubscription
# CHECK EXISTS: ResourceGroup
$RegionFullName = "South Central US"
$RegionShortName = "scus"
$EnvironmentShortName = "dev"
$ApplicationShortName = "<not shown>"
$ObjectTypeShortName = "rg"
$ResourceGroupFullName = "$($RegionShortName)-$($EnvironmentShortName)-$($ApplicationShortName)-$($ObjectTypeShortName)"
$ResourceGroup = Get-AzureRmResourceGroup -Name $ResourceGroupFullName -ErrorVariable NotPresent -ErrorAction SilentlyContinue
if ($ResourceGroup -eq $Null) {
#CREATE: ResourceGroup
$ResourceGroup = New-AzureRmResourceGroup -Name $ResourceGroupFullName -Location $RegionFullName -Confirm
}
I suppose you are using Import-PublishSettingsFile, but Azure Management Certificates and Publishing Setting files are only intended (for) and (are) limited to managing Azure Service Management (ASM) resources, which are being retired.
In your script, you mixed the ASM and AzureRm powershell modules together. Select-AzureSubscription and Get-AzureSubscription belong to ASM, Get-AzureRmResourceGroup and New-AzureRmResourceGroup belong to AzureRm.
So if you need to use AzureRm command, you need to run Connect-AzureRmAccount to login your account.
What is the equivalient of this code using New-AzAppServicePlan?
az appservice plan create --resource-group $ServerFarmResourceGroupName `
--name $AppServicePlanName `
--is-linux `
--location $ResourceGroupLocation `
--sku $AppServicePlanTier `
--number-of-workers $NumberOfWorkers
Is there really no way to create an App Service Plan using Az Powershell? Why can it only be done via Azure CLI or ARM?
I only found this answer, which basically uses ARM directly: How do I use Powershell to create an Azure Web App that runs on Linux?
There are some issues about this, suppose for now this is not supported for New-AzureRmAppServicePlan, however you could use New-AzureRmResource to create a linux plan. You could try the below command.
New-AzureRmResource -ResourceGroupName <>group name -Location "Central US" -ResourceType microsoft.web/serverfarms -ResourceName <plan name> -kind linux -Properties #{reserved="true"} -Sku #{name="S1";tier="Standard"; size="S1"; family="S"; capacity="1"} -Force
I originally used my script to create a ConsumptionPlan (Y1) through PowerShell and AzureCLI because I don't like when Azure put a generated name when creating a ConsumptionPlan.
Please find my solution to create a Linux App Service Plan (B1) using New-AzResource:
$fullObject = #{
location = "West Europe"
sku = #{
name = "B1"
tier = "Basic"
}
kind = "linux"
properties = #{
reserved = $true
}
}
$resourceGroupName = "rg-AppServicePlanLinux"
$serverFarmName = "aspl-test"
Write-Host "Step 1: CREATING APP SERVICE PLAN B1:Basic named [$serverFarmName]"
# Create a server farm which will host the function app in the resource group specified
New-AzResource -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.Web/serverfarms" -Name $serverFarmName -IsFullObject -PropertyObject $fullObject -Force
So I used the ARM template to understand which information you need to provide on the -PropertyObject parameter
It also now seems possible to do an App Service Plan Linux with New-AzAppServicePlan command since Az PowerShell 4.3.0 (June 2020) with the parameter -Linux
Az.Websites
Added safeguard to delete created webapp if restore failed in 'Restore-AzDeletedWebApp'
Added 'SourceWebApp.Location' for 'New-AzWebApp' and 'New-AzWebAppSlot'
Fixed bug that prevented changing Container settings in 'Set-AzWebApp' and 'Set-AzWebAppSlot'
Fixed bug to get SiteConfig when -Name is not given for Get-AzWebApp
Added a support to create ASP for Linux Apps
Added exceptions for clone across resource groups
Release Note: https://learn.microsoft.com/en-us/powershell/azure/release-notes-azureps?view=azps-5.6.0&viewFallbackFrom=azps-4.3.0#azwebsites-7
New-AzAppServicePlan: https://learn.microsoft.com/en-us/powershell/module/az.websites/new-azappserviceplan?view=azps-5.6.0
If you get "The Service is unavailable" after deploying your new Function app (Consumption Plan) with Azure CLI, please make sure the following statement from Microsoft:
https://github.com/Azure/Azure-Functions/wiki/Creating-Function-Apps-in-an-existing-Resource-Group
I waste the whole day because I got another Function App (Premium Plan) in the same resource group I used to deploy the Consumption one.
This worked for me:
Adding -Linux as a parameter to my command
New-AzAppServicePlan -ResourceGroupName $RESOURCE_GROUP_NAME -Name $APP_SERVICE_PLAN_NAME -Location $RESOURCE_LOCATION -Linux -Tier $APP_SERVICE_PLAN_TIER -NumberofWorkers $APP_SERVICE_PLAN_WORKERS -WorkerSize $APP_SERVICE_PLAN_WORKER_SIZE
Example:
New-AzAppServicePlan -ResourceGroupName 'MyResourceGroup' -Name 'MyServicePlan' -Location 'northeurope' -Linux -Tier 'PremiumV2' -NumberofWorkers 2 -WorkerSize Medium
That's all.
I hope this helps
I created new GitHub private repository, in that I added ARM templates for Azure key vault. After that I am trying to deploy ARM template from my local machine using PowerShell tool.
This is PowerShell script I used for deploying ARM template into azure.
#Login-AzureRmAccount
#region Parameters
$resourceGroupName='KZEU-ARMTMP-SB-DEV-RGP-01'
$location='eastus'
$parametersUri='E:\Kishore\Kishore GitHub\ARMTemplates\Parameters\StorageAccount.parameters.json'
$templateUri='https://raw.githubusercontent.com/xxxxxxx/ARMTemplates/master/Templates/StorageAccount.json?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$clientID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="
#endregion
#region Login into Azure
$SecurePassword = $key | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $clientID, $SecurePassword
Add-AzureRmAccount -Credential $cred -Tenant "xxxxxxxxxxxxxxxxxxxxxx" - ServicePrincipal
Set-AzureRmContext -SubscriptionID 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
#endregion
#region Check or Create Resource Group
Get-AzureRmResourceGroup -Name $resourceGroupName -ev notPresent -ea 0
if($notPresent){
Write-Host "Failover RG '$resourceGroupName' doesn't exist. Creating a new in $location...." -ForegroundColor Yellow
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
}else{
Write-Host "Using existing resource group '$resourceGroupName'" -ForegroundColor Yellow;
}
#endregion
#region Validate & Deploy ARM Templates
try{
$templateValidationResult= Test-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile $templateUri -TemplateParameterFile $parametersUri -Verbose
if($templateValidationResult[0].Code-eq"InvalidTemplateDeployment"){
Write-Host "Failed to validate ARM template"
exit 1
}else{
Write-Host "Successfully completed to validate ARM template"
$deploymentResult= New-AzureRmResourceGroupDeployment -Name StorageAccount-Deployment -ResourceGroupName $resourceGroupName -TemplateFile $templateUri -TemplateParameterFile $parametersUri -Verbose
if($deploymentResult.ProvisioningState-eq"Succeeded"){
Write-Host "Successfully completed to deploy ARM template"
}else{
Write-Host "Failed to deploy ARM template"
exit 1
}
}
}
catch{
$ex = $_.Exception | Format-List -Force
Write-Host $ex
}
#endregion
When I run the above PowerShell script, then I am getting the error like
Unable to download deployment content from "https://raw.githubusercontent.com/xxxx/demo-in/master/xxxx/keyVault.json"
So, can anyone suggest me how to resolve the above issue?
Your issue is that you can't deploy from a private repo (see doc). What you are trying to do is pass a template URI for Azure to read and it doesn't have permission to read from your private repo. You have a couple options:
Do like the docs say and save the deploy.json to Azure Storage
and protect it with a SAS token.
You can clone your repo locally and
deploy from the local file.
I would like to know how to create an alert for an Azure VM which tells me if the server(s) is running at a specific time.
The scenario:
Servers for the Azure network need to start at 7:30am to be ready for the users as they shut down at 7:30pm each day to save $$.
Today the azure automation script could not find any vms for the resource group! So that meant the servers where not started. I want to create an alert that will only tell me if the server(s) are not running at say 7:45am. So I can start them.
(Running the script now does find all of the servers now but didn't before for some reason... maybe Azure was moving the vms in the resource group?)
I have looked at:
- Microsoft Operations Management Suit > Log Search > Add Alert Rule.
- Resource Manager > Virtual Machines > Monitoring > Alert Rules > Add metic alert & Add activity log alert.
But I can't see where to only run the alert at a specific time.
Update/Edit:
Script used:
param (
[Parameter(Mandatory=$false)]
[String]$AzureCredentialAssetName = 'AzureCred',
[Parameter(Mandatory=$false)]
[String]$AzureSubscriptionIDAssetName = 'AzureSubscriptionId'
)
# Setting error and warning action preferences
$ErrorActionPreference = "SilentlyContinue"
$WarningPreference = "SilentlyContinue"
# Connecting to Azure
$Cred = Get-AutomationPSCredential -Name $AzureCredentialAssetName -ErrorAction Stop
$null = Add-AzureAccount -Credential $Cred -ErrorAction Stop -ErrorVariable err
$null = Add-AzureRmAccount -Credential $Cred -ErrorAction Stop -ErrorVariable err
# Selecting the subscription to work against
$SubID = Get-AutomationVariable -Name $AzureSubscriptionIDAssetName
Select-AzureRmSubscription -SubscriptionId $SubID
# Getting all resource groups
$ResourceGroup = "Servers"
# Getting all virtual machines
$RmVMs = (Get-AzureRmVM -ResourceGroupName $ResourceGroup -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).Name
# Managing virtual machines deployed with the Resource Manager deployment model
"Loop through all VMs in resource group $ResourceGroup."
if ($RmVMs)
{
foreach ($RmVM in $RmVMs)
{
"`t$RmVM found ..."
$RmPState = (Get-AzureRmVM -ResourceGroupName $ResourceGroup -Name $RmVM -Status -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).Statuses.Code[1]
if ($RmPState -eq 'PowerState/deallocated')
{
"`t$RmVM is starting up ..."
$RmSState = (Start-AzureRmVM -ResourceGroupName $ResourceGroup -Name $RmVM -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).IsSuccessStatusCode
if ($RmSState -eq 'True')
{
"`t$RmVM has been started."
}
else
{
"`t$RmVM failed to start."
}
}
}
}
else
{
"No VMs for $ResourceGroup deployed with the Resource Manager deployment model."
}
"Runbook Completed."
I just want a fail safe to know if the servers are not running when they should be.
Expected output:
Loop through all VMs in resource group Servers.
DOMAINCONTROLLER found ...
SQLSERVER found ...
GATEWAY found ...
APPLICATIONHOST found ...
Runbook Completed.
instead of:
Loop through all VMs in resource group Servers.
No VMs for Servers deployed with the Resource Manager deployment model.
Runbook Completed.
I.e. rerunning the same script manually gave expected results.
Based on my knowledge, Azure metric alert could not send mail when your VM has been started or stopped at a specific time.
According to your description, Start/Stop VMs during off-hours [Preview] solution in Automation is a good solution for you to save money.
The Start/Stop VMs during off-hours [Preview] solution starts and stops your Azure Resource Manager virtual machines on a user-defined schedule and provides insight into the success of the Automation jobs that start and stop your virtual machines with OMS Log Analytics.
It could send email notifications when the start and stop VM runbooks complete.
You also could use Azure automation to start or stop VM for a specific time, more information please refer to this link.
Update:
Your script works for me. I check your script, $RmVMs = (Get-AzureRmVM -ResourceGroupName $ResourceGroup -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).Name returns null. Do you have multiple subscriptions? It seems that your subscription ID is wrong. Please ensure your subscription ID is right. You could get your subscription ID on your local PowerShell.
Get-AzureRmSubscription
Update2:
You could save your save your subscription to automation connection. You could use the script below:
param (
[Parameter(Mandatory=$false)]
[String]$AzureCredentialAssetName
)
# Authenticate to Azure with certificate
Write-Verbose "Get connection asset: $ConnectionAssetName" -Verbose
$connectionName = Get-AutomationConnection -Name $AzureCredentialAssetName
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $AzureCredentialAssetName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$ResourceGroup = "shui2"
.....