Installing Azure powershell in an azure Virtual Machine - powershell

I need to write a powershell workflow that creates an Azure Virtual Machine and executes some azure cmdlets in that Azure Virtual Machine. But the newly created VM has no azure powershell module installed in it. My code would be like this
New-AzureQuickVM -Windows -ServiceName $serviceName -Name $vmname -ImageName $VMImage -Password $password -AdminUserName $username -InstanceSize "ExtraSmall" -WaitForBoot
$WinRmUri = Get-AzureWinRMUri -ServiceName $serviceName -Name $vmname
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
Invoke-Command -ConnectionUri $WinRmUri -Credential $Cred -ScriptBlock {
Add-AzureAccount ...... ## These cmdlets need Azure Powershell Module
Set-AzureSubscription........
New-AzureStorageAccount......
}
I am not supposed to manually get rdp of that VM and open it to install Azure Powershell Module but to dynamically create a VM using powershell cmdlet and install azure module in that vm using powershell itself.

This can easily be done with an ARM (Azure Resource Manager) template. This is a JSON template which defines objects to be deployed. In your case, you would want to deploy a VM with a custom script extension. Upon provisioning of the VM, the Azure Resource Manager will fetch the supplied files and run your custom powershell. See the example below, and replace the line https://<YOUR-BLOB-HERE>.blob.core.windows.net/resources/CUSTOM-POWERSHELL-SCRIPT.ps1 with your blob and powershell script. To run the script you can use Azure powershell, as described here: https://azure.microsoft.com/en-us/documentation/articles/powershell-azure-resource-manager/
The key cmdlet for your purposes is New-AzureResourceGroup. The invocation will be something like:
Switch-AzureMode -Name AzureResourceManager
New-AzureResourceGroup -Name TestRG1 -Location "West US" -TemplateFile <YOUR-JSON-ARM-TEMPLATE>.json
See a list of ARM templates here for reference: https://github.com/Azure/azure-quickstart-templates . Sample template to modify to run custom code/install Azure powershell.
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"newStorageAccountName": {
"type": "string",
"metadata": {
"description": "Unique DNS Name for the Storage Account where the Virtual Machine's disks will be placed."
}
},
"adminUsername": {
"type": "string",
"metadata": {
"description": "Username for the Virtual Machine."
}
},
"adminPassword": {
"type": "securestring",
"metadata": {
"description": "Password for the Virtual Machine."
}
},
"dnsNameForPublicIP": {
"type": "string",
"metadata": {
"description": "Unique DNS Name for the Public IP used to access the Virtual Machine."
}
},
"windowsOSVersion": {
"type": "string",
"defaultValue": "2012-R2-Datacenter",
"allowedValues": [
"2008-R2-SP1",
"2012-Datacenter",
"2012-R2-Datacenter"
],
"metadata": {
"description": "The Windows version for the VM. This will pick a fully patched image of this given Windows version. Allowed values: 2008-R2-SP1, 2012-Datacenter, 2012-R2-Datacenter."
}
}
},
"variables": {
"location": "West US",
"imagePublisher": "MicrosoftWindowsServer",
"imageOffer": "WindowsServer",
"OSDiskName": "osdiskforwindowssimple",
"nicName": "myVMNic",
"addressPrefix": "10.0.0.0/16",
"subnetName": "Subnet",
"subnetPrefix": "10.0.0.0/24",
"storageAccountType": "Standard_LRS",
"publicIPAddressName": "myPublicIP",
"publicIPAddressType": "Dynamic",
"vmStorageAccountContainerName": "vhds",
"vmName": "MyWindowsVM",
"vmSize": "Standard_A2",
"virtualNetworkName": "MyVNET",
"vnetID": "[resourceId('Microsoft.Network/virtualNetworks',variables('virtualNetworkName'))]",
"subnetRef": "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]"
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[parameters('newStorageAccountName')]",
"apiVersion": "2015-05-01-preview",
"location": "[variables('location')]",
"properties": {
"accountType": "[variables('storageAccountType')]"
}
},
{
"apiVersion": "2015-05-01-preview",
"type": "Microsoft.Network/publicIPAddresses",
"name": "[variables('publicIPAddressName')]",
"location": "[variables('location')]",
"properties": {
"publicIPAllocationMethod": "[variables('publicIPAddressType')]",
"dnsSettings": {
"domainNameLabel": "[parameters('dnsNameForPublicIP')]"
}
}
},
{
"apiVersion": "2015-05-01-preview",
"type": "Microsoft.Network/virtualNetworks",
"name": "[variables('virtualNetworkName')]",
"location": "[variables('location')]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[variables('addressPrefix')]"
]
},
"subnets": [
{
"name": "[variables('subnetName')]",
"properties": {
"addressPrefix": "[variables('subnetPrefix')]"
}
}
]
}
},
{
"apiVersion": "2015-05-01-preview",
"type": "Microsoft.Network/networkInterfaces",
"name": "[variables('nicName')]",
"location": "[variables('location')]",
"dependsOn": [
"[concat('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
"[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
],
"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"privateIPAllocationMethod": "Dynamic",
"publicIPAddress": {
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
},
"subnet": {
"id": "[variables('subnetRef')]"
}
}
}
]
},
},
{
"apiVersion": "2015-05-01-preview",
"type": "Microsoft.Compute/virtualMachines",
"name": "[variables('vmName')]",
"location": "[variables('location')]",
"dependsOn": [
"[concat('Microsoft.Storage/storageAccounts/', parameters('newStorageAccountName'))]",
"[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
],
"properties": {
"hardwareProfile": {
"vmSize": "[variables('vmSize')]"
},
"osProfile": {
"computername": "[variables('vmName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
},
"storageProfile": {
"imageReference": {
"publisher": "[variables('imagePublisher')]",
"offer": "[variables('imageOffer')]",
"sku" : "[parameters('windowsOSVersion')]",
"version":"latest"
},
"osDisk" : {
"name": "osdisk",
"vhd": {
"uri": "[concat('http://',parameters('newStorageAccountName'),'.blob.core.windows.net/',variables('vmStorageAccountContainerName'),'/',variables('OSDiskName'),'.vhd')]"
},
"caching": "ReadWrite",
"createOption": "FromImage"
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
}
]
}
},
"resources": [
{
"name": "CustomScript",
"type": "extensions",
"location": "[variables('location')]",
"apiVersion": "2015-05-01-preview",
"dependsOn": [
"[concat('Microsoft.Compute/virtualMachines/', variables('vmName')]"
],
"properties": {
"publisher": "Microsoft.Compute",
"type": "CustomScriptExtension",
"typeHandlerVersion": "[variables('customScriptExtensionVersion')]",
"settings": {
"fileUris": [
"https://<YOUR-BLOB-HERE>.blob.core.windows.net/resources/CUSTOM-POWERSHELL-SCRIPT.ps1",
"http://go.microsoft.com/?linkid=9811175&clcid=0x409"
],
"commandToExecute": "[concat('powershell.exe -ExecutionPolicy Unrestricted -Command .\\CUSTOM-POWERSHELL-SCRIPT.ps1 -Argument1 argument1')]"
}
}
}
]
}
]
}

