Skip to content

Commit

Permalink
Add skip_build_key_vault_create to skip build Keyvault create during …
Browse files Browse the repository at this point in the history
…window builds (#393)

* Add skip_create_build_key_vault

---------

Co-authored-by: Jenna Goldstrich <jenna.goldstrich@hashicorp.com>
Co-authored-by: Jenna Goldstrich <jenna.goldstrich2@gmail.com>
Co-authored-by: Lucas Bajolet <lucas.bajolet@hashicorp.com>
  • Loading branch information
4 people committed May 22, 2024
1 parent 37e4d3f commit 04e2be0
Show file tree
Hide file tree
Showing 14 changed files with 672 additions and 22 deletions.
11 changes: 11 additions & 0 deletions .web-docs/components/builder/arm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,17 @@ Providing `temp_resource_group_name` or `location` in combination with
- `build_key_vault_sku` (string) - Specify the KeyVault SKU to create during the build. Valid values are
standard or premium. The default value is standard.

- `skip_create_build_key_vault` (bool) - Skip creating the build key vault during Windows build.
This is useful for cases when a subscription has policy restrictions on key vault resources.
If true, you have to provide an alternate method to setup WinRM.
You can find examples of this in the `example/windows_skip_key_vault` directory.
These examples provide a minimal setup needed to get a working solution with the `skip_create_build_key_vault` flag.
This script may require changes depending on the version of Windows used,
or if any changes are made to the existing versions of Windows that impact creation of a WinRM listener.
For more information about custom scripts or user data, please refer to the docs:
* [Custom Script documentation](https://docs.microsoft.com/en-us/azure/virtual-machines/extensions/custom-script-windows)
* [User Data for Azure VM documentation](https://learn.microsoft.com/en-us/azure/virtual-machines/user-data)

- `disk_encryption_set_id` (string) - Specify the Disk Encryption Set ID to use to encrypt the OS and data disks created with the VM during the build
Only supported when publishing to Shared Image Galleries, without a managed image
The disk encryption set ID can be found in the properties tab of a disk encryption set on the Azure Portal, and is labeled as its resource ID
Expand Down
14 changes: 11 additions & 3 deletions builder/azure/arm/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,10 @@ func (b *Builder) Run(ctx context.Context, ui packersdk.Ui, hook packersdk.Hook)
NewStepGetSourceImageName(azureClient, ui, &b.config, generatedData),
NewStepCreateResourceGroup(azureClient, ui),
}
if b.config.BuildKeyVaultName == "" {

if b.config.SkipCreateBuildKeyVault {
ui.Message("Skipping build keyvault creation...")
} else if b.config.BuildKeyVaultName == "" {
keyVaultDeploymentName := b.stateBag.Get(constants.ArmKeyVaultDeploymentName).(string)
steps = append(steps,
NewStepValidateTemplate(azureClient, ui, &b.config, keyVaultDeploymentName, GetCommunicatorSpecificKeyVaultDeployment),
Expand All @@ -366,9 +369,14 @@ func (b *Builder) Run(ctx context.Context, ui packersdk.Ui, hook packersdk.Hook)

steps = append(steps, NewStepCertificateInKeyVault(azureClient, ui, &b.config, secret, b.config.WinrmExpirationTime))
}

if !b.config.SkipCreateBuildKeyVault {
steps = append(steps,
NewStepGetCertificate(azureClient, ui),
NewStepSetCertificate(&b.config, ui),
)
}
steps = append(steps,
NewStepGetCertificate(azureClient, ui),
NewStepSetCertificate(&b.config, ui),
NewStepValidateTemplate(azureClient, ui, &b.config, deploymentName, getVirtualMachineDeploymentFunction),
NewStepDeployTemplate(azureClient, ui, &b.config, deploymentName, getVirtualMachineDeploymentFunction, VirtualMachineTemplate),
NewStepGetIPAddress(azureClient, ui, endpointConnectType),
Expand Down
16 changes: 16 additions & 0 deletions builder/azure/arm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,18 @@ type Config struct {
// standard or premium. The default value is standard.
BuildKeyVaultSKU string `mapstructure:"build_key_vault_sku"`

// Skip creating the build key vault during Windows build.
// This is useful for cases when a subscription has policy restrictions on key vault resources.
// If true, you have to provide an alternate method to setup WinRM.
// You can find examples of this in the `example/windows_skip_key_vault` directory.
// These examples provide a minimal setup needed to get a working solution with the `skip_create_build_key_vault` flag.
// This script may require changes depending on the version of Windows used,
// or if any changes are made to the existing versions of Windows that impact creation of a WinRM listener.
// For more information about custom scripts or user data, please refer to the docs:
// * [Custom Script documentation](https://docs.microsoft.com/en-us/azure/virtual-machines/extensions/custom-script-windows)
// * [User Data for Azure VM documentation](https://learn.microsoft.com/en-us/azure/virtual-machines/user-data)
SkipCreateBuildKeyVault bool `mapstructure:"skip_create_build_key_vault" required:"false"`

// Specify the Disk Encryption Set ID to use to encrypt the OS and data disks created with the VM during the build
// Only supported when publishing to Shared Image Galleries, without a managed image
// The disk encryption set ID can be found in the properties tab of a disk encryption set on the Azure Portal, and is labeled as its resource ID
Expand Down Expand Up @@ -1269,6 +1281,10 @@ func assertRequiredParametersSet(c *Config, errs *packersdk.MultiError) {
}
}

if c.SkipCreateBuildKeyVault && !strings.EqualFold(c.Comm.Type, "winrm") {
errs = packer.MultiErrorAppend(errs, fmt.Errorf("Communicator type must be winrm when skip_create_build_key_vault is set"))
}

/////////////////////////////////////////////
// Deployment
xor := func(a, b bool) bool {
Expand Down
2 changes: 2 additions & 0 deletions builder/azure/arm/config.hcl2spec.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion builder/azure/arm/template_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ func GetVirtualMachineTemplateBuilder(config *Config) (*template.TemplateBuilder
}
case constants.Target_Windows:
osType = hashiVMSDK.OperatingSystemTypesWindows
err = builder.BuildWindows(config.Comm.Type, config.tmpKeyVaultName, config.tmpWinRMCertificateUrl)
err = builder.BuildWindows(config.Comm.Type, config.tmpKeyVaultName, config.tmpWinRMCertificateUrl, config.SkipCreateBuildKeyVault)
if err != nil {
return nil, err
}
Expand Down
36 changes: 23 additions & 13 deletions builder/azure/common/template/template_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (s *TemplateBuilder) BuildLinux(sshAuthorizedKey string, disablePasswordAut
return nil
}

func (s *TemplateBuilder) BuildWindows(communicatorType string, keyVaultName string, certificateUrl string) error {
func (s *TemplateBuilder) BuildWindows(communicatorType string, keyVaultName string, certificateUrl string, skipCreateKV bool) error {
resource, err := s.getResourceByType(resourceVirtualMachine)
if err != nil {
return err
Expand All @@ -102,24 +102,34 @@ func (s *TemplateBuilder) BuildWindows(communicatorType string, keyVaultName str
}

provisionVMAgent := true
basicWindowConfiguration := hashiVMSDK.WindowsConfiguration{
ProvisionVMAgent: &provisionVMAgent,
}

if communicatorType == "ssh" {
profile.WindowsConfiguration = &hashiVMSDK.WindowsConfiguration{
ProvisionVMAgent: &provisionVMAgent,
}
profile.WindowsConfiguration = &basicWindowConfiguration
return nil
}

protocol := hashiVMSDK.ProtocolTypesHTTPS
profile.WindowsConfiguration = &hashiVMSDK.WindowsConfiguration{
ProvisionVMAgent: common.BoolPtr(true),
WinRM: &hashiVMSDK.WinRMConfiguration{
Listeners: &[]hashiVMSDK.WinRMListener{
{
Protocol: &protocol,
CertificateUrl: common.StringPtr(certificateUrl),
// when communicator type is winrm
if !skipCreateKV {
// when skip kv create is not set, add secrets and listener
protocol := hashiVMSDK.ProtocolTypesHTTPS
profile.WindowsConfiguration = &hashiVMSDK.WindowsConfiguration{
ProvisionVMAgent: common.BoolPtr(true),
WinRM: &hashiVMSDK.WinRMConfiguration{
Listeners: &[]hashiVMSDK.WinRMListener{
{
Protocol: &protocol,
CertificateUrl: common.StringPtr(certificateUrl),
},
},
},
},
}
} else {
// when skip kv create is set, no need to add secrets and listener in template
profile.Secrets = nil
profile.WindowsConfiguration = &basicWindowConfiguration
}

return nil
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"adminPassword": {
"type": "securestring"
},
"adminUsername": {
"type": "string"
},
"commandToExecute": {
"type": "string"
},
"dataDiskName": {
"type": "string"
},
"dnsNameForPublicIP": {
"type": "string"
},
"nicName": {
"type": "string"
},
"nsgName": {
"type": "string"
},
"osDiskName": {
"type": "string"
},
"publicIPAddressName": {
"type": "string"
},
"storageAccountBlobEndpoint": {
"type": "string"
},
"subnetName": {
"type": "string"
},
"virtualNetworkName": {
"type": "string"
},
"vmName": {
"type": "string"
},
"vmSize": {
"type": "string"
}
},
"resources": [
{
"apiVersion": "[variables('networkApiVersion')]",
"location": "[variables('location')]",
"name": "[parameters('publicIPAddressName')]",
"properties": {
"dnsSettings": {
"domainNameLabel": "[parameters('dnsNameForPublicIP')]"
},
"publicIPAllocationMethod": "[variables('publicIPAddressType')]"
},
"type": "Microsoft.Network/publicIPAddresses"
},
{
"apiVersion": "[variables('networkApiVersion')]",
"location": "[variables('location')]",
"name": "[variables('virtualNetworkName')]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[variables('addressPrefix')]"
]
},
"subnets": [
{
"name": "[variables('subnetName')]",
"properties": {
"addressPrefix": "[variables('subnetAddressPrefix')]"
}
}
]
},
"type": "Microsoft.Network/virtualNetworks"
},
{
"apiVersion": "[variables('networkApiVersion')]",
"dependsOn": [
"[concat('Microsoft.Network/publicIPAddresses/', parameters('publicIPAddressName'))]",
"[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
],
"location": "[variables('location')]",
"name": "[parameters('nicName')]",
"properties": {
"ipConfigurations": [
{
"name": "ipconfig",
"properties": {
"privateIPAllocationMethod": "Dynamic",
"publicIPAddress": {
"id": "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddressName'))]"
},
"subnet": {
"id": "[variables('subnetRef')]"
}
}
}
]
},
"type": "Microsoft.Network/networkInterfaces"
},
{
"apiVersion": "[variables('computeApiVersion')]",
"dependsOn": [
"[concat('Microsoft.Network/networkInterfaces/', parameters('nicName'))]"
],
"location": "[variables('location')]",
"name": "[parameters('vmName')]",
"properties": {
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": false
}
},
"hardwareProfile": {
"vmSize": "[parameters('vmSize')]"
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces', parameters('nicName'))]"
}
]
},
"osProfile": {
"adminPassword": "[parameters('adminPassword')]",
"adminUsername": "[parameters('adminUsername')]",
"computerName": "[parameters('vmName')]",
"windowsConfiguration": {
"provisionVMAgent": true
}
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2012-R2-Datacenter",
"version": "latest"
},
"osDisk": {
"caching": "ReadWrite",
"createOption": "FromImage",
"name": "[parameters('osDiskName')]",
"vhd": {
"uri": "[concat(parameters('storageAccountBlobEndpoint'),variables('vmStorageAccountContainerName'),'/', parameters('osDiskName'),'.vhd')]"
}
}
}
},
"type": "Microsoft.Compute/virtualMachines"
},
{
"apiVersion": "[variables('computeApiVersion')]",
"condition": "[not(empty(parameters('commandToExecute')))]",
"dependsOn": [
"[resourceId('Microsoft.Compute/virtualMachines/', parameters('vmName'))]"
],
"location": "[variables('location')]",
"name": "[concat(parameters('vmName'), '/extension-customscript')]",
"properties": {
"autoUpgradeMinorVersion": true,
"publisher": "Microsoft.Compute",
"settings": {
"commandToExecute": "[parameters('commandToExecute')]"
},
"type": "CustomScriptExtension",
"typeHandlerVersion": "1.10"
},
"type": "Microsoft.Compute/virtualMachines/extensions"
}
],
"variables": {
"addressPrefix": "10.0.0.0/16",
"computeApiVersion": "2023-03-01",
"location": "[resourceGroup().location]",
"networkApiVersion": "2023-04-01",
"publicIPAddressType": "Dynamic",
"sshKeyPath": "[concat('/home/',parameters('adminUsername'),'/.ssh/authorized_keys')]",
"subnetAddressPrefix": "10.0.0.0/24",
"subnetName": "[parameters('subnetName')]",
"subnetRef": "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]",
"virtualNetworkName": "[parameters('virtualNetworkName')]",
"virtualNetworkResourceGroup": "[resourceGroup().name]",
"vmStorageAccountContainerName": "images",
"vnetID": "[resourceId(variables('virtualNetworkResourceGroup'), 'Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]"
}
}
Loading

0 comments on commit 04e2be0

Please sign in to comment.