-
Notifications
You must be signed in to change notification settings - Fork 61
/
Create_VM_with_Vault_Secrets.ps1
64 lines (46 loc) · 1.86 KB
/
Create_VM_with_Vault_Secrets.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Set-Location c:\
Clear-Host
Install-Module -Name Az -Force -AllowClobber -Verbose
#Basic variables
$location = "westeurope"
$resourceGroup = "myResourceGroup"
$vmName = "myVM"
#Log into Azure
Connect-AzAccount
#Select the correct subscription
Get-AzSubscription -SubscriptionName "Visual Studio Enterprise-Abonnement" | Select-AzSubscription
Get-AzContext
#Create a resource group
New-AzResourceGroup -Name $resourceGroup -Location $location
#region Azure Key Vault
#Create a Key Vault
New-AzKeyVault -Name 'tw-vault2020' -ResourceGroupName $resourceGroup -Location $location
#(Optional)Give your user account permissions to manage secrets in Key Vault
Set-AzKeyVaultAccessPolicy -VaultName tw-vault2020 -UserPrincipalName 'user@domain.com' -PermissionsToSecrets get,set,delete
#Adding a secret to Key Vault
$secretvalue = ConvertTo-SecureString 'hVFkk965BuUv' -AsPlainText -Force
$secret = Set-AzKeyVaultSecret -VaultName tw-vault2020 -Name 'SysadminSecret' -SecretValue $secretvalue
Get-AzKeyVaultSecret -VaultName 'tw-vault2020' -Name 'SysadminSecret' | Get-Member
(Get-AzKeyVaultSecret -VaultName 'tw-vault2020' -Name 'SysadminSecret').SecretValueText
#endregion
#Retreive sysadmin password from KeyVault
$pass = (Get-AzKeyVaultSecret -VaultName tw-vault2020 -Name SysadminSecret).SecretValue
#Build creds for local sysadmin
$u = 'sysadmin'
$cred = New-Object System.Management.Automation.PSCredential ($u, $pass)
#Create a virtual machine
$vmParams = @{
ResourceGroupName = $resourceGroup
Location = $location
Name = $vmName
ImageName = 'Win2016Datacenter'
VirtualNetworkName = 'myVnet'
SubnetName = 'mySubnet'
PublicIpAddressName = 'myPublicIp'
SecurityGroupName = "$VMName-SG"
OpenPorts = 80
Credential = $cred
}
New-AzVM @vmParams
#Clean Up
Remove-AzResourceGroup -Name $resourceGroup -Force