Overview
In this article, we will explore how to create a Windows AMI on AWS using Packer in conjunction with Ansible. This process allows for automated image creation, making it easier to manage and deploy Windows instances.
Packer Configuration
Below is a sample Packer configuration file that defines the necessary parameters for building a Windows AMI:
{
"builders": [
{
"type": "amazon-ebs",
"access_key": "{{user `aws_access_key`}}",
"secret_key": "{{user `aws_secret_key`}}",
"region": "eu-west-1",
"source_ami": "ami-58a1a73e",
"instance_type": "m3.medium",
"ami_name": "my-windows-ami {{timestamp}}",
"user_data_file": "./init.ps",
"communicator": "winrm",
"winrm_username": "Administrator",
"winrm_use_ssl": true,
"winrm_insecure": true
}
],
"provisioners": [
{
"type": "ansible",
"playbook_file": "./playbook.yml",
"extra_arguments": [
"--extra-vars", "ansible_user=Administrator ansible_connection=winrm ansible_ssh_port=5986 ansible_winrm_server_cert_validation=ignore ansible_shell_type=powershell"
]
},
{
"type": "powershell",
"script": "./init.ps1"
}
]
}
User Data Script
The user data script (init.ps) is responsible for configuring WinRM on the AWS instance. Below is an example of what this script might look like:
<powershell>
# Output message indicating the script is running
write-output "Executing User Data Script"
# Set execution policy to allow script execution
Set-ExecutionPolicy Unrestricted -Scope LocalMachine -Force -ErrorAction Ignore
# Configure WinRM settings
Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse
Set-Item WSMan:\localhost\MaxTimeoutms 1800000
Set-Item WSMan:\localhost\Service\Auth\Basic $true
# Create a self-signed certificate for HTTPS
$Cert = New-SelfSignedCertificate -CertstoreLocation Cert:\LocalMachine\My -DnsName "packer"
New-Item -Path WSMan:\LocalHost\Listener -Transport HTTPS -Address * -CertificateThumbPrint $Cert.Thumbprint -Force
# Configure WinRM service
cmd.exe /c winrm quickconfig -q
cmd.exe /c winrm set "winrm/config" '@{MaxTimeoutms="1800000"}'
cmd.exe /c netsh advfirewall firewall set rule group="remote administration" new enable=yes
cmd.exe /c net start winrm
</powershell>
Troubleshooting Connection Issues
If you encounter connection errors during provisioning, such as:
==> amazon-ebs: Provisioning with Ansible...
amazon-ebs: fatal: [default]: UNREACHABLE! => {"msg": "ssl: auth method ssl requires a password", "unreachable": true}
This may indicate that the WinRM configuration is not set up correctly or that the credentials are not being passed properly. Ensure that the ansible_user and other connection parameters are correctly specified in your Packer configuration.
Conclusion
By following the steps outlined in this guide, you should be able to successfully create a Windows AMI using Packer and Ansible. If you continue to face issues, double-check your configurations and ensure that your AWS security groups allow the necessary traffic for WinRM.