Azure VM Extension Powershell DSC with template deployment - the process fails when a reboot is configured - azure-virtual-machine

I'm struggling with configuring a Reboot through Powershell DSC.
This is my scenario:
Using Azure RM Template deployments with a Visual Studio 2017 Resource Group project:
A VM is successfully deployed as a nested (linked) template
Next, again as a nested (linked) template dependent on the VM deployment, a Powershell DSC extension template is created
Within the Powershell DSC configuration a reboot should be forced at a certain stage
Tried two scenarios: a) using VM with Windows Server 2016 Datacenter and b) Windows Server 2012
Both scenarios report a failure. a) The first one fails at the reboot. b) The second one however seems to reboot and finish with the configurations, but still a failure is reported on the resource group deployments and VS output.
In both scenarios the error is: "DSC Configuration 'Main' completed with error(s). Following are the first few: C A general error occurred that is not covered by a more specific error code. C"
Here is the DSC configuration:
Configuration Main
{
param(
... a few parameters here ...
)
### required only for Windows Server 2012
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -Force
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser -Force
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine -Force
###
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -ModuleName xPendingReboot
Node "localhost"
{
LocalConfigurationManager
{
RebootNodeIfNeeded = $true
}
... Initial Configuration ...
Script Reboot
{
TestScript = {
return (Test-Path HKLM:\SOFTWARE\MyMainKey\RebootKey)
}
SetScript = {
New-Item -Path HKLM:\SOFTWARE\MyMainKey\RebootKey -Force
$global:DSCMachineStatus = 1
}
GetScript = { return #{result = 'Reboot'}}
DependsOn = '<Initial Configuration>'
}
# Reboot if pending
xPendingReboot RebootCheck
{
Name = "RebootCheck"
}
... Configuration Continued ...
}
}
Any help would be appreciated, thanks!
SOME UPDATE:
Actually, my "reboot" requirement is a workaround, because when the two deployments are executed as nested templates one after the other - the Powershell DSC fails
(if I deploy them separately, everything works fine).
The configuration seems to fail after a Script Resource has installed a windows service using NSSM. Then I noticed that if a restart is initiated on the machine, the configuration is applied successfully. Thus, the workaround with a restart....

in this case the solution was to add:
DependsOn = "[xPendingReboot]RebootCheck"
to all resources after xPendingReboot

Related

Can't run remote PowerShell commands in custom CloudFormation AMI (WinServer 2012)

The issue I'm going to describe works OK on a stock Windows Server 2012 AMI from Amazon. I'm facing issues with a custom AMI.
I created a custom AMI for Windows Server 2012 by creating an image from an EC2 machine.
Just before creating the custom AMI, I used the Ec2ConfigServiceSetting.exe to make sure:
The instance receives a new machine name based on its IP.
The password of the user is changed on boot.
The instance is provisioned using the script I have in place in UserData.
I also shut down the instance using Sysprep from the Ec2ConfigServiceSetting before creating the image for the custom AMI.
However, when I run a remote PowerShell command (from C# code, if it matters), it doesn't work. From C#-land, the command gets executed OK, but nothing happens in the machine.
Let's say my remote PS command launches a program in the remote machine (agent.exe). My script looks a little bit like:
Set-Location C:\path\in\disk
$env:Path = "C:\some\thing;" + $env:Path
C:\path\to\agent.exe --daemon
Once I log into the Ec2 instance, agent.exe --daemon is NOT running. However, if I first log into the instance, then run the remote PowerShell command, agent.exe --daemon DOES run.
This works perfectly with a stock AMI from Amazon, so I can only assume there's some configuration I'm missing for this to work (and, why does it work if I first log in using RDesktop?)
We found in the past some issues regarding SSL initialization without a user profile, so in our provisioning script (UserData) we do some things someone might consider shenanigans:
net user Administrator hardcoded-password
net user ec2-user hardcoded-password /add
$pwd = (ConvertTo-SecureString 'hardcoded-password' -AsPlainText -Force)
$cred = New-Object System.Management.Automation.PSCredential('Administrator', $pwd)
Start-Process cmd -LoadUserProfile -Credential $cred

How to make windows EC2 user data script run again on startup?

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!

Debugging a PowerShell script in .ebextensions

I'm trying to follow the instructions on https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/SSLNET.SingleInstance.html to install a self-signed certificate on an Elastic Beanstalk dev instance. That is, I have (in addition to other prerequisites listed there), a .ebextensions/https-instance-dotnet.config file of the form:
files:
"C:\\certs\\install-cert.ps1":
content:
Echo "I want some SSL"
import-module webadministration
## Settings - replace the following values with your own
$bucket = "my-bucket"
$certkey = "example.com.pfx"
$pwdkey = "password.txt"
[...]
commands:
00_install_ssl:
command: powershell -NoProfile -ExecutionPolicy Bypass -file C:\\certs\\install-cert.ps1 > c:\\certs\\log.txt
I'm publishing from Visual Studio to AWS EB using AWS Toolkit and not seeing errors. The file seems to be formatted correctly according to a YAML validator. But I can't tell if the script is working or not, or even being run, or if C:\certs\install-cert.ps1 and log.txt are being created in my environment.
My question is: How do I debug or trace this so I can see (for example) the results of the Echo commands?

Unable to set tags for azure virtual machine from Azure automation runbook

I am using the below code to set TAGs to my Azure virtual machine. The code is working when I am running it on my laptop (VM are getting tagged). However, when I run the same code from Azure Automation runbook, the virtual machines are not getting tagged. No errors or warnings observed post runbook execution.
Code:
$resource_group = "agentinstall-poc"
$tags = (Get-AzureRmResource -ResourceGroupName $resource_group -Name "client-2").Tags
$tags += #{manju="rao"}
Set-AzureRmResource -ResourceGroupName $resource_group -Name "client-2" -ResourceType "Microsoft.Compute/VirtualMachines" -Tag $tags -Force -ApiVersion '2015-06-15'
The problem was that the PowerShell modules in the Azure automation account are not updated by default (they are v1.0 ish when the account gets created). I had to update the modules and they started working.

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.