If your VM has PowerShell 5.0, then you can use the PowerShell Gallery to install your modules. You will not require any steps mentioned in other answers. All you need to do is write the PowerShell script as you would normally do. Just add the Module from PowerShell gallery using just one cmdlet.
You can either use Install-Module to install a module from the gallery, or you can use Install-Script to install a sample script from the PowerShell public gallery.
You can even put your own modules in the gallery and install from there.
Reference: Get Started with the PowerShell Gallery

You may use Azure Automation service implementing your Powershell code into a runbook.
http://azure.microsoft.com/en-us/documentation/services/automation/

Though not a straight forward approach I implemented this idea that satisfied my need.
Create a new azure VM from Portal and connect it through RDP https://azure.microsoft.com/en-in/documentation/articles/virtual-machines-windows-tutorial/
Now download azure powershell msi in YOUR machine ( In AzureVM downloading is blocked) http://az635501.vo.msecnd.net/azcopy-3-1-0/MicrosoftAzureStorageTools.msi
Manually copy the msi file to the virtual machine and install it in that VM
Now Capture the image of that VM and upload it in Azure My images
https://azure.microsoft.com/en-in/documentation/articles/virtual-machines-capture-image-windows-server/
When I write automation script to create a VM, I used this newly created customVM image, where AzurePowershell is already installed

Related

Enable .NET Core collection in AppService with ARM or PowerShell

I would like to enable the .NET Core collection level with applicationInsight in Azure AppService as shown in below picture. From Azure Portal it works well. Keep in mind that by default value is set to disabled:
Now I would like to automate this using either ARM template or powershell.
I did a export template to see how it looks on ARM but there is no settings related to .NET Core collection
I check documentation on MS website but nothing about ARM template with enabling collection too
In PowerShell same problem
Is there anyone in the community who know how to enable the collection using ARM or PowerShell ?
Thanks a lot !
It's simply setting an app setting called XDT_MicrosoftApplicationInsights_Mode with value recommended (to enable) or default (to disable) as described here. You can do that both in ARM or PowerShell as below.
ARM (check appSettings part):
{
"resources": [
{
"name": "[parameters('name')]",
"type": "Microsoft.Web/sites",
"properties": {
"siteConfig": {
"appSettings": [
{
"name": "APPINSIGHTS_INSTRUMENTATIONKEY",
"value": "[reference('microsoft.insights/components/AppMonitoredSite', '2015-05-01').InstrumentationKey]"
},
{
"name": "APPLICATIONINSIGHTS_CONNECTION_STRING",
"value": "[reference('microsoft.insights/components/AppMonitoredSite', '2015-05-01').ConnectionString]"
},
{
"name": "ApplicationInsightsAgent_EXTENSION_VERSION",
"value": "~2"
},
{
"name": "XDT_MicrosoftApplicationInsights_Mode ",
"value": "recommended"
}
]
},
"name": "[parameters('name')]",
"serverFarmId": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('serverFarmResourceGroup'), '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
"hostingEnvironment": "[parameters('hostingEnvironment')]"
},
"dependsOn": [
"[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
"microsoft.insights/components/AppMonitoredSite"
],
"apiVersion": "2016-03-01",
"location": "[parameters('location')]"
},
{
"apiVersion": "2016-09-01",
"name": "[parameters('hostingPlanName')]",
"type": "Microsoft.Web/serverfarms",
"location": "[parameters('location')]",
"properties": {
"name": "[parameters('hostingPlanName')]",
"workerSizeId": "[parameters('workerSize')]",
"numberOfWorkers": "1",
"hostingEnvironment": "[parameters('hostingEnvironment')]"
},
"sku": {
"Tier": "[parameters('sku')]",
"Name": "[parameters('skuCode')]"
}
},
{
"apiVersion": "2015-05-01",
"name": "AppMonitoredSite",
"type": "microsoft.insights/components",
"location": "West US 2",
"properties": {
"ApplicationId": "[parameters('name')]",
"Request_Source": "IbizaWebAppExtensionCreate"
}
}
],
"parameters": {
"name": {
"type": "string"
},
"hostingPlanName": {
"type": "string"
},
"hostingEnvironment": {
"type": "string"
},
"location": {
"type": "string"
},
"sku": {
"type": "string"
},
"skuCode": {
"type": "string"
},
"workerSize": {
"type": "string"
},
"serverFarmResourceGroup": {
"type": "string"
},
"subscriptionId": {
"type": "string"
}
},
"$schema": "https://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
"contentVersion": "1.0.0.0"
}
Powershell:
$app = Get-AzWebApp -ResourceGroupName "AppMonitoredRG" -Name "AppMonitoredSite" -ErrorAction Stop
$newAppSettings = #{} # case-insensitive hash map
$app.SiteConfig.AppSettings | %{$newAppSettings[$_.Name] = $_.Value} # preserve non Application Insights application settings.
$newAppSettings["APPINSIGHTS_INSTRUMENTATIONKEY"] = "012345678-abcd-ef01-2345-6789abcd"; # set the Application Insights instrumentation key
$newAppSettings["APPLICATIONINSIGHTS_CONNECTION_STRING"] = "InstrumentationKey=012345678-abcd-ef01-2345-6789abcd"; # set the Application Insights connection string
$newAppSettings["ApplicationInsightsAgent_EXTENSION_VERSION"] = "~2"; # enable the ApplicationInsightsAgent
$newAppSettings["XDT_MicrosoftApplicationInsights_Mode"] = "recommended"; # set the APM collection to recommended
$app = Set-AzWebApp -AppSettings $newAppSettings -ResourceGroupNamrecommendede $app.ResourceGroup -Name $app.Name -ErrorAction Stop

deploying webapp in azure devops pipeline release w powershell / json templates - error - modal dialog box is not valid

