How to make windows EC2 user data script run again on startup? - amazon-web-services

A user data script will run the first time an EC2 is started.
How can I restore/reactivate this ability on a windows EC2?
Note
I have tried the script suggested here but it fails immediately as there is no file C:\Program Files\Amazon\Ec2ConfigService\Settings\Config.xml and nothing similarly named (not that I found; not even an Ec2ConfigService directory)
Also note, my question is identical to this question but for windows ec2, not linux

I understand that the point is about just running user-data, and not all the other stuff ...
To run (only) user-data script, you can run it by:
Import-Module (Join-Path (Join-Path $env:ProgramData -ChildPath "Amazon\EC2-Windows\Launch") -ChildPath "Module\Ec2Launch.psd1")
Invoke-Userdata -OnlyExecute
let's say you save this as 'C:\ProgramData\Amazon\EC2-Windows\Launch\Config\run-user-data.ps1', then you can use PowerShell to schedule a new task to run at startup:
$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-ExecutionPolicy Bypass C:\ProgramData\Amazon\EC2-Windows\Launch\Config\run-user-data.ps1'
$Trigger = New-ScheduledTaskTrigger -AtStartup
$Settings = New-ScheduledTaskSettingsSet
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName 'Execute user-data' -InputObject $Task -User 'NT AUTHORITY\SYSTEM' -Force
I use this sort of solution by creating the mentioned file and command on 'AWS::CloudFormation::Init' sections.
Hope it helps!

Related

Fargate Windows container with pseudoTerminal

I am trying to create a fargate container to house a long running .net framework console app. The docker image I created works fine locally when i use the -t option. Trying to replicate this in fargate i set the psuedoTerminal option to true. Doing this causes the task not to start with the error
CannotStartContainerError: ResourceInitializationError: failed to create new container runtime task: failed to create shim: if using terminal, stderr must be empty: failed precondition
Here is the dockerfile i was using
FROM mcr.microsoft.com/windows/servercore:ltsc2019
RUN powershell.exe Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
RUN powershell.exe Install-Module -Name AWS.Tools.Installer -RequiredVersion 1.0.2.4 -Force
RUN powershell.exe Install-AWSToolsModule AWS.Tools.SQS,AWS.Tools.S3 -CleanUp -Force
COPY script.ps1 /app/script.ps1
ENTRYPOINT ["powershell.exe", "C:\\app\\script.ps1"]

How to properly use AWS Secrets Manager in a Elastic Beanstalk Deployment on Windows Server

