Create Azure Objects Using 'Publish Settings' File - azure

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.

Related

PowerShell Task not running the script in Azure Pipelines?

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.

restart cloud service using powershell

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"

Powershell Script continues to ask me to use Select-AzureSubscription although I have called it

I have an Azure runbook where I am trying to deallocate VMs. When I run the runbook I get the error
Stop-AzureVM : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to
set the default subscription.
I have used the below in my script.
Add-AzureRmAccount
Select-AzureRMSubscription
After calling the select, it prints out
PSComputerName : localhost
PSSourceJobInstanceId :
Account :
Environment :
Subscription :
Tenant :
with the correct subscrption and tenant information so it seems the select is working correctly, but for some reason I still cannot use the Stop-AzureVM cmdlet.
Any ideas?
The command Stop-AzureVM is Azure Service Management PowerShell command. It just can be used to stop Azure classic VM. But the command Add-AzureRmAccount is Azure Resource Management PowerShell command. After running the command, we just can manage Azure Resource Management resources. For more details, please refer to here and here.
So with Azure ARM VM, please use the command Stop-AzureRmVM to stop it. Meanwhile, regarding how to stop Azure classic VM, please refer to the following steps
Create Azure Classic Run As Account
Script
$ConnectionAssetName = "AzureClassicRunAsConnection"
# Get the connection
$Conn = Get-AutomationConnection -Name $ConnectionAssetName
# Authenticate to Azure with certificate
$CertificateAssetName = $Conn.CertificateAssetName
$AzureCert = Get-AutomationCertificate -Name $CertificateAssetName
Set-AzureSubscription -SubscriptionName $Conn.SubscriptionName -SubscriptionId $Conn.SubscriptionID -Certificate $AzureCert
Select-AzureSubscription -SubscriptionId $Conn.SubscriptionID
#stop VM
Stop-AzureVM -ServiceName "ContosoService01" -Name "MyVM" -Force
Besides, regarding how to check if the VM is classic, please refer to the blog
Try Running the below :
Get-Module AzureRm.Profile -ListAvailable
This issue might occur when there is multiple instances of the module. If there are multiple instance remove the older modules and retain the new module.
To remove the old module : Uninstall-Module -Name AzureRm.Profile -RequiredVersion 4.6.0#(olderversion if you have any)

How to create a Linux AppService Plan with New-AzAppServicePlan?

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

Error creating web app slot with Azure Powershell cmdlet

I can successfully create a new Azure Web App with this command (provided the resource group and app service plan exist, of course):
New-AzureWebApp `
-Name site-name `
-ResourceGroupName resource-group-name `
-Location 'North Central US' `
-AppServicePlan app-service-plan-name
But when I try to add a slot with a similar command it fails:
New-AzureWebApp `
-Name site-name `
-ResourceGroupName resource-group-name `
-Location 'North Central US' `
-AppServicePlan app-service-plan-name `
-SlotName dev # <--------------------------- this line is added
with the error:
New-AzureWebApp : MismatchingResourceName: The provided resource name 'site-name'
did not match the name in the Url 'site-name/dev'.
At line:1 char:1
+ New-AzureWebApp -SlotName "dev" -Name "site-name" -Location "North ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureWebApp], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.WebApp.Cmdlets.NewAzureWebAppCmdlet
What's going on here? Am I not going about making slots the right way?
Note: I'm using Azure Powershell in AzureResourceManager mode.
This AzureServiceManagement mode command does work so I'm not entirely lost:
New-AzureWebsite -Name "site-name" -Slot "dev" -Location "North Central US"
But why can't I get the former command to work?
What is your App Service plan mode? I hope this is already been taken care, and you should be in either Standard or Premium plan.
This seems to be a issue with the latest release of Azure modules. Will have to wait till the issue is fixed. Probably you might need to raise a Azure Support ticket to bump up the priority.

Resources