Last active
January 12, 2021 02:16
-
-
Save grenade/3115f926cbd425502b4af35e2a538dff to your computer and use it in GitHub Desktop.
import bb ami to tc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<powershell> | |
function Write-Log { | |
param ( | |
[string] $message, | |
[string] $severity = 'INFO', | |
[string] $source = 'OpenCloudConfig', | |
[string] $logName = 'Application' | |
) | |
if (!([Diagnostics.EventLog]::Exists($logName)) -or !([Diagnostics.EventLog]::SourceExists($source))) { | |
New-EventLog -LogName $logName -Source $source | |
} | |
switch ($severity) { | |
'DEBUG' { | |
$entryType = 'SuccessAudit' | |
$eventId = 2 | |
break | |
} | |
'WARN' { | |
$entryType = 'Warning' | |
$eventId = 3 | |
break | |
} | |
'ERROR' { | |
$entryType = 'Error' | |
$eventId = 4 | |
break | |
} | |
default { | |
$entryType = 'Information' | |
$eventId = 1 | |
break | |
} | |
} | |
Write-EventLog -LogName $logName -Source $source -EntryType $entryType -Category 0 -EventID $eventId -Message $message | |
} | |
function Remove-LegacyStuff { | |
param ( | |
[string[]] $users = @( | |
'cltbld' | |
), | |
[string[]] $paths = @( | |
('{0}\default_browser' -f $env:SystemDrive), | |
('{0}\etc' -f $env:SystemDrive), | |
('{0}\nxlog\conf\nxlog_*.conf' -f $env:ProgramFiles), | |
('{0}\opt' -f $env:SystemDrive), | |
('{0}\opt.zip' -f $env:SystemDrive), | |
('{0}\Puppet Labs' -f $env:ProgramFiles), | |
('{0}\PuppetLabs' -f $env:ProgramData), | |
('{0}\puppetagain' -f $env:ProgramData), | |
('{0}\slave' -f $env:SystemDrive), | |
('{0}\System32\Tasks\runner' -f $env:SystemRoot) | |
), | |
[string[]] $services = @( | |
'puppet' | |
), | |
[string[]] $scheduledTasks = @( | |
'"START RUNNER"', | |
'runner' | |
), | |
[string[]] $registryKeys = @( | |
'HKLM:\SOFTWARE\PuppetLabs' | |
), | |
[hashtable] $registryEntries = @{ | |
'DefaultUserName' = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'; | |
'DefaultPassword' = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'; | |
'AutoAdminLogon' = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' | |
}, | |
[hashtable] $ec2ConfigSettings = @{ | |
'Ec2HandleUserData' = 'Enabled'; | |
'Ec2InitializeDrives' = 'Disabled'; | |
'Ec2EventLog' = 'Disabled'; | |
'Ec2OutputRDPCert' = 'Disabled'; | |
'Ec2SetDriveLetter' = 'Disabled'; | |
'Ec2WindowsActivate' = 'Disabled'; | |
'Ec2SetPassword' = 'Disabled'; | |
'Ec2SetComputerName' = 'Disabled'; | |
'Ec2ConfigureRDP' = 'Disabled'; | |
'Ec2DynamicBootVolumeSize' = 'Disabled'; | |
'AWS.EC2.Windows.CloudWatch.PlugIn' = 'Disabled' | |
} | |
) | |
# clear the event log | |
wevtutil el | % { wevtutil cl $_ } | |
# remove scheduled tasks | |
foreach ($scheduledTask in $scheduledTasks) { | |
try { | |
Start-Process 'schtasks.exe' -ArgumentList @('/Delete', '/tn', $scheduledTask, '/F') -Wait -NoNewWindow -PassThru -RedirectStandardOutput ('{0}\log\{1}.schtask-{2}-delete.stdout.log' -f $env:SystemDrive, [DateTime]::Now.ToString("yyyyMMddHHmmss"), $scheduledTask) -RedirectStandardError ('{0}\log\{1}.schtask-{2}-delete.stderr.log' -f $env:SystemDrive, [DateTime]::Now.ToString("yyyyMMddHHmmss"), $scheduledTask) | |
Write-Log -message ('{0} :: scheduled task: {1}, deleted.' -f $($MyInvocation.MyCommand.Name), $scheduledTask) -severity 'INFO' | |
} | |
catch { | |
Write-Log -message ('{0} :: failed to delete scheduled task: {1}. {2}' -f $($MyInvocation.MyCommand.Name), $scheduledTask, $_.Exception.Message) -severity 'ERROR' | |
} | |
} | |
# remove user accounts | |
foreach ($user in $users) { | |
if (@(Get-WMiObject -class Win32_UserAccount | Where { $_.Name -eq $user }).length -gt 0) { | |
Start-Process 'logoff' -ArgumentList @((((quser /server:. | ? { $_ -match $user }) -split ' +')[2]), '/server:.') -Wait -NoNewWindow -PassThru -RedirectStandardOutput ('{0}\log\{1}.net-user-{2}-logoff.stdout.log' -f $env:SystemDrive, [DateTime]::Now.ToString("yyyyMMddHHmmss"), $user) -RedirectStandardError ('{0}\log\{1}.net-user-{2}-logoff.stderr.log' -f $env:SystemDrive, [DateTime]::Now.ToString("yyyyMMddHHmmss"), $user) | |
Start-Process 'net' -ArgumentList @('user', $user, '/DELETE') -Wait -NoNewWindow -PassThru -RedirectStandardOutput ('{0}\log\{1}.net-user-{2}-delete.stdout.log' -f $env:SystemDrive, [DateTime]::Now.ToString("yyyyMMddHHmmss"), $user) -RedirectStandardError ('{0}\log\{1}.net-user-{2}-delete.stderr.log' -f $env:SystemDrive, [DateTime]::Now.ToString("yyyyMMddHHmmss"), $user) | |
Write-Log -message ('{0} :: user: {1}, deleted.' -f $($MyInvocation.MyCommand.Name), $user) -severity 'INFO' | |
} | |
if (Test-Path -Path ('{0}\Users\{1}' -f $env:SystemDrive, $user) -ErrorAction SilentlyContinue) { | |
Remove-Item ('{0}\Users\{1}' -f $env:SystemDrive, $user) -confirm:$false -recurse:$true -force -ErrorAction SilentlyContinue | |
Write-Log -message ('{0} :: path: {1}, deleted.' -f $($MyInvocation.MyCommand.Name), ('{0}\Users\{1}' -f $env:SystemDrive, $user)) -severity 'INFO' | |
} | |
if (Test-Path -Path ('{0}\Users\{1}*' -f $env:SystemDrive, $user) -ErrorAction SilentlyContinue) { | |
Remove-Item ('{0}\Users\{1}*' -f $env:SystemDrive, $user) -confirm:$false -recurse:$true -force -ErrorAction SilentlyContinue | |
Write-Log -message ('{0} :: path: {1}, deleted.' -f $($MyInvocation.MyCommand.Name), ('{0}\Users\{1}*' -f $env:SystemDrive, $user)) -severity 'INFO' | |
} | |
} | |
# delete paths | |
foreach ($path in $paths) { | |
Remove-Item $path -confirm:$false -recurse:$true -force -ErrorAction SilentlyContinue | |
Write-Log -message ('{0} :: path: {1}, deleted.' -f $($MyInvocation.MyCommand.Name), $path) -severity 'INFO' | |
} | |
# delete services | |
foreach ($service in $services) { | |
if (Get-Service -Name $service -ErrorAction SilentlyContinue) { | |
Get-Service -Name $service | Stop-Service -PassThru | |
(Get-WmiObject -Class Win32_Service -Filter "Name='$service'").delete() | |
Write-Log -message ('{0} :: service: {1}, deleted.' -f $($MyInvocation.MyCommand.Name), $service) -severity 'INFO' | |
} | |
} | |
# remove registry keys | |
foreach ($registryKey in $registryKeys) { | |
Remove-Item -Path $registryKey -recurse | |
Write-Log -message ('{0} :: registry key: {1}, deleted.' -f $($MyInvocation.MyCommand.Name), $registryKey) -severity 'INFO' | |
} | |
# remove registry entries | |
foreach ($name in $registryEntries.Keys) { | |
$path = $registryEntries.Item($name) | |
$item = (Get-Item -Path $path) | |
if (($item -ne $null) -and ($item.GetValue($name) -ne $null)) { | |
Remove-ItemProperty -path $path -name $name | |
Write-Log -message ('{0} :: registry entry: {1}\{2}, deleted.' -f $($MyInvocation.MyCommand.Name), $path, $name) -severity 'INFO' | |
} | |
} | |
# reset ec2 config settings | |
$ec2ConfigSettingsFile = 'C:\Program Files\Amazon\Ec2ConfigService\Settings\Config.xml' | |
$ec2ConfigSettingsFileModified = $false; | |
[xml]$xml = (Get-Content $ec2ConfigSettingsFile) | |
foreach ($plugin in $xml.DocumentElement.Plugins.Plugin) { | |
if ($ec2ConfigSettings.ContainsKey($plugin.Name)) { | |
if ($plugin.State -ne $ec2ConfigSettings[$plugin.Name]) { | |
$plugin.State = $ec2ConfigSettings[$plugin.Name] | |
$ec2ConfigSettingsFileModified = $true | |
Write-Log -message ('{0} :: Ec2Config {1} set to: {2}, in: {3}' -f $($MyInvocation.MyCommand.Name), $plugin.Name, $plugin.State, $ec2ConfigSettingsFile) -severity 'INFO' | |
} | |
} | |
} | |
if ($ec2ConfigSettingsFileModified) { | |
& 'icacls' @($ec2ConfigSettingsFile, '/grant', 'Administrators:F') | |
& 'icacls' @($ec2ConfigSettingsFile, '/grant', 'System:F') | |
$xml.Save($ec2ConfigSettingsFile) | |
} | |
} | |
Write-Log -message 'userdata run starting.' -severity 'INFO' | |
tzutil /s UTC | |
Write-Log -message 'system timezone set to UTC.' -severity 'INFO' | |
W32tm /register | |
W32tm /resync /force | |
Write-Log -message 'system clock synchronised.' -severity 'INFO' | |
Remove-LegacyStuff | |
New-Item -ItemType Directory -Force -Path ('{0}\generic-worker' -f $env:SystemDrive) | |
(New-Object Net.WebClient).DownloadFile('https://github.com/taskcluster/generic-worker/releases/download/v7.1.3/generic-worker-windows-386.exe', ('{0}\generic-worker\generic-worker.exe' -f $env:SystemDrive)) | |
(New-Object Net.WebClient).DownloadFile('https://github.com/taskcluster/livelog/releases/download/v1.0.0/livelog-windows-386.exe', ('{0}\generic-worker\livelog.exe' -f $env:SystemDrive)) | |
& 'C:\generic-worker\generic-worker.exe' @('install', 'startup', '--config', 'C:\generic-worker\generic-worker.config') | |
(New-Object Net.WebClient).DownloadFile('https://raw.githubusercontent.com/mozilla-releng/OpenCloudConfig/master/userdata/Configuration/nxlog/win7.conf', ('{0}\nxlog\conf\nxlog.conf' -f $env:ProgramFiles)) | |
$env:USERDOMAIN = 'gecko-t-win7-32-alpha.mozilla.com' | |
[Environment]::SetEnvironmentVariable("USERDOMAIN", "$env:USERDOMAIN", "Machine") | |
Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\' -Name 'Domain' -Value "$env:USERDOMAIN" | |
Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\' -Name 'NV Domain' -Value "$env:USERDOMAIN" | |
Write-Log -message 'userdata run completed' -severity 'INFO' | |
</powershell> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
source_ami="${1}" | |
source_region='us-east-1' | |
target_region='us-west-2' | |
source_profile='releng-grenade' | |
target_profile='taskcluster' | |
if [ -z "$source_ami" ]; then | |
source_ami="$(aws ec2 describe-images --profile ${source_profile} --region ${source_region} --owners self --filters "Name=state,Values=available" "Name=name,Values=base-t-w732*" --query 'Images[*].{A:CreationDate,B:ImageId}' --output text | sort -u | tail -1 | cut -f2)" | |
fi | |
target_account_id='692406183521' | |
target_worker_type='gecko-t-win7-32' | |
target_instance_type='c4.2xlarge' | |
target_key="mozilla-taskcluster-worker-${target_worker_type}" | |
userdata_path='import-ami.ps1' | |
aws ec2 modify-image-attribute --profile ${source_profile} --region ${source_region} --image-id ${source_ami} --launch-permission "{\"Add\":[{\"UserId\":\"${target_account_id}\"}]}" | |
instance_id="$(aws ec2 run-instances --profile ${target_profile} --region ${source_region} --image-id "${source_ami}" --key-name ${target_key} --security-groups "ssh-only" "rdp-only" --user-data "$(cat ${userdata_path})" --instance-type ${target_instance_type} --block-device-mappings '[ {"DeviceName":"/dev/sda1","Ebs":{"VolumeSize":120,"VolumeType":"gp2","DeleteOnTermination":true}}, {"DeviceName":"/dev/sdb","VirtualName":"ephemeral0"}, {"DeviceName":"/dev/sdc","VirtualName":"ephemeral1"}]' --instance-initiated-shutdown-behavior stop --client-token "$(uuidgen)" | sed -n 's/^ *"InstanceId": "\(.*\)", */\1/p')" | |
aws ec2 create-tags --profile ${target_profile} --region ${source_region} --resources "${instance_id}" --tags "Key=WorkerType,Value=base-${target_worker_type}" | |
echo "$(date -Iseconds): instance: ${instance_id} instantiated and tagged: WorkerType=base-${target_worker_type}" | |
sleep 30 # give aws 30 seconds to start the instance | |
instance_public_ip="$(aws ec2 describe-instances --profile ${target_profile} --region ${source_region} --instance-id "${instance_id}" --query 'Reservations[*].Instances[*].NetworkInterfaces[*].Association.PublicIp' --output text)" | |
echo "$(date -Iseconds): instance public ip: ${instance_public_ip}" | |
echo "$(date -Iseconds): rdp: rdesktop -u root -p '$(pass Mozilla/relops/ec2/root@t-w732)' -k en-gb -g 2400x1200 -a 16 -K -r clipboard:CLIPBOARD ${instance_public_ip}" | |
rdesktop -u root -p '$(pass Mozilla/relops/ec2/root@t-w732)' -k en-gb -g 2400x1200 -a 16 -K -r clipboard:CLIPBOARD ${instance_public_ip} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment