简体   繁体   English

在Azure虚拟机中安装Azure PowerShell

[英]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. 我需要编写一个powershell工作流,用于创建Azure虚拟机并在该Azure虚拟机中执行一些azure cmdlet。 But the newly created VM has no azure powershell module installed in it. 但是新创建的VM没有安装azure powershell模块。 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. 我不应该手动获取该VM的rdp并打开它以安装Azure Powershell模块,而是使用powershell cmdlet动态创建VM,并使用PowerShell本身在该vm中安装azure模块。

This can easily be done with an ARM (Azure Resource Manager) template. 这可以使用ARM(Azure资源管理器)模板轻松完成。 This is a JSON template which defines objects to be deployed. 这是一个JSON模板,用于定义要部署的对象。 In your case, you would want to deploy a VM with a custom script extension. 在您的情况下,您可能希望部署具有自定义脚本扩展的VM。 Upon provisioning of the VM, the Azure Resource Manager will fetch the supplied files and run your custom powershell. 配置VM后,Azure资源管理器将获取提供的文件并运行自定义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. 请参阅下面的示例,并将您的blob和powershell脚本替换为https://<YOUR-BLOB-HERE>.blob.core.windows.net/resources/CUSTOM-POWERSHELL-SCRIPT.ps1 To run the script you can use Azure powershell, as described here: https://azure.microsoft.com/en-us/documentation/articles/powershell-azure-resource-manager/ 要运行脚本,您可以使用Azure powershell,如下所述: https//azure.microsoft.com/en-us/documentation/articles/powershell-azure-resource-manager/

The key cmdlet for your purposes is New-AzureResourceGroup. 用于您的目的的关键cmdlet是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 . 请参阅此处的ARM模板列表以供参考: https//github.com/Azure/azure-quickstart-templates Sample template to modify to run custom code/install Azure powershell. 要修改的示例模板以运行自定义代码/安装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. 如果您的VM具有PowerShell 5.0,则可以使用PowerShell库来安装模块。 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. 您需要做的就是像平常一样编写PowerShell脚本。 Just add the Module from PowerShell gallery using just one cmdlet. 只需使用一个cmdlet即可从PowerShell库添加模块。

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. 您可以使用Install-Module从库中安装模块,也可以使用Install-Script从PowerShell公共库中安装示例脚本。

You can even put your own modules in the gallery and install from there. 您甚至可以将自己的模块放在库中并从那里安装。

Reference: Get Started with the PowerShell Gallery 参考: PowerShell库入门

You may use Azure Automation service implementing your Powershell code into a runbook. 您可以使用Azure自动化服务将Runershell代码实现到Runbook中。

http://azure.microsoft.com/en-us/documentation/services/automation/ http://azure.microsoft.com/en-us/documentation/services/automation/

Though not a straight forward approach I implemented this idea that satisfied my need. 虽然不是一个直截了当的方法,但我实现了满足我需求的这个想法。

  1. Create a new azure VM from Portal and connect it through RDP https://azure.microsoft.com/en-in/documentation/articles/virtual-machines-windows-tutorial/ 从Portal创建一个新的azure VM并通过RDP连接它https://azure.microsoft.com/en-in/documentation/articles/virtual-machines-windows-tutorial/
  2. Now download azure powershell msi in YOUR machine ( In AzureVM downloading is blocked) http://az635501.vo.msecnd.net/azcopy-3-1-0/MicrosoftAzureStorageTools.msi 现在在你的机器上下载azure powershell msi(在AzureVM下载被阻止) http://az635501.vo.msecnd.net/azcopy-3-1-0/MicrosoftAzureStorageTools.msi
  3. Manually copy the msi file to the virtual machine and install it in that VM 手动将msi文件复制到虚拟机并将其安装在该VM中

  4. 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/ 现在捕获该VM的映像并将其上载到Azure中我的映像https://azure.microsoft.com/en-in/documentation/articles/virtual-machines-capture-image-windows-server/

  5. When I write automation script to create a VM, I used this newly created customVM image, where AzurePowershell is already installed 当我编写自动化脚本来创建VM时,我使用了这个新创建的customVM映像,其中已经安装了AzurePowershell

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM