我想在 terraform 中配置一个 Azure VM (Windows),通过 IIS 软件部署包安装 python、pip、java JDK 等。所有这些安装都应该通过命令或脚本完成。这些脚本应该与配置文件一起使用,我可以在其中为 PowerShell 参数提供变量或参数,配置文件位于存储库中。
经过一番研究,我找到了 3 种继续进行配置的方法。
选择参数:
在 Azure VM terraform 中选择哪个 - 自定义数据、VM 扩展资源或配置程序以通过命令安装包和软件
要在 VM
上安装
Python、pip 和 Java JDK,您可以使用
CustomScriptExtension
扩展运行脚本。要将软件部署到 IIS
,您可以使用 WebDeployExtension
扩展。
将
PowerShell script
保存到 Azure blob 并复制其 URL。然后,将 URL 粘贴到 fileUris
部分。
这是安装
PowerShell Script
的Python, pip, and Java JDK on the VM
。
脚本.ps1
New-Item -Type Directory -Path 'c:\' -Name Java
# JDK Instalation
invoke-webrequest -uri 'https://download.oracle.com/java/21/latest/jdk-21_windows-x64_bin.msi' -OutFile 'C:\Java\jdk-21_windows-x64_bin.msi'
Start-Process -FilePath 'c:\Java\jdk-21_windows-x64_bin.msi' /qn -Wait
# Python
Invoke-WebRequest -Uri "https://www.python.org/ftp/python/3.7.0/python-3.7.0.exe" -OutFile "C:\Java\python-3.7.0.exe"
c:/Java/python-3.7.0.exe /qn -Wait
# Install pip (included with Python)
python -m ensurepip
# Install IIS
Install-WindowsFeature -Name Web-Server -IncludeManagementTools
Terraform 脚本
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = "windows-resources"
location = "East US"
}
resource "azurerm_virtual_network" "example" {
name = "windows-network"
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
}
resource "azurerm_subnet" "example" {
name = "internal"
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example.name
address_prefixes = ["10.0.2.0/24"]
}
resource "azurerm_network_interface" "example" {
name = "windows-nic"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.example.id
private_ip_address_allocation = "Dynamic"
}
}
resource "azurerm_windows_virtual_machine" "example" {
name = "windows-machine"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
size = "Standard_DS1_v2"
admin_username = "adminuser"
admin_password = "P@$$w0rd1234!"
network_interface_ids = [
azurerm_network_interface.example.id,
]
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
encryption_at_host_enabled = true
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2016-Datacenter"
version = "latest"
}
}
resource "azurerm_virtual_machine_extension" "example" {
name = "customScript"
virtual_machine_id = azurerm_windows_virtual_machine.example.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
settings = <<SETTINGS
{
"fileUris": ["https://samplestoragevm.blob.core.windows.net/vmstorage/Script.ps1"],
"commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File Script.ps1"
}
SETTINGS
}
Terraform 应用: