Enable SSH into Windows Server with cloud-init

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.

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~
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'


Set-Acl -Path $AuthorizedKeyFile -AclObject $Acl

The local machine’s public SSH key is added to authorized_keys file as a template parameter.

comments powered by Disqus