Azure powershell cmdlet for creating Azure Service bus queue and topics - powershell

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]"
}
}
}

Related

Azure ARM Template for runbook with Powershell file from Azure Git Repo

We are trying to deploy a runbook with Powershell that queries Log Analytics periodically. We have it working on the portal and now we are trying tobuild a ARM Template for doing future deployments to other environments. We have our ARM (json) template and the PS1 file in the same Azure Devops Git repo and we even tried hard coding the path of PS1 file in the template but it doesnt work. Can someone please help us here on what we are doing wrong. Following is the ARM Template:-
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"automationAccountName": {
"type": "string",
"defaultValue": "Automation-XXX-INFRA-MONITORING",
"metadata": {
"description": "Automation Account"
}
},
"automationRegion": {
"defaultValue": "eastus2",
"type": "string",
"allowedValues": [
"westeurope",
"southeastasia",
"eastus2",
"southcentralus",
"japaneast",
"northeurope",
"canadacentral",
"australiasoutheast",
"centralindia",
"westcentralus"
],
"metadata": {
"description": "Specify the region for your automation account"
}
},
"_artifactsLocation": {
"type": "string",
"defaultValue": "https://ABCD.visualstudio.com/3Pager/_git/Infrastructure?path=%2FAzure.Infra%2FAppInsights%2FMonthOverMonthTrendAnalysisReport.ps1&version=GBmaster",
"metadata": {
"description": "URI to artifacts location"
}
},
"_artifactsLocation1": {
"type": "string",
"defaultValue": "https://ABCD.visualstudio.com/3Pager/_git/Infrastructure?path=%2FAzure.Infra%2FAppInsights%2FMonthOverMonthTrendAnalysisReport.ps1&version=GBmaster",
"metadata": {
"description": "URI to artifacts location"
}
}
},
"variables": {
"asrScripts": {
"runbooks": [
{
"name": "Test_Runbook",
"url": "[parameters('_artifactsLocation')]",
"version": "1.0.0.0",
"type": "PowerShell",
"description": "Runbook for month over month trend analysis report"
}
]
}
},
"resources": [
{
"apiVersion": "2015-10-31",
"type": "Microsoft.Automation/automationAccounts/runbooks",
"name": "[concat(parameters('automationAccountName'), '/', variables('asrScripts').runbooks[copyIndex()].Name)]",
"location": "[parameters('automationRegion')]",
"copy": {
"name": "runbooksLoop",
"count": "[length(variables('asrScripts').runbooks)]"
},
"properties": {
"description": "[variables('asrScripts').runbooks[copyIndex()].description]",
"runbookType": "[variables('asrScripts').runbooks[copyIndex()].type]",
"logProgress": false,
"logVerbose": true,
"publishContentLink": {
"uri":"[parameters('_artifactsLocation1')]",
"version": "[variables('asrScripts').runbooks[copyIndex()].version]" }
}
}
],
"outputs": {}
}
You are sending a URI to ARM telling it where to find the runbooks. When the AutomationAccount/runbooks resource type is created it will make a GET call to the publishContentLink.url in order to get the content from the URI. If Azure can't access that URI (presumably your visualstudio.com URI is not publicly accessible) then it won't be able to access the runbook content and the deployment will fail.
The solution is to make sure the publishContentLink URI is something accessible to the Azure Automation service. You can do this a couple ways:
Put the content in a publicly accessible URI such as Github or a public Blob Storage container.
Create a SAS token to the content. https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-tutorial-secure-artifacts shows an example of how to do this with Azure Storage, or https://xebia.com/blog/setting-up-vsts-with-arm-templates/ for doing it with VSTS.
Leaving it here in case someone has similar issue. For a private Azure DevOps Repo it can be solved by Azure Function with HTTP trigger and following PowerShell script:
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Interact with query parameters or the body of the request.
$adouri = $Request.Query.adouri
$pat = $Request.Query.pat
if (!$adouri){
$response = "Please pass uri"
Write-Warning "URI not passed" -Warning
} elseif (!$pat){
$response = "Please pass pat"
Write-Warning "PAT not passed" -Warning
} else {
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$headers = #{
"Authorization" = ("Basic {0}" -f $base64AuthInfo)
}
$response = Invoke-RestMethod -Uri $adouri -Method Get -ContentType "application/text" -Headers $headers
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = [HttpStatusCode]::OK
Body = $response
})
Once the function is ready, it can be called then directly from ARM template, e.g.:
"variables": {
"runbookUri": "https://[function name].azurewebsites.net/api/[trigger name]?adouri=https://dev.azure.com/[ADO Organization]/[ADO project]/_apis/git/repositories/[Repo]/items?path=%2F[folder]%2F[subfolder]%2Fscript.ps1&pat=[token]"
},
"resources": [
{
"type": "Microsoft.Automation/automationAccounts/runbooks",
"apiVersion": "2018-06-30",
"name": "[name]",
"location": "[location]"
"properties": {
"runbookType": "PowerShell",
"logVerbose": false,
"logProgress": false,
"logActivityTrace": 0,
"publishContentLink": {
"uri": "[variables('runbookUri')]"
}
}
}]
Token is just the Personal Access Token from Azure DevOps. To keep it secured it can be passed to the ARM template from a secret ADO variable or Azure KeyVault.
I overcame this limitation by using Terraform templates. They offer the possibility to publish custom content into a runbook by using local paths. So you can do this either directly from the Git repository file system (your pc), or by linking an Azure Pipeline to your repository and using the file as an artifact.
If interested, check https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/automation_runbook in the "Example Usage - custom content".

Cannot pass an array type parameter in ARM template via Powershell

I have an ARM Template with the following parameters:
"parameters": {
"projectName": {
"type": "string",
"metadata": {
"description": "Name of the project"
}
},
"environmentName": {
"type": "string",
"defaultValue": "testing",
"metadata": {
"description": "Name/Type of the environment"
}
},
"vmResourceGroupName": {
"type": "string",
"metadata": {
"description": "Resource Group in which VMs wil be deployed"
}
},
"vmName": {
"type": "string",
"metadata": {
"description": "Name of the Virtual Machine"
}
},
"vmIPAddress": {
"type": "string",
"metadata": {
"description": "IP Address of the Virtual Machine"
}
},
"osDiskVhdUri": {
"type": "string",
"metadata": {
"description": "Uri of the existing VHD in ARM standard or premium storage"
}
},
"dataDiskVhdUri": {
"type": "array",
"metadata": {
"description": "Uri of the existing VHD in ARM standard or premium storage"
}
},
"vmSize": {
"type": "string",
"metadata": {
"description": "Size of the Virtual Machine"
}
},
"osType": {
"type": "string",
"allowedValues": [
"Windows",
"Linux"
],
"metadata": {
"description": "OS of the VM - Typically Windows or Linux"
}
},
"ManagedDisk": {
"type": "string",
"allowedValues": [
"Yes",
"No"
],
"metadata": {
"description": "Yes for Managed Disks, No for VHDs"
}
}
As evident, $dataDiskVHDURI is of type:array and I am trying to deploy the template using -TemplateParameterObject with New-AzureRMresourceGroupDeployment cmdlet in Powershell using the following code:
{
$vmWithDDTemplate = 'azuredeploy.json'
$vmWithoutDDTemplate = 'azuredeploy-withoutdd.json'
$dataDiskVhdUri = New-Object -TypeName System.Collections.ArrayList
$dataDiskVhdUri.Add("$VM.dataDiskVhduri")
#Creating VM param object
$VMTemplateObject = #{"projectname" = $projectName; `
"environmentname" = $environmentName; `
"vmResourceGroupName" = $vmResourceGroupName; `
"vmName" = $VM.vmName; `
"vmIPAddress" = $VM.vmIPAddress; `
"osDiskVhdUri" = $VM.osDiskVhdUri; `
"dataDiskVhdUri" = ,$dataDiskVhdUri; `
"vmSize" = $VM.vmSize; `
"osType" = $VM.osType; `
"ManagedDisk" = $VM.ManagedDisk
}
#$VMTemplateObject
# Checking if VM contains a data disk
if($VM.dataDiskVhdUri -ne $null)
{
Write Output "$VM contains data disk"
New-AzureRmResourceGroupDeployment -Name ('vmwithdd' + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) `
-ResourceGroupName $ResourceGroupName `
-TemplateParameterObject $VMTemplateObject `
-TemplateFile $vmWithDDTemplate `
-Force -Verbose -ErrorVariable ErrorMessages `
-ErrorAction Stop -DefaultProfile $azureCred
}
else
{
Write-output '$VM does not contain data disk'
}
}
However, I get the following error every time:
Microsoft.PowerShell.Utility\Write-Error : 4:46:14 PM - Error:
Code=InvalidTemplate; Message=Deployment template validation failed:
'The provided value for the template parameter 'dataDiskVhdUri' at
line '44' and column '27' is not valid.'. At Create-Environment:73
char:73
+
+ CategoryInfo : NotSpecified: (:) [Write-Error], RemoteException
+ FullyQualifiedErrorId : System.Management.Automation.RemoteException,Microsoft.PowerShell.Commands.WriteErrorCommand
+ PSComputerName : [localhost]
Does anyone know how to resolve this?
Not sure, but maybe feeding it with an ArrayList object wrapped in an array by use of the preceeding , is not what it wants. If i lookup examples, i see only single values added there like "dataDiskVhdUri" = $VM.dataDiskVhduri;
Try this:
$OptionalParameters = New-Object -TypeName Hashtable
$OptionalParameters.Add("aParam", #(1,2,3))
New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
-TemplateFile azuredeply.json `
#OptionalParameters
With:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"aParam": {
"type": "array"
}
},
"variables": { },
"resources": [ ],
"outputs": {
"dump": {
"type": "array",
"value": "[parameters('aParam')]"
}
}
}

How To Enable Azure Cosmos DB Preview Features (aggregation pipeline and Mongodbv3.4) via Powershell?

I would like to enable Aggregation Pipeline and MongoDBv3.4 preview features programmatically through AzureRM Powershell.
So far I've tried to do that through Azure ARM Template and Set-AzureRmResource command without any success.
Set-AzureRmResource:
$updateDBProperties = #{
"capabilities" = #(#{"Name" = "EnableAggregationPipeline"}, #{"Name"= "MongoDBv3.4"})
};
# also tried without luck
# $updateDBProperties = #{
# "capabilities" = #("EnableAggregationPipeline", "MongoDBv3.4")
# };
# won't work
Set-AzureRmResource -ResourceType "Microsoft.DocumentDb/databaseAccounts" `
-ApiVersion "2015-04-08" `
-ResourceGroupName "my-resource-group" `
-Name "my-cosmosdb-development" `
-Properties $updateDBProperties
Through arm template without luck:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"cosmosDBName": {
"type": "string"
},
"location": {
"type": "string"
},
"locations": {
"type": "array"
}
},
"variables": {},
"resources": [
{
"name": "[parameters('cosmosDBName')]",
"type": "Microsoft.DocumentDB/databaseAccounts",
"apiVersion": "2015-04-08",
"location": "[parameters('location')]",
"kind": "MongoDB",
"properties": {
"consistencyPolicy": {
"defaultConsistencyLevel": "Session",
"maxIntervalInSeconds": 5,
"maxStalenessPrefix": 100
},
"databaseAccountOfferType": "Standard",
"locations": "[array(parameters('locations'))]",
"capabilities": [
{
"name": "EnableAggregationPipeline"
},
{
"name": "MongoDBv3.4"
}
]
}
}
],
"outputs": {}
}
We load the arm template above through Powershell. The cosmos db get created but the preview features is not enabled:
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroup -TemplateFile $templateDirectory"/azureCosmosDB.json" -TemplateParameterObject $templateParameterObject -Name $templateParameterObject.cosmosDBName;
I succeeded to set these capabilities via the command line tool az:
az cosmosdb update \
--name my-resource-group \
--resource-group my-cosmosdb-deployment \
--capabilities "EnableAggregationPipeline" "MongoDBv3.4"
Though it took several minutes. Hope that helps!
This is achievable with PowerShell by patching the CosmosDB account resource. The key is to add the -UsePatchSemantics flag to Set-AzureRmResource so that it makes an HTTP PATCH request, rather than an HTTP PUT.
$db = Get-AzureRmResource -ResourceName "CosmosDB account name" -ResourceGroupName "RG name" | Where-Object -Property ResourceType -eq "Microsoft.DocumentDb/databaseAccounts"
# Enable some optional capabilities/features
$props = #{capabilities = #( #{name="EnableAggregationPipeline"}, #{name="MongoDBv3.4"})}
# Patch the resource with these settings
Set-AzureRmResource -ResourceId $db.ResourceId -ApiVersion "2015-04-08" -PropertyObject $props -UsePatchSemantics
To get this working as part of the ARM template, I had to change the apiVersion (2015-04-08, in your case) to something more recent:
"apiVersion": "2019-08-01",
For more information on apiVersion, you can review the MS documentation here.
However, this currently seems to only be working when initially creating the Cosmos DB with the feature enabled; So far, I didn't find a way to enable it after the resource has been initially provisioned.

Installing Azure powershell in an azure Virtual Machine

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

Apply tags to Azure resource group within resource template file

I'm using Powershell to create an Azure resource group from a template file and parameter file.
New-AzureResourceGroup -Name $groupName `
-TemplateFile $templateFile `
-TemplateParameterFile $paramFile `
-Location $location `
-Force -Verbose
Within the template I'm setting some tags on the resources within the group.
resourcegroup.json
"parameters": {
"environment": {
"type": "string",
"allowedValues": [
"Dev",
"Test",
"QA",
"Prod"
]}
}
....
"resources": [
{
...
"tags": {
"Environment": "[parameters('environment')]",
}
}
I'd like to apply the same tag values to the resource group itself, but I don't see a way to do that within the schema of the template file. Am I missing something?
Now at least, this is possible:
{
"type": "Microsoft.Resources/tags",
"name": "default",
"apiVersion": "2020-06-01",
"dependsOn": [
"resource1"
],
"properties": {
"tags": {
"Tag1": "Value1",
"Tag2": "Value2"
}
}
}
Documentation reference here
AFAIK, you have to use the azure Powershell command-let to add tags to your Azure Resource group. It cannot be done through the Template file.