Skip to content

Commit

Permalink
[Modules] Updated Compute/VirtualMachines to new dependency approach (#…
Browse files Browse the repository at this point in the history
…1822)

* [Modules] Updated Compute/VirtualMachines to new dependency approach

* Restored VM

* Update to latest

* Update to latest

* Updated SSH ref

* introduced ssh key name var

* Minor rename

* Adjusted SSH handling, updated role assignments, update readme generation to cut out dependsOn for bicep examples

* Script update

* Converted to SSH output

* Update to latest

* Updated readme error handling

* Updated RBAC

* Update to latest

* Apply suggestions from code review
  • Loading branch information
AlexanderSehr authored Oct 19, 2022
1 parent f06faee commit 317cdde
Show file tree
Hide file tree
Showing 23 changed files with 2,165 additions and 1,132 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/ms.compute.virtualmachines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,7 @@ jobs:
- name: 'Using test file [${{ matrix.moduleTestFilePaths }}]'
uses: ./.github/actions/templates/validateModuleDeployment
with:
templateFilePath: '${{ env.modulePath }}/deploy.bicep'
parameterFilePath: '${{ env.modulePath }}/${{ matrix.moduleTestFilePaths }}'
templateFilePath: '${{ env.modulePath }}/${{ matrix.moduleTestFilePaths }}'
location: '${{ env.location }}'
resourceGroupName: '${{ env.resourceGroupName }}'
subscriptionId: '${{ secrets.ARM_SUBSCRIPTION_ID }}'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
param(
[string] $SSHKeyName,
[string] $ResourceGroupName
)

if (-not ($sshKey = Get-AzSshKey -ResourceGroupName $ResourceGroupName | Where-Object { $_.Name -eq $SSHKeyName })) {
Write-Verbose "No SSH key [$SSHKeyName] found in Resource Group [$ResourceGroupName]. Generating new." -Verbose
$null = ssh-keygen -f generated -N (Get-Random -Maximum 99999)
$publicKey = Get-Content 'generated.pub' -Raw
# $privateKey = cat generated | Out-String
} else {
Write-Verbose "SSH key [$SSHKeyName] found in Resource Group [$ResourceGroupName]. Returning." -Verbose
$publicKey = $sshKey.publicKey
}
# Write into Deployment Script output stream
$DeploymentScriptOutputs = @{
# Requires conversion as the script otherwise returns an object instead of the plain public key string
publicKey = ($publicKey | ConvertTo-Json | ConvertFrom-Json).Value
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
param(
[string] $StorageAccountName,
[string] $ResourceGroupName,
[string] $ContainerName,
[string] $FileName
)

Write-Verbose "Create file [$FileName]" -Verbose
$file = New-Item -Value "Write-Host 'I am content'" -Path $FileName -Force

Write-Verbose "Getting storage account [$StorageAccountName|$ResourceGroupName] context." -Verbose
$storageAccount = Get-AzStorageAccount -ResourceGroupName $ResourceGroupName -StorageAccountName $StorageAccountName -ErrorAction 'Stop'

Write-Verbose 'Uploading file [$fileName]' -Verbose
Set-AzStorageBlobContent -File $file.FullName -Container $ContainerName -Context $storageAccount.Context -Force -ErrorAction 'Stop' | Out-Null
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
@description('Required. The name of the Virtual Network to create.')
param virtualNetworkName string

@description('Required. The name of the Managed Identity to create.')
param managedIdentityName string

@description('Required. The name of the Deployment Script to create for the SSH Key generation.')
param sshDeploymentScriptName string

@description('Required. The name of the SSH Key to create.')
param sshKeyName string

@description('Optional. The location to deploy resources to.')
param location string = resourceGroup().location

resource virtualNetwork 'Microsoft.Network/virtualNetworks@2022-01-01' = {
name: virtualNetworkName
location: location
properties: {
addressSpace: {
addressPrefixes: [
'10.0.0.0/24'
]
}
subnets: [
{
name: 'defaultSubnet'
properties: {
addressPrefix: '10.0.0.0/24'
}
}
]
}
}

resource managedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = {
name: managedIdentityName
location: location
}

resource msiRGContrRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid('msi-${resourceGroup().id}-${location}-${managedIdentity.id}-ResourceGroup-Reader-RoleAssignment')
scope: resourceGroup()
properties: {
principalId: managedIdentity.properties.principalId
roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c') // Contributor
principalType: 'ServicePrincipal'
}
}

resource sshDeploymentScript 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
name: sshDeploymentScriptName
location: location
kind: 'AzurePowerShell'
identity: {
type: 'UserAssigned'
userAssignedIdentities: {
'${managedIdentity.id}': {}
}
}
properties: {
azPowerShellVersion: '6.2.1'
retentionInterval: 'P1D'
arguments: ' -SSHKeyName "${sshKeyName}" -ResourceGroupName "${resourceGroup().name}"'
scriptContent: loadTextContent('../.scripts/New-SSHKey.ps1')
}
dependsOn: [
msiRGContrRoleAssignment
]
}

resource sshKey 'Microsoft.Compute/sshPublicKeys@2022-03-01' = {
name: sshKeyName
location: location
properties: {
publicKey: sshDeploymentScript.properties.outputs.publicKey
}
}

@description('The resource ID of the created Virtual Network Subnet')
output subnetResourceId string = virtualNetwork.properties.subnets[0].id

@description('The resource ID of the created SSH Key')
output SSHKeyResourceID string = sshKey.id

@description('The Public Key of the created SSH Key')
output SSHKey string = sshKey.properties.publicKey
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
targetScope = 'subscription'

// ========== //
// Parameters //
// ========== //
@description('Optional. The name of the resource group to deploy for testing purposes.')
@maxLength(80)
param resourceGroupName string = 'ms.compute.virtualMachines-${serviceShort}-rg'

@description('Optional. The location to deploy resources to.')
param location string = deployment().location

@description('Optional. A short identifier for the kind of deployment. Should be kept short to not run into resource-name length-constraints.')
param serviceShort string = 'cvmlinatmg'

// =========== //
// Deployments //
// =========== //

// General resources
// =================
resource resourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' = {
name: resourceGroupName
location: location
}

module resourceGroupResources 'dependencies.bicep' = {
scope: resourceGroup
name: '${uniqueString(deployment().name, location)}-nestedDependencies'
params: {
location: location
virtualNetworkName: 'dep-<<namePrefix>>-vnet-${serviceShort}'
sshDeploymentScriptName: 'dep-<<namePrefix>>-ds-${serviceShort}'
sshKeyName: 'dep-<<namePrefix>>-ssh-${serviceShort}'
managedIdentityName: 'dep-<<namePrefix>>-msi-${serviceShort}'
}
}

// ============== //
// Test Execution //
// ============== //

// resource sshKey 'Microsoft.Compute/sshPublicKeys@2022-03-01' existing = {
// name: sshKeyName
// scope: resourceGroup
// }

module testDeployment '../../deploy.bicep' = {
scope: resourceGroup
name: '${uniqueString(deployment().name)}-test-${serviceShort}'
params: {
location: location
name: '<<namePrefix>>${serviceShort}'
adminUsername: 'localAdminUser'
imageReference: {
offer: 'UbuntuServer'
publisher: 'Canonical'
sku: '18.04-LTS'
version: 'latest'
}
nicConfigurations: [
{
ipConfigurations: [
{
name: 'ipconfig01'
pipConfiguration: {
publicIpNameSuffix: '-pip-01'
}
subnetResourceId: resourceGroupResources.outputs.subnetResourceId
}
]
nicSuffix: '-nic-01'
}
]
osDisk: {
diskSizeGB: '128'
managedDisk: {
storageAccountType: 'Premium_LRS'
}
}
osType: 'Linux'
vmSize: 'Standard_B12ms'
configurationProfile: '/providers/Microsoft.Automanage/bestPractices/AzureBestPracticesProduction'
disablePasswordAuthentication: true
publicKeys: [
{
keyData: resourceGroupResources.outputs.SSHKey
path: '/home/localAdminUser/.ssh/authorized_keys'
}
]
}
dependsOn: [
resourceGroupResources // Required to leverage `existing` SSH key reference
]
}

This file was deleted.

This file was deleted.

Loading

0 comments on commit 317cdde

Please sign in to comment.