#Using Azure DevOps pipeline release with a powershell script and a json template file and json parameter #file. Note-authenticating to the azure portal requires multi factor authentication (ie.authenticator on my mobile)
#'ERROR- >>>>> <strong>"Showing a modal dialog box or form when the application is not running in #UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly #style to display a notification from a service application."</strong>
#(Note- Bottom of logs immediately below contains this modal error.)'
2020-11-14T20:33:38.7159389Z ##[section]Starting: WebApp_Create01
2020-11-14T20:33:38.7499602Z ==============================================================================
2020-11-14T20:33:38.7499865Z Task : Azure PowerShell
2020-11-14T20:33:38.7499927Z Description : Run a PowerShell script within an Azure environment
2020-11-14T20:33:38.7499981Z Version : 3.1.28
2020-11-14T20:33:38.7500050Z Author : Microsoft Corporation
2020-11-14T20:33:38.7500132Z Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-powershell
2020-11-14T20:33:38.7500215Z ==============================================================================
2020-11-14T20:33:40.5542183Z ##[command]Import-Module -Name C:\Program Files\WindowsPowerShell\Modules\AzureRM\6.13.1\AzureRM.psd1 -Global
2020-11-14T20:33:54.9421385Z ##[command]Clear-AzureRmContext -Scope Process
2020-11-14T20:33:55.3824175Z ##[command]Disable-AzureRmContextAutosave -ErrorAction Stop
2020-11-14T20:33:56.1766169Z ##[command]Add-AzureRMAccount -ServicePrincipal -Tenant *** -Credential System.Management.Automation.PSCredential -Environment AzXXXXXXXXXXXXXnt #processScope
2020-11-14T20:33:57.8815316Z ##[command] Select-AzureRMSubscription -SubscriptionId c27XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2 -TenantId ***
2020-11-14T20:33:58.5484671Z ##[command]& 'C:\agent\Workfolder_CloudUiPathAgent03\_temp\939d1XXXXXXXXXXXXXXXXXXXXXXXX2127.ps1'
2020-11-14T20:33:58.7424214Z ##[command]Disconnect-AzureRmAccount -Scope Process -ErrorAction Stop
2020-11-14T20:33:59.1018440Z ##[command]Clear-AzureRmContext -Scope Process -ErrorAction Stop
<strong>2020-11-14T20:33:59.7603535Z ##[error]Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.</strong>
2020-11-14T20:33:59.8133689Z ##[section]Finishing: WebApp_Create01
<br>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#The immediately below is the ps1 pasted into the section for the "Inline" script. Pipeline was #created as "Azure Powershell":
Connect-AzureRmAccount -Environment AzXXXXXXXXXXXXXnt -TenantId '410XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXf1d' -Force
Select-AzureRmSubscription -Subscription "c271XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX832"
# Tried both Connect-AzureRmAccount and Login-AzureRmAccount without any success?
#Login-AzureRmAccount -Environment AzXXXXXXXXXXXXXt | Out-Null
#Select-AzureRmSubscription -Subscription "c271XXXXXXXXXXXXXXXXXXXXXXXXX832" | Out-Null
<br>
# Deploy App Service Plan, Web App & Deployment Slots
$DeploymentParametersBuildVM = #{
ResourceGroupName = 'DXXXXXXXXXXXXXXXXXXXXXXXXamic'
TemplateUri = 'https://dXXXXXXXXXXXXXXXXX.blob.core.XXXXXcloudapi.net/blob-uXXXXXXXXXXXXXXXXXXXXXXXXX7/webappcreate.json'
TemplateParameterFile = "https://XXXXXXXXXXXXXapi.net/blob-uXXXXXXXXXXXXXXXXXXXXXXXXX7/webappcreate.parameters.json"
Verbose = $true
webAppName = 'uXXXXXXXXXXXXXXXXXXXXXXXXXXX7'
hostingPlanName = 'WebXXXXXXXXXXXXXXXXXXXXXX01'
templateSasToken = 'mtAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXpSTQ=='
subscriptionId = 'c271XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX832'
name = 'uXXXXXXXXXXXXXXXXXXXXX7'
location = 'UXXXXXXXXXXXXXXX'
serverFarmResourceGroup = 'DXXXXXXXXXXXXXXXXXXXXXXXXamic'
Tenantid = '410XXXXXXXXXXXXXXXXXXXXXXXXXXXf1d'
alwaysOn = 'off'
sku = 'Free'
skuCode = 'F1'
workerSize = '0'
workerSizeId = '0'
numberOfWorkers = '1'
currentStack = 'dotnet'
phpVersion = 'OFF'
appInsightValue = 'uXXXXXXXXXXXXXXXXXXXXXXo7Insight'
netFrameworkVersion = 'v4.0'
azureAccountPassword = '12XXXXXXXXXXXXXXXXXditto'
accountid = 'a183XXXXXXXXXXXXXXXXXXXXXXXXXXXXX68fa'
Credential = '12XXXXXXXXXXXXXXXXXditto'
ServicePrincipal = '_MV_XXXXXXXXXXXXXXXXXXXXXXXXXXXX9~1e'
}
# DEPLOY
New-AzureRmResourceGroupDeployment #DeploymentParametersBuildVM
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#webapp.parameters.json (this is the azure webapp "parameter" json immediately below):
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"subscriptionId": {
"value": "c271XXXXXXXXXXXXXXXXXXXXXXXXXXXXX832"
},
"name": {
"value": "uXXXXXXXXXXXXXXXXXXX7"
},
"location": {
"value": "UXXXXXXXXXXXXXX"
},
"hostingPlanName": {
"value": "WebXXXXXXXXXXXXXXXXXXX01"
},
"serverFarmResourceGroup": {
"value": "DXXXXXXXXXXXXXXXXXXXic"
},
"alwaysOn": {
"value": "true"
},
"sku": {
"value": "Free"
},
"skuCode": {
"value": "F1"
},
"workerSize": {
"value": "0"
},
"workerSizeId": {
"value": "0"
},
"numberOfWorkers": {
"value": "1"
},
"currentStack": {
"value": "dotnet"
},
"phpVersion": {
"value": "OFF"
},
"appInsightValue": {
"value": "uXXXXXXXXXXXXXXXXXX7Insight"
},
"netFrameworkVersion": {
"value": "v4.0"
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#webappacreate.json (this is the azure webapp "template" json immediately below)
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"subscriptionId": {
"type": "string"
},
"name": {
"type": "string"
},
"location": {
"type": "string"
},
"hostingPlanName": {
"type": "string"
},
"serverFarmResourceGroup": {
"type": "string"
},
"alwaysOn": {
"type": "bool"
},
"sku": {
"type": "string"
},
"skuCode": {
"type": "string"
},
"workerSize": {
"type": "string"
},
"workerSizeId": {
"type": "string"
},
"numberOfWorkers": {
"type": "string"
},
"currentStack": {
"type": "string"
},
"phpVersion": {
"type": "string"
},
"appInsightValue": {
"type": "string"
},
"netFrameworkVersion": {
"type": "string"
}
},
"variables": {
"appInsightName": "[concat('microsoft.insights/components/',parameters('appInsightValue'))]"
},
"resources": [
{
"apiVersion": "2018-11-01",
"name": "[parameters('name')]",
"type": "Microsoft.Web/sites",
"location": "[parameters('location')]",
"tags": {},
"dependsOn": [
"[concat('microsoft.insights/components/',parameters('appInsightValue'))]",
"[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
],
"properties": {
"name": "[parameters('name')]",
"siteConfig": {
"appSettings": [
{
"name": "APPINSIGHTS_INSTRUMENTATIONKEY",
"value": "[reference(variables('appInsightName'), '2015-05-01').InstrumentationKey]"
},
{
"name": "APPLICATIONINSIGHTS_CONNECTION_STRING",
"value": "[reference(variables('appInsightName'), '2015-05-01').ConnectionString]"
},
{
"name": "ApplicationInsightsAgent_EXTENSION_VERSION",
"value": "~2"
},
{
"name": "XDT_MicrosoftApplicationInsights_Mode",
"value": "default"
}
],
"metadata": [
{
"name": "CURRENT_STACK",
"value": "[parameters('currentStack')]"
}
],
"phpVersion": "[parameters('phpVersion')]",
"netFrameworkVersion": "[parameters('netFrameworkVersion')]",
"alwaysOn": "[parameters('alwaysOn')]"
},
"serverFarmId": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('serverFarmResourceGroup'), '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
"clientAffinityEnabled": true
}
},
{
"apiVersion": "2018-11-01",
"name": "[parameters('hostingPlanName')]",
"type": "Microsoft.Web/serverfarms",
"location": "[parameters('location')]",
"kind": "",
"tags": {},
"dependsOn": [],
"properties": {
"name": "[parameters('hostingPlanName')]",
"workerSize": "[parameters('workerSize')]",
"workerSizeId": "[parameters('workerSizeId')]",
"numberOfWorkers": "[parameters('numberOfWorkers')]"
},
"sku": {
"Tier": "[parameters('sku')]",
"Name": "[parameters('skuCode')]"
}
},
{
"apiVersion": "2015-05-01",
"name": "[parameters('appInsightValue')]",
"type": "microsoft.insights/components",
"location": "[parameters('location')]",
"tags": {},
"properties": {
"ApplicationId": "[parameters('name')]",
"Request_Source": "IbizaWebAppExtensionCreate"
}
}
]
}
According to the error message, it seems you need to set the options of MessageBox.Show to either ServiceNotification or DefaultDesktopOnly. You can try the workaround provided in this ticket: adding MessageBoxOptions.ServiceNotification
MessageBox.Show(msg, "Print Error", System.Windows.Forms.MessageBoxButtons.YesNo,
System.Windows.Forms.MessageBoxIcon.Error,
System.Windows.Forms.MessageBoxDefaultButton.Button1,
System.Windows.Forms.MessageBoxOptions.ServiceNotification);
But, MessageBox is for use within windows (as opposed to web) applications. It would attempt to open a message box on the server. Here is a ticket you can refer to.
Found out that no authentication was required for azure devops pipeline hence no login or connect is required. This got rid of the popup (modal error).
Next I checked with the azure devops person and he said to not use powershell in the pipeline.
He recommended "Azure Resource Group Deployment" option for the pipeline release. This does not require any initiation script but just a json template and a json parameter.
Thank You.

Deploying an Azure VM and Users with an ARM template and DSC

I am taking my first look at creating a DSC (Desired State Configuration) to go with an ARM (Azure Resource Manager) template to deploy a Windows Server 2016 and additional local user accounts. So far the ARM template works fine and for the DSC file I am using simple example to test functionality. The deployment works fine until I try to pass a username/password so I can create a local Windows user account. I can't seem to make this function work at all (see the error message below).
My question is, how do I use the ARM template to pass the credentials (password) to the DSC (mof) file so that the user can be created without having to explicitly allow plain text passwords (which is not a good practice)?
This is what I have tried:
DSC file
Configuration xUser_CreateUserConfig {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[string]
$nodeName,
[Parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
Import-DscResource -ModuleName xPSDesiredStateConfiguration
Node $nodeName {
xUser 'CreateUserAccount' {
Ensure = 'Present'
UserName = Split-Path -Path $Credential.UserName -Leaf
Password = $Credential
}
}
}
Azure ARM Template Snippet 1st Method
"resources": [
{
"apiVersion": "2016-03-30",
"type": "extensions",
"name": "Microsoft.Powershell.DSC",
"location": "[parameters('location')]",
"tags": {
"DisplayName": "DSC",
"Dept": "[resourceGroup().tags['Dept']]",
"Created By": "[parameters('createdBy')]"
},
"dependsOn": [
"[resourceId('Microsoft.Compute/virtualMachines', concat(variables('vmNamePrefix'), copyIndex(1)))]"
],
"properties": {
"publisher": "Microsoft.Powershell",
"type": "DSC",
"typeHandlerVersion": "2.19",
"autoUpgradeMinorVersion": true,
"settings": {
"wmfVersion": "latest",
"modulesUrl": "[concat(variables('_artifactslocation'), '/', variables('dscArchiveFolder'), '/', variables('dscArchiveFileName'))]",
"configurationFunction": "xCreateUserDsc.ps1\\xUser_CreateUserConfig",
"properties": {
"nodeName": "[concat(variables('vmNamePrefix'), copyIndex(1))]",
"Credential": {
"UserName": "[parameters('noneAdminUsername')]",
"Password": "PrivateSettingsRef:UserPassword"
}
}
},
"protectedSettings": {
"Items": {
"UserPassword": "[parameters('noneAdminUserPassword')]"
}
}
}
}
]
Error message
The resource operation completed with terminal provisioning state 'Failed'. VM has reported a failure when processing extension 'Microsoft.Powershell.DSC'. Error message: \\"The DSC Extension received an incorrect input: Compilation errors occurred while processing configuration 'xUser_CreateUserConfig'. Please review the errors reported in error stream and modify your configuration code appropriately. System.InvalidOperationException error processing property 'Password' OF TYPE 'xUser': Converting and storing encrypted passwords as plain text is not recommended. For more information on securing credentials in MOF file, please refer to MSDN blog: http://go.microsoft.com/fwlink/?LinkId=393729
This error message does not help
Azure ARM Template snippet 2nd Method
"resources": [
{
"apiVersion": "2018-10-01",
"type": "extensions",
"name": "Microsoft.Powershell.DSC",
"location": "[parameters('location')]",
"tags": {
"DisplayName": "DSC",
"Dept": "[resourceGroup().tags['Dept']]",
"Created By": "[parameters('createdBy')]"
},
"dependsOn": [
"[resourceId('Microsoft.Compute/virtualMachines', concat(variables('vmNamePrefix'), copyIndex(1)))]"
],
"properties": {
"publisher": "Microsoft.Powershell",
"type": "DSC",
"typeHandlerVersion": "2.9",
"autoUpgradeMinorVersion": true,
"settings": {
"wmfVersion": "latest",
"configuration": {
"url": "[concat(variables('_artifactslocation'), '/', variables('dscArchiveFolder'), '/', variables('dscArchiveFileName'))]",
"script": "xCreateUserDsc.ps1",
"function": "xUser_CreateUserConfig"
},
"configurationArguments": {
"nodeName": "[concat(variables('vmNamePrefix'), copyIndex(1))]"
},
"privacy": {
"dataCollection": "Disable"
}
},
"protectedSettings": {
"configurationArguments": {
"Credential": {
"UserName": "[parameters('noneAdminUsername')]",
"Password": "[parameters('noneAdminUserPassword')]"
}
}
}
}
}
]
Error Message
VM has reported a failure when processing extension 'Microsoft.Powershell.DSC'. Error message: "The DSC Extension received an incorrect input: A parameter cannot be found that matches parameter name '$credential.Password'. Another common error is to specify parameters of type PSCredential without an explicit type. Please be sure to use a typed parameter in DSC Configuration, for example: configuration Example param([PSCredential] $UserAccount). Please correct the input and retry executing the extension. More information on troubleshooting is available at https://aka.ms/VMExtensionDSCWindowsTroubleshoot
This does not help!
I have been trying to solve this error for a couple of days. I have Googled for other example but can only find example of people deploying Web Server and Microsoft's documentation is no help because it tells you to use both of the above methods. When method 1 is the old way (according to Microsoft). So, any help will be much appreciated.
this is how I was setting up parameter in the configuration:
# Credentials
[Parameter(Mandatory)]
[System.Management.Automation.PSCredential]$Admincreds,
and then in the template:
"properties": {
"publisher": "Microsoft.Powershell",
"type": "DSC",
"typeHandlerVersion": "2.19",
"autoUpgradeMinorVersion": true,
"settings": {
"configuration": xxx // doesn't matter for this question
"configurationArguments": yyy // doesn't matter for this question
},
"protectedSettings": {
"configurationArguments": {
"adminCreds": {
"userName": "someValue",
"password": "someOtherValue"
}
}
}
}
Links to working stuff:
https://github.com/Cloudneeti/PCI_Reference_Architecture/blob/master/templates/resources/AD/azuredeploy.json#L261
https://github.com/Cloudneeti/PCI_Reference_Architecture/blob/master/artifacts/configurationscripts/ad-domain.ps1#L11
ps. you might also need to do this. Honestly, I dont remember ;)

How to run a PowerShell script during Azure VM deployment with ARM template?

I want to deploy a VM in azure using Azure Resource Manager (ARM), and then run a PowerShell script inside the VM post deployment to configure it.
I can do this fine with something like this: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vm-vsts-agent
However that template grabs the PowerShell script from GitHub. As part of my deployment I want to upload the script to Azure Storage, and then have the VM get the script from Azure storage and run it. How can I do that part with regards to dependencies on the PowerShell script, because it has to exist in Azure Storage somewhere before being executed.
I currently have this to install a VSTS Agent as part of a deployment, but the script is downloaded from GitHub, I don't want to do that, I want the installation script of the VSTS Agent to be part of my ARM Project.
{
"name": "vsts-build-agents",
"type": "extensions",
"location": "[parameters('location')]",
"apiVersion": "2017-12-01",
"dependsOn": [
"vsts-build-vm"
],
"tags": {
"displayName": "VstsInstallScript"
},
"properties": {
"publisher": "Microsoft.Compute",
"type": "CustomScriptExtension",
"typeHandlerVersion": "1.9",
"settings": {
"fileUris": [
"[concat(parameters('_artifactsLocation'), '/', variables('powerShell').folder, '/', variables('powerShell').script, parameters('_artifactsLocationSasToken'))]"
]
},
"protectedSettings": {
"commandToExecute": "[concat('powershell.exe -ExecutionPolicy Unrestricted -Command \"& {', './', variables('powerShell').script, ' ', variables('powerShell').buildParameters, '}\"')]"
}
}
}
I guess my question is really about how to set _azurestoragelocation to an azure storage location where the script has just been uploaded as part of the deployment.
chicken\egg problem. you cannot upload to azure storage with arm template, you need to use script to upload to azure storage, but if you have that script on vm to upload it you dont really need to upload it.
that being said, why dont you use VSTS agent extension?
{
"name": "xxx",
"apiVersion": "2015-01-01",
"type": "Microsoft.Resources/deployments",
"properties": {
"mode": "Incremental",
"templateLink": {
"uri": "https://gallery.azure.com/artifact/20161101/microsoft.vsts-agent-windows-arm.1.0.0/Artifacts/MainTemplate.json"
},
"parameters": {
"vmName": {
"value": "xxx"
},
"location": {
"value": "xxx"
},
"VSTSAccountName": {
"value": "xxx"
},
"TeamProject": {
"value": "xxx"
},
"DeploymentGroup": {
"value": "Default"
},
"AgentName": {
"value": "xxx"
},
"PATToken": {
"value": "xxx"
}
}
}
},
Do you mean how to set _artifactsLocation as in the quickstart sample? If so you have 2 options (or 3 depending)
1) use the script in the QS repo, the defaultValue for the _artifactsLocation param will set that for you...
2) if you want to customize, from your local copy of the sample, just use the Deploy-AzureResourceGroup.ps1 in the repo and it will stage and set the value for you accordingly (when you use the -UploadArtifacts switch)
3) stage the PS1 somewhere yourself and manually set the values of _artifactsLocation and _artifactsLocationSasToken
You can also deploy from gallery.azure.com, but that will force you to use the script that is stored in the galley (same as using the defaults in GitHub)
That help?

Azure powershell cmdlet for creating Azure Service bus queue and topics

Is there any Azure powershell cmdlets for creating and managing Azure Service bus Queue and Topics?
The following link does not provide this:
http://msdn.microsoft.com/library/windowsazure/jj983731.aspx
Microsoft is planning to release this soon?
There currently are not PowerShell cmdlets for Service Bus queues and topics. They do have Cmdlets for creating the namespaces and some of the ACS entities, but not brokered messaging yet. The Azure cross-platform command line tool has the same capabilities.
You can monitor what's in the PowerShell Cmdlets, or even see pre-release bits on Windows Azure SDK-Tools repo on GitHub. This is a public repo of the code that makes up the PowerShell Cmdlets.
I've seen no public announcements about if/when this functionality will be added to the Cmdlets or the CLI tools.
Some documentation about this scenario was recently added:
http://azure.microsoft.com/en-us/documentation/articles/service-bus-powershell-how-to-provision/
The summary is that there are only a limited number of PowerShell cmdlets that relate to Service Bus. However, you can reference the NuGet packages and use the types there to do anything that is available in the client libraries.
Save the given below template in json file and execute the given below powershell command
----------------------------------------------------------------
param(
[Parameter(Mandatory=$True)]
[string]
$resourceGroupName,
[string]
$resourceGroupLocation,
[Parameter(Mandatory=$True)]
[string]
$templateFilePath = "C:\ARM-ServiceBus\sb_template.json",
[string]
$parametersFilePath = "C:\ARM-ServiceBus\sb_parameters.json"
)
#***********************************************************************
# Script body
# Execution begins here
#***********************************************************************
$ErrorActionPreference = "Stop"
$subscriptionId ='1234-545-474f-4544-5454454545'
# sign in
Write-Host "Logging in...";
Login-AzureRmAccount;
# select subscription
Write-Host "Selecting subscription '$subscriptionId'";
Select-AzureRmSubscription -SubscriptionID $subscriptionId;
#Create or check for existing resource group
$resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName -
ErrorAction SilentlyContinue
if(!$resourceGroup)
{
Write-Host "Resource group '$resourceGroupName' does not exist. To
create a new resource group, please enter a location.";
if(!$resourceGroupLocation) {
$resourceGroupLocation = Read-Host "resourceGroupLocation";
}
Write-Host "Creating resource group '$resourceGroupName' in location
'$resourceGroupLocation'";
New-AzureRmResourceGroup -Name $resourceGroupName -Location
$resourceGroupLocation
}
else{
Write-Host "Using existing resource group '$resourceGroupName'";
}
# Start the deployment
Write-Host "Starting deployment...";
if(Test-Path $parametersFilePath) {
New-AzureRmResourceGroupDeployment -ResourceGroupName
$resourceGroupName -TemplateFile $templateFilePath -
TemplateParameterFile $parametersFilePath;
} else {
New-AzureRmResourceGroupDeployment -ResourceGroupName
$resourceGroupName -TemplateFile $templateFilePath;
}
--------------Template(sb_template.json)--------------------------
{
"$schema": "http://schema.management.azure.com/schemas/2014-04-01-
preview/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"serviceBusNamespaceName": {
"type": "string",
"metadata": {
"description": "Name of the Service Bus namespace"
}
},
"serviceBusQueueName": {
"type": "string",
"metadata": {
"description": "Name of the Queue"
}
},
"serviceBusApiVersion": {
"type": "string",
"defaultValue": "2015-08-01",
"metadata": {
"description": "Service Bus ApiVersion used by the template"
}
}
},
"variables": {
"location": "[resourceGroup().location]",
"sbVersion": "[parameters('serviceBusApiVersion')]",
"defaultSASKeyName": "RootManageSharedAccessKey",
"authRuleResourceId": "
[resourceId('Microsoft.ServiceBus/namespaces/authorizationRules',
parameters('serviceBusNamespaceName'),
variables('defaultSASKeyName'))]"
},
"resources": [{
"apiVersion": "[variables('sbVersion')]",
"name": "[parameters('serviceBusNamespaceName')]",
"type": "Microsoft.ServiceBus/Namespaces",
"location": "[variables('location')]",
"kind": "Messaging",
"sku": {
"name": "StandardSku",
"tier": "Standard",
"capacity": 1
},
"resources": [{
"apiVersion": "[variables('sbVersion')]",
"name": "[parameters('serviceBusQueueName')]",
"type": "Queues",
"dependsOn": [
"[concat('Microsoft.ServiceBus/namespaces/', parameters('serviceBusNamespaceName'))]"
],
"properties": {
"path": "[parameters('serviceBusQueueName')]"
}
}]
}],
"outputs": {
"NamespaceConnectionString": {
"type": "string",
"value": "[listkeys(variables('authRuleResourceId'), variables('sbVersion')).primaryConnectionString]"
},
"SharedAccessPolicyPrimaryKey": {
"type": "string",
"value": "[listkeys(variables('authRuleResourceId'), variables('sbVersion')).primaryKey]"
}
}
}