Im trying to pass my applications connectionstring from Secrets Manager into Elastic Beanstalk during deployment. If i remote desktop onto the server i am deploying to, i can run the following command -
aws secretsmanager get-secret-value --secret-id XXX-MY-SECRET-ID --version-stage AWSCURRENT --query=SecretString --output text
And it outputs correctly. All good.
However when i try and automate this through the .ebextensions folder, it always returns an empty string.
So ive tried lots of things, firstly using a container command to point to a Powershell file that i placed in the .ebextensions folder, like so -
container_commands:
00-myscript:
command : powershell.exe -ExecutionPolicy Bypass -Command ".\\.ebextensions\\BuildConnectionStrings.ps1"
Then the Powershell command would be
$response = aws secretsmanager get-secret-value --secret-id XXX-MY-SECRET-ID --version-stage AWSCURRENT --query=SecretString --output text
$FileName = "ConnectionStrings.config"
New-Item $FileName -ItemType File
Set-Content $FileName $response
If i run this directly in powershell, it all works as expected. But when i deploy the site, it just creates an empty file.
Ive tried various combinations of putting the Powershell commands directly in the .ebextensions config files, always with the same result.
I just cant figure out why the same commands work when i run them directly on the server, but not when deployed through EB.
Ive been stuck for days on this, can anyone help?
So for anyone else that has this problem...
Simply installing the aws cli on the server is not enough. The error i was getting was caused by PowerShell not recognising the aws command (even tho it had been installed).
The solution was to run the following code at the beginning of my script -
$command = "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12"
Invoke-Expression $command
Invoke-WebRequest -Uri "https://awscli.amazonaws.com/AWSCLIV2.msi" -Outfile C:\AWSCLIV2.msi
$arguments = "/i `"C:\AWSCLIV2.msi`" /quiet"
Start-Process msiexec.exe -ArgumentList $arguments -Wait
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine")
aws --version
This ensured that the aws cli would be installed (again).
I dont know why this is necessary, but its the only solution ive found

Start-Process cmd does not work with Credential parameter when invoked from AWS Cloudformation template

I am creating an EC2 instance on AWS using Cloudformation template. As part of that template i am invoking a powershell script which performs the below steps (the script performs other tasks as well, but the below lines cause the error)
$MyFolder = "C:\installers\temp\Database"
$MyRHFolder = $MyFolder + "\Roundhouse"
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
Write-Host "Secure password generated"
$cred = New-Object System.Management.Automation.PSCredential $Username, $securePassword
Start-Process cmd -ArgumentList "/c RoundHouseInstall.cmd" -WorkingDirectory $MyRHFolder -Credential $cred -Wait
This fails everytime when it is invoked as part of the Cloudformation stack creation. There are strangely no errors thrown or any other output in the log. The RoundHouseInstall.cmd simply does not get invoked. However, if I manually log in to the EC2 and invoke the same script it works.
Also when I removed the -Credential parameter from the Start-Process command, the script worked fine even from Cloudformation, which means there is something going wrong with the credential parameter.
I need to run the script using the particular credential only otherwise the RoundHouseInstall.cmd will fail. I am out of my depth to understand why this fails and also what to try to make it work. Any assistance is appreciated.

Run Powershell script as a service, watching log files and reporting via email

I have some log files that I am watching, I need to do this using PowerShell since its a windows server. the command I am using to do this is:
Get-Content System.log -wait | {$_-match "some regex"}
I am trying to run this in a script and make it email me if it found any changes to the log file that follow the regex i specify. This is easily doable using bash and cron. I am not sure what's the equivalent in PowerShell. and what return code I need to look for to know if it found anything?
have you tried
Get-Content System.log -wait | {$_-match "some regex"} | foreach { send-email -message $_ }
I don't know if the result of the where will be piped until get-content -wait exits but give it a go.
As for running it as a service you can call a powershell script from FireDaemon or SvrAny but you could also use a schedule task to keep restarting the script.

Setting up Bamboo SVN commit build trigger

Bamboo CI has a build in feature of having the subversion program trigger a build in bamboo when someone commits to the repository. I followed the instructions of what to put in the post commit hook but I am not sure what the 2 arguments are supposed to be for the postcommitbuildtrigger.sh file. Lets say the project name is TEST and the build name is TESTBUILD and the server url is http://localhost:8085. I wrote this in the post commit hook command line.
/<pathtopostcommit.sh> TEST TESTBUILD
Question
The post commit .sh file is on a windows machine. It could be because windows doesnt run .sh files but if thats so does anyone know how to set up this trigger on windows?
Also, I think this will trigger a build immediatly? Is is possible to trigger bamboo to run a poll instead so the build will obey the quiet period?
Have to write your own scripts. Bamboo only distributes mac and linux scripts.
Ok I wrote my own. It's so much nicer than subversion poll time-outs. Tested on:
VisualSvn Server 2.7.2;
Windows Web Server 2008 R2.
PowerShell 2.0
BambooWebApiTrigger.bat
A batch file runner for PowerShell in C:\SvnHooks\:
#echo OFF
rem this file just makes spawning powershell from VisualSvn a tad easier...
rem
rem Args from VisualSvn Server are ignored. Pass Bamboo BUILD KEY as the first
rem parameter to this script.
Powershell.exe -executionpolicy remotesigned -File C:\SvnHooks\BambooWebApiTrigger.ps1 -key %1
BambooWebApiTrigger.ps1
A PowerShell script to run System.Net.WebClient, also in C:\SvnHooks\. Overwrite bamboo.yourdefaultdomain.com with your local Bamboo server:
# A Powershell script to trigger Bamboo to build a specific key
param (
[string]$baseurl = "http://bamboo.radicalsystems.com.au:8085",
[Parameter(Mandatory=$true)]
[string]$key,
[string]$tmp = $null
)
$fullUrl = $baseurl + "/updateAndBuild.action?buildKey=" + $key
if (!$tmp) {
$tmp = [io.path]::GetTempFileName()
}
echo "Pinging Bamboo API at '$fullUrl'"
$client = new-object System.Net.WebClient
$client.DownloadFile($fullUrl, $tmp)
# comment Remove-Item to see the results. It is a HTML result with success message.
# echo "Results are in $tmp"
Remove-Item $tmp
Configure VisualSvn
Right click on project in VisualSvn Server Manager > Properties > Hooks > Post-commit hook (Edit).
Enter this line after any others:
C:\SvnHooks\BambooWebApiTrigger.bat BambooProjectKey
where BambooProjectKey is the key, found after your bamboo url when browsing the Build Plan (not the project). It usually has a hyphen in it: http://bamboo.yourdomain.com:8085/browse/FOO-BAR. In this case, FOO-BAR would be the key.
Configure Bamboo
Change your Bamboo trigger to Repository triggers the build when changes are committed
Options
You can overwrite the key from the VisualSvn post-commit hook dialog, as well as Bamboo base URL and temp file location from the batch file runner.