Skip to content

Instantly share code, notes, and snippets.

@mefellows
Last active August 29, 2015 14:19
Show Gist options
  • Save mefellows/df5b4f3e1a11b28436de to your computer and use it in GitHub Desktop.
Save mefellows/df5b4f3e1a11b28436de to your computer and use it in GitHub Desktop.
Machine Factories with Windows Part 2: AWS Environments
log packer build -var base_ami=ami-9999eeee --var subnet_id=subnet-1234aaaa --var vpc_id=vpc-1111bbbb --var app_bundle=../publish/source.zip --var package_name=machine-factory-tutorial application.json
{
"variables": {
"build_version": "1.0.0",
"base_ami":"ami-3a3b1d52",
"user":"vagrant",
"password":"FooBar@123",
"instance_type":"t2.small",
"vpc_id":"",
"subnet_id":""
},
"builders": [
{
"type": "amazon-windows-ebs",
"name": "base-ami",
"region": "us-east-1",
"source_ami": "{{user `base_ami`}}",
"instance_type": "{{user `instance_type`}}",
"ami_name": "base-{{user `build_version`}}",
"user_data_file":"./scripts/ec2-bootstrap.ps1",
"associate_public_ip_address":false,
"winrm_username": "{{user `user`}}",
"winrm_password": "{{user `password`}}",
"winrm_wait_timeout": "20m",
"winrm_private_ip": true,
"winrm_port":5985,
"vpc_id": "{{user `vpc_id`}}",
"subnet_id": "{{user `subnet_id`}}"
}
],
"provisioners": [
{
"type": "powershell",
"elevated_user": "{{user `user`}}",
"elevated_password": "{{user `password`}}",
"scripts": [ "./scripts/provision.ps1" ]
},
{
"type":"powershell",
"scripts": [
"./scripts/Ec2Config.ps1"
]
}
]
}
packer build --var base_ami=ami-ac3a1cc4 --var subnet_id=subnet-1234abcd--var vpc_id=vpc-4567defg ./base.json
#r "System.Net.Http.dll"
#r "Build/packages/FAKE/tools/FakeLib.dll"
#r "Build/packages/FSharp.Data/lib/net40/FSharp.Data.dll"
open System
open System.IO
open System.Net
open System.Net.Http
open System.Text.RegularExpressions
open Fake
open Fake.AssemblyInfoFile
open FSharp.Data
open FSharp.Data.JsonExtensions
let projectName = "MachineFactoryTutorial"
let projectDescription = "Windows Machine Factory Tutorial"
let authors = ["mfellows"]
let applicationName = "Machine-Factory-Tutorial"
let packageName = applicationName.ToLowerInvariant()
let streamKey = "se"
// Paths
let testDir = "./test/"
let buildDir = "./buildTemp/"
let packagingRoot = "./packaging/"
let root = "./"
let deployDir = "./publish/"
let version = defaultArg TeamCityBuildNumber "0.0"
tracefn "Version: %s" version
RestorePackages()
// Targets
Target "Clean" (fun _ ->
CleanDirs [ testDir; buildDir; packagingRoot; deployDir ]
)
Target "RestorePackages" (fun _ ->
!! "**/ShortUrl*/packages.config"
|> Seq.iter (RestorePackage (fun p -> {p with OutputPath = "./packages"}))
)
Target "AssemblyInfo" (fun _ ->
CreateCSharpAssemblyInfo "./urlsvc/ShortUrlWebApp/Properties/AssemblyInfo.cs"
[Attribute.Title projectName
Attribute.Description projectDescription
Attribute.Guid "1acd961c-b169-44ce-84f9-ed8e3f95aeb1"
Attribute.Product projectName
Attribute.Version version
Attribute.FileVersion version]
)
Target "BuildWebApp" (fun _ ->
!! @"**/ShortUrlWebApp.csproj"
++ @"**/ShortUrl.csproj"
|> MSBuildRelease buildDir "Build"
|> Log "AppBuild-Output: "
)
let dependencies =
[ "seek-dsc-networking"
"seek-dsc-webadministration" ]
Target "CreatePackage" (fun _ ->
let packageDir = "./Build/packages/"
let autoDep x = x, GetPackageVersion packageDir x
let dependenciesWithVersion = dependencies |> List.map autoDep
projectName
|> sprintf "%s.nuspec"
|> NuGet (fun p ->
{p with
Authors = authors
Project = packageName
Description = projectDescription
OutputPath = deployDir
WorkingDir = root
Version = version
Dependencies = dependenciesWithVersion
Files = [(@"buildTemp/**", Some "lib", None)
(@"urlsvc/ShortUrlWebApp/modules/**/*", Some "dsc", None)
(@"urlsvc/ShortUrlWebApp/manifests/*", Some "dsc", None)
(@"urlsvc/ShortUrlWebApp/Install/*", Some "tools", None)]
Publish = false })
)
Target "CreateSourceZip" (fun _ ->
let copyPackage name =
let pkg = sprintf "**/%s*.nupkg" name
!! pkg
|> Copy deployDir
dependencies
|> List.iter copyPackage
!! (deployDir @@ "*.nupkg")
|> Zip deployDir (deployDir @@ "source.zip")
)
Target "All" DoNothing
//Target "RestorePackages" DoNothing
// Dependencies
"Clean"
==> "BuildWebApp"
==> "CreatePackage"
==> "CreateSourceZip"
==> "All"
// start build
RunTargetOrDefault "All"
packer build --var base_ami=AMI-FROMBASE--var subnet_id=subnet-1234abcd--var vpc_id=vpc-4567defg ./build-agent.json
# This is a workaround to deal with the fact that
# 1) New Chocolatey now sets the UI Culture to invariant
# 2) DSC Tries to Import-LocalizedData (line 57 of C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psm1)
# which uses implicit UI Culture, but of course is not available in this mode.
If ( -not ( Test-Path "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.Resource.psd1" ) ) {
cmd /c mklink C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.Resource.psd1 C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\en-US\PSDesiredStateConfiguration.Resource.psd1
}
$outputPath = $env:TEMP
$webAppPath = $(Join-Path $env:chocolateyPackageFolder "/lib/_PublishedWebsites/ShortUrlWebApp")
$modules = $(Join-Path $env:chocolateyPackageFolder "/dsc/")
$env:PSModulePath+=";${modules}"
# Dot source the configuration file
. $(Join-Path $env:chocolateyPackageFolder "/dsc/MyWebsite.ps1")
MyWebsite -Force -OutputPath $outputPath -MachineName "localhost" -WebAppPath $webAppPath | Out-Null
Start-DscConfiguration -Wait -Verbose -Path $outputPath -ErrorAction Stop
<powershell>
write-output "Running User Data Script"
write-host "(host) Running User Data Script"
# Also note, this user should be removed in Cfn Init
cmd.exe /c net user /add vagrant FooBar@123
cmd.exe /c net localgroup administrators vagrant /add
Set-ExecutionPolicy -ExecutionPolicy bypass -Force
# RDP
cmd.exe /c netsh advfirewall firewall add rule name="Open Port 3389" dir=in action=allow protocol=TCP localport=3389
cmd.exe /c reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
# WinRM
write-output "Setting up WinRM"
write-host "(host) setting up WinRM"
cmd.exe /c winrm quickconfig -q
cmd.exe /c winrm quickconfig '-transport:http'
cmd.exe /c winrm set "winrm/config" '@{MaxTimeoutms="1800000"}'
cmd.exe /c winrm set "winrm/config/winrs" '@{MaxMemoryPerShellMB="512"}'
cmd.exe /c winrm set "winrm/config/service" '@{AllowUnencrypted="true"}'
cmd.exe /c winrm set "winrm/config/client" '@{AllowUnencrypted="true"}'
cmd.exe /c winrm set "winrm/config/service/auth" '@{Basic="true"}'
cmd.exe /c winrm set "winrm/config/client/auth" '@{Basic="true"}'
cmd.exe /c winrm set "winrm/config/service/auth" '@{CredSSP="true"}'
cmd.exe /c winrm set "winrm/config/listener?Address=*+Transport=HTTP" '@{Port="5985"}'
cmd.exe /c netsh advfirewall firewall set rule group="remote administration" new enable=yes
cmd.exe /c netsh firewall add portopening TCP 5985 "Port 5985"
cmd.exe /c net stop winrm
cmd.exe /c sc config winrm start= auto
cmd.exe /c net start winrm
cmd.exe /c wmic useraccount where "name='vagrant'" set PasswordExpires=FALSE
</powershell>
$EC2SettingsFile="C:\\Program Files\\Amazon\\Ec2ConfigService\\Settings\\Config.xml"
$xml = [xml](get-content $EC2SettingsFile)
$xmlElement = $xml.get_DocumentElement()
$xmlElementToModify = $xmlElement.Plugins
foreach ($element in $xmlElementToModify.Plugin)
{
if ($element.name -eq "Ec2SetPassword")
{
$element.State="Enabled"
}
elseif ($element.name -eq "Ec2SetComputerName")
{
$element.State="Enabled"
}
elseif ($element.name -eq "Ec2HandleUserData")
{
$element.State="Enabled"
}
elseif ($element.name -eq "AWS.EC2.Windows.CloudWatch.PlugIn")
{
$element.State="Enabled"
}
}
$xml.Save($EC2SettingsFile)
(iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')))>$null 2>&1
choco install 7zip -y
choco install seek-dsc -y
# Disable Windows Updates
cmd /c reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v AUOptions /t REG_DWORD /d 1 /f
tzutil /s "AUS Eastern Standard Time"
Install-WindowsFeature Web-Server
Install-WindowsFeature Web-Mgmt-Tools
Install-WindowsFeature Web-App-Dev -IncludeAllSubFeature
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment