Enable SSH into Windows Server with cloud-init
12-02-2021
When I had to bring up a Windows Server on AWS using the default Windows Server AMI recently, I needed a way to automatically configure the machine so it can be SSH-ed into without manual configuration. This was needed in order to run ansible on the machine after it was brought up by Terraform.
This could be done with cloud-init and a PowerShell script. The script would install OpenSSH server and configure the permissions for the authorized_keys
file to allow incoming SSH session for the Administrator
user.
<powershell>
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
$AuthorizedKeyFile = 'C:\ProgramData\ssh\administrators_authorized_keys'
New-Item $AuthorizedKeyFile
Set-Content $AuthorizedKeyFile '${authorized_keys}'
# Reset authorized_keys file ACL to enable SSH
# By default, it inherits parent folder permission, which is too permissive
$Acl = Get-Acl -Path $AuthorizedKeyFile
# disable inheritance
$isProtected = $true
$preserveInheritance = $false
$Acl.SetAccessRuleProtection($isProtected, $preserveInheritance)
$Administrators = 'BUILTIN\Administrators'
$System = 'SYSTEM'
$FullControl = 'FullControl'
$AdministratorAccessRule = New-Object Security.AccessControl.FileSystemAccessRule $Administrators, $FullControl, 'Allow'
$SystemAccessRule = New-Object Security.AccessControl.FileSystemAccessRule $System, $FullControl, 'Allow'
$Acl.SetAccessRule($AdministratorAccessRule)
$Acl.SetAccessRule($SystemAccessRule)
Set-Acl -Path $AuthorizedKeyFile -AclObject $Acl
</powershell>
The local machine’s public SSH key is added to authorized_keys
file as a template parameter.