Invoke-AzVMReimage: The Reimage and OSUpgrade Virtual Machine actions require that the virtual machine has Automatic OS Upgrades enabled - azure-virtual-machine

I'm creating VM using the following configuration which specifies -EnableAutoUpdate:
# Create virtual machine
Write-Host "Creating virtual machine '$vmName' in resource group '$resourceGroupName'";
$virtualMachineConfig = New-AzVmConfig -VMName "$vmName" -VMSize "Standard_D2_v3" -IdentityType UserAssigned -IdentityID "$($userAssignedIdentity.Id)" `
| Set-AzVMOperatingSystem -CustomData $encodedScript -Windows -ComputerName "$vmname" -Credential $Credential -ProvisionVMAgent -EnableAutoUpdate `
| Add-AzVMNetworkInterface -Id $nic.Id `
| Set-AzVMSourceImage -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' -Skus '2016-Datacenter' -Version latest `
| Set-AzVMBootDiagnostics -Enable -ResourceGroupName $resourceGroup.ResourceGroupName -StorageAccountName $bootDiagStorageAccount.StorageAccountName;
But when I try to reimage VM get the following error:
Invoke-AzVMReimage: The Reimage and OSUpgrade Virtual Machine actions require that the virtual machine has Automatic OS Upgrades enabled.
What exactly need to be able to run reimage command?

I vaguely remember this feature been in preview for Azure VMs with ephemeral OS Disk. I didn't sign up for preview back then to can't repro.
https://azure.microsoft.com/en-us/blog/ephemeral-os-disk-limited-public-preview/
hope this points you in right direction.

Related

AWS PowerShell customize SSO Callback: There is no Runspace available to run scripts in this thread

I'm using the PowerShell (v7) script below to customize AWS SSO Login FLow. It's based on a working .net implementation:
$ErrorActionPreference = "Stop"
Import-Module -Name "AWSPowerShell.NetCore"
$profileName = "my-sso-profile"
$chain = New-Object Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain
$credentials = $null
$chain.TryGetAWSCredentials($profileName, [ref]$credentials)
$ssoCredentials = [Amazon.Runtime.SSOAWSCredentials]$credentials
$ssoCredentials.Options.ClientName = "Example-SSO-Script"
$ssoCredentials.Options.SsoVerificationCallback = [System.Action[Amazon.Runtime.SsoVerificationArguments]]{
param($x)
# Launch SSO Login Flow in Browser
Start-Process $x.VerificationUriComplete
}
Set-AWSCredential -Credential $ssoCredentials
# Print details about current Credential
Get-StsCallerIdentity
Error
When I run this script in Powershell (v7), I get an exception:
There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: param($x) …cationUriComplete
Looks like there is an issue invoking my script delegate in$ssoCredentials.Options.SsoVerificationCallback
Question
How can I configure my Script/PowerShell Session so that my SsoVerificationCallback delegate executes without throwing an error?
Research
I'm guessing the problem has something to do with the C# code invoking the SsoVerificationCallback delegate, which is now a PSScriptBlock(?), and something going wrong marshalling back and forth between C# and PowerShell.
Looking around SO, the SsoVerificationCallback invocation isn't Async, though it is invoked inside an async method GetSsoTokenAsync, so I don't think Runspace issus using async APIs from Powershell applies.
And I'm not making a web call directly, so tips in blog such as https://www.agilepointnxblog.com/powershell-error-there-is-no-runspace-available-to-run-scripts-in-this-thread/ recommended setting [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null also didn't make any impact.
While I'm hazy on the details, the following general information may be helpful:
While PowerShell script blocks ({ ... }) generally can be used as .NET delegates, their invocation only succeeds if the calling thread has a PowerShell runspace associated with it - script blocks cannot execute otherwise.
If a given script-block-based delegate is called (back) from the PowerShell session's own foreground thread, this requirement is by definition met; e.g., passing a script block as a MatchEvaluator delegate to [regex]::Replace():
PS> [regex]::Replace('woo', 'o$', { param($m) $m.Value + 't!' })
woot!
However, it seems that in your case a different thread - one without an associated PowerShell runspace - is calling your script-block-based delegate, which results in the error you saw.
There may be a - cumbersome, nontrivial - workaround based on ad-hoc compilation of C# code, as shown in this answer.

CAS Policy error in C++ while executing the EXE windows service

This method explicitly uses CAS policy, which has been obsoleted by
the .NET Framework. In order to enable CAS policy for compatibility
reasons, please use the NetFx40_LegacySecurityPolicy configuration
switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for
more information.
This is the error I am facing
I am trying to access my EXE file to install the file but it is throwing such error. Here are details
"$progExe" #AmsoPana\AMSOService.exe
"$dir" #AmsoPana
"$userServiceName" #AMSOService
"$requiresInstanceNameSwitch" #true
"$displayName" #CompanyName PANA Service
if($displayName -eq $null)
{
.\Tools\Deployment.exe type="exec" program="C:\CompanyName\CPANA\$progExe" directory="C:\xys\CPANA\$dir" param="/install ${Instance_Name_Arg} /SERVICENAME $userServiceName" serviceNotExists="$userServiceName"
}
else
{
.\Tools\Deployment.exe type="exec" program="C:\CompanyName\CPANA\$progExe" directory="C:\xyz\CPANA\$dir" param="/install ${Instance_Name_Arg} /SERVICENAME $userServiceName /DISPLAYNAME "$displayName"" serviceNotExists="$userServiceName"
}

WlanHostedNetworkStartUsing or how windows 10 builtin mobile hotspot works

I'm trying to write a program which creates hotspot. I'm using WlanHostedNetworkStartUsing but it returns ERROR_INVALID_STATE. And yet when I call WlanHostedNetworkInitSettings it returns succsess. According to documemtation (last paragraph in Remarks section) it should to create a virtual wireless connection under Control Panel\Network and Internet\Network and Sharing Center but it doesn't.
I've searching a bit and found this:
When I run netsh wlan show drivers it puts:
Driver : Intel(R) Dual Band Wireless-AC 3165
Vendor : Intel Corporation
Provider : Intel
Date : 07-Sep-16
Version : 19.20.0.6
INF file : ????
Type : Native Wi-Fi Driver
Radio types supported : 802.11b 802.11g 802.11n 802.11a 802.11ac
/ ...
Hosted network supported : No <--- Here
/ ...
So it says my wifi adapter doesn't wifi sharing at all (I have last drivers from HP site).
BUT when I try to create hotspot with Windows 10 builtin' tool it works.
The question: How could windows tool do it and how can I use this mechanism in my app?
Original 06/06/2018 comments here (see updates below):
Microsoft deprecated the WLAN HostedNetwork capability and it is NOT
available for Win10 drivers. To use the old model in Win10 you must
find and install drivers from 2015 (8.1 or possibly earlier depending
on vendor).
The Win10 driver model changed the mechanism of HostedNetwork to be
based on WiFi Direct, and took control away from app-developers and
moved this feature to the kernel. There are some samples available if
you dig around, that show how to use the modern-com (RT) UWP app
libraries to configure a WiFi Direct HostedNetwork. It is a PITA,
which was not explained by Microsoft, is not understood by most people
commenting on this in the web, and which mostly looks like a two-step
microsoft failure where product features were cut to make ship
schedule and re-orgs among teams changed the ownership and plan for
WiFi and hotspots. WiFi direct enables - theoretically - a simpler
pairing and authentication model between devices. But the currently
implementation involves bluetooth and therefore it is questionable
other than support a limited mobile device WiFi 2.0 scenario. If you
are working with headless devices or IoT device scenarios this is
broken.
I've had to do a lot of work in this area. If you have a choice in
WiFi hardware, I strongly recommend a hardware chipset that uses the
Intel drivers (they are solid).
You may find this App store app helpful if your scenario allows for UX
interaction.
http://www.topuwp.com/windowsapps/wifi-direct-access-point/598084.html
====================
02/27/2020 Update to that story...
When Hosted network supported : No then legacy hosted network support is not available on your adapter because you have WiFi Direct in Windows 10 etc. In which case you'll want to know and use this very sparsely commented on supported portion of WiFi Direct:
https://learn.microsoft.com/en-us/uwp/api/windows.networking.networkoperators.networkoperatortetheringmanager.createfromconnectionprofile
Command Line to HotSpot settings: start ms-settings:network-mobilehotspot
Article that talks about PowerShell programmatic access to the WinRT HotSpot APIs
enable Win10 inbuild hotspot by cmd/batch/powershell
KEYWORDS: "Virtual Wi-Fi", SoftAP, AdHoc IBSS, MobileHotSpot, netsh wlan HostedNetwork
====================
Which would not be complete without a working C++/WinRT code sample as follows:
#include <winrt/Windows.Networking.Connectivity.h>
#include <winrt/Windows.Networking.NetworkOperators.h>
#include <winrt/Windows.Devices.WiFiDirect.h>
#include <winrt/Windows.Security.Credentials.h>
namespace winrt { // /ZW embed in :<winrt> when `Windows` is ambiguously defined
static void af_winrt_wifi_hotspot_test() {
// start ms-settings:network-mobilehotspot
init_apartment(); // apartment_type::multi_threaded
if (false /* play as you wish to test this all in simple c++ console app, I used clang */) {
auto publisher = Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher();
auto advertisement = publisher.Advertisement();
advertisement.ListenStateDiscoverability(Windows::Devices::WiFiDirect::WiFiDirectAdvertisementListenStateDiscoverability::Intensive);
advertisement.IsAutonomousGroupOwnerEnabled(true);
auto legacySettings = advertisement.LegacySettings();
legacySettings.IsEnabled(true);
legacySettings.Ssid(L"your-hotspot-name");
auto credential = Windows::Security::Credentials::PasswordCredential(); credential.Password(L"the-password!");
legacySettings.Passphrase(credential);
publisher.Start();
}
else {
auto connectionProfile{ Windows::Networking::Connectivity::NetworkInformation::GetInternetConnectionProfile() };
auto tetheringManager = Windows::Networking::NetworkOperators::NetworkOperatorTetheringManager::CreateFromConnectionProfile(connectionProfile);
auto credential = Windows::Security::Credentials::PasswordCredential(); credential.Password(L"the-password!");
auto conf = Windows::Networking::NetworkOperators::NetworkOperatorTetheringAccessPointConfiguration();
conf.Ssid(L"I-Own-You"); conf.Passphrase(credential.Password());
auto oldConf = tetheringManager.GetCurrentAccessPointConfiguration();
auto oldSsid = oldConf.Ssid(); auto oldPwd = oldConf.Passphrase();
tetheringManager.ConfigureAccessPointAsync(conf); // Sets new ssid/pwd here
switch (tetheringManager.TetheringOperationalState()) {
case Windows::Networking::NetworkOperators::TetheringOperationalState::Off: {
auto ioAsync = tetheringManager.StartTetheringAsync();
auto fResult = ioAsync.get();
}
break;
case Windows::Networking::NetworkOperators::TetheringOperationalState::On: {
// auto ioAsync = tetheringManager.StopTetheringAsync();
// auto fResult = ioAsync.get();
}
break;
case Windows::Networking::NetworkOperators::TetheringOperationalState::InTransition:
default:
break;
}
}
clear_factory_cache();
uninit_apartment();
}
}
Look here for older Microsoft Samples relating to WiFiDirectAdvertisementPublisher:
C++ WiFiDirectLegacyAPDemo_v1.0.zip on Microsoft Page
C# Microsoft IoT Sample OnboardingAccessPoint.cs on GitHub Page
mobile broadband networks, use IMbnConnectionProfileManager::CreateConnectionProfile
Wi-Fi networks, use WlanSetProfile function
Mobile Hotspot XML WFD_GROUP_OWNER_PROFILE profile is in this dir-path: C:\ProgramData\Microsoft\Wlansvc\Profiles\Interfaces\
So many articles on the web, so much confusion created by WiFi-Direct.
I've spent two whole days figuring it all out. Which, for my time, is a lot.
No excuse for Microsoft (where I use to work as an Architect) not having created a Blog about this very popular topic. Let alone simply having made netsh and Ad Hoc Wifi compat support, instead of leaving it so cryptic and confusing for devops, end-users, and developers.
-- enjoy David
The above is pretty concise, and exposes working c++/WinRT code for all scenarios.
[I now have this bundled in EdgeS: EdgeShell/EdgeScript/afm-scm toolset]
[]5
Your computer does not support hosted network.
Because of that, this won't work.
Open command prompt as admin and try these commands:
netsh wlan set hostednetwork mode=allow ssid=“OSToto Hotspot” key=“12345678”
The ssid is the name of your network and the key is the password. You can name them like the above command.
Then run:
netsh wlan start hostednetwork
Rest before saying anything else, I would like to got through your source code.

Java code to get currently running beanstalk version label?

From within a running Java application running on beanstalk, how can I get the beanstalk version label that is currently running?
[Multiple Edits later...]
After a few back-and-forth comments with Sony (see below), I wrote the following code which works for me now. If you put meaningful comments in your version label when you deploy, then this will tell you what you're running. We have a continuous build environment, so we can get our build environment to supply a label that leads to the check-in comments for the related code. Put this all together, and your server can tell you exactly what code its running relative to your source code check-ins. Really useful for us. OK now I'm actually answering my own question here, but with invaluable help from Sony. Seems a shame you can't remove the hard-coded values and query for those at runtime.
String getMyVersionLabel() throws IOException {
Region region = Region.getRegion(Regions.fromName("us-west-2")); // Need to hard-code this
AWSCredentialsProvider credentialsProvider = new ClasspathPropertiesFileCredentialsProvider();
AWSElasticBeanstalkClient beanstalk = region.createClient(AWSElasticBeanstalkClient.class, credentialsProvider, null);
String environmentName = System.getProperty("PARAM2", "DefaultEnvironmentName"); // Need to hard-code this too
DescribeEnvironmentsResult environments = beanstalk.describeEnvironments();
for (EnvironmentDescription ed : environments.getEnvironments()) {
if (ed.getEnvironmentName().equals( environmentName)) {
return "Running version " + ed.getVersionLabel() + " created on " + ed.getDateCreated());
break;
}
}
return null;
}
You can use AWS Java SDK and call this directly.
See the details of describeApplicationVersions API for how to get all the versions in an application.Ensure to give your regions as well (otherwise you will get the versions from the default AWS region).
Now, if you need to know the version deployed currently, you need to call additionally the DescribeEnvironmentsRequest. This has the versionLabel, which tells you the the version currently deployed.
Here again, if you need to know the environment name in the code, you need to pass it as a param to the beanstalk configuration in the aws console, and access as a PARAM.

Determining dev vs production

What method should I use to determine if I'm on the dev system vs. production?
In this post from Ray Camden, he shows how to see what folder you're in, so that could be an indicator.
While in dev, I want to have error trapping turned off, missing template turned off, debug="yes" for cfstoredproc and cfquery, as well as always reload the components onRequestStart.
I have two approaches to this, both of which have served well. I'll start with the easiest approach first, which is what I'd call a "static". I use this when I don't have many environment-specific settings... maybe a small handful.
I'm assuming you have an Application.cfc or .cfm file for your app. In there, you could set a variable, something like "application.environment", and by default it'd be set to "dev". Throughout your app you could inspect that variable to determine where you are.
When you package your application for deployment, you could then change that Application.cfc file to read "" instead.
Now, that's going to get annoying, so I just use ant for this. I just use something like this in my build.xml, which lives in the same directory as Application.cfc:
<replace file="Application.cfc" token="DEV" value="PROD" casesensitive="true" />
And then zip the app for deployment:
<zip destfile="${zipdir}/MyApp-Production.zip">
<zipfileset dir="." prefix="MyApp" />
</zip>
Then I deploy the zip. If I'm working on a small project that uses FTP instead of some corporate enterprisey deployment hooey, then I'll just have an ANT task that FTPs files to my production server and it'll also perform that replace on Application.cfc and push that file, too.
For most of the apps I work on where I work, we use two database tables to manage environments. We do this because we have a lot of different environments, and each one has different settings, usually centered around filesystem and network paths that differ per environment (let's not talk about why they're different... totally separate discussion). So We have a table we call "AppLocations":
LocationID | LocName | LocDesc | Setting1 | Setting2 | Setting 3| ......
1 | Local | 'Localhost Environment' | whatever.....
2 | Dev | 'Development Environment' | whatever....
3 | Test | 'Test Environment' | whatever.....
and so on.
Then, we have another table named "AppLocationHosts"
LocationID | LocHostName
1 | 'localhost'
2 | 'devservername'
2 | 'otherdevservername'
3 | 'testservername'
3 | 'othertestserver'
and so on.
then, in Application.cfc, in onApplicationStart, we do this query
SELECT TOP 1 *
FROM AppLocations
WHERE LocationID IN (SELECT LocationID FROM AppLocationHosts WHERE LocHostName = <cfqueryparam value="#CGI.HTTP_HOST#" cfsqltype="cf_sql_varchar"/>)
And from there, once we know what location we're in based on the http_host match, we set those "Setting" columns into the application scope:
<cfloop list="#qryAppPathLocations.ColumnList#" index="ColName">
<cfset application[ColName] = qryAppPathLocations[ColName]>
</cfloop>
This approach isn't for everyone, but in our weird environment where consistency is unusual, it's been a very flexible approach.
Now, if you literally only have two environments, and one of them is "localhost" and the other is "www.myapp.com", then by far the easiest would be to just do a check on http_host in onApplicationStart and if you're in "www.myapp.com", then you do your production-specific setup. Perhaps here you set stuff like "request.querydebug = true" and then when you're in production, you turn that off. Then your queries could use that flag to determine whether to turn debug on or off for the cfstoredproc and query. Though I must say, I strongly recommend against that.
Can you just enable debugging in CFAdmin on your Dev box for your IP then use IsDebugMode()?
Dump the #server# scope and you'll see some keys that may help - eg the license mode of ColdFusion.
The solution we use is to set the IP of the current instance, and check it against our known "dev" IPs. Simple, easy, works.
A lot of good answers here - I'd like to mention using cgi.server_name , which can be combined with using a custom DNS to specify your dev environment. To get the localhost working, for IIS on Windows, set up hosts file like e.g. this:
C:\Windows\System32\drivers\etc\hosts - add entry:
127.0.0.1 myapp.dev.mydomain.com.au
Then in IIS map your server to this DNS.
Your systest and uat servers might be set up properly in your corp's DNS, such as
myapp.systest.mydomain.com.au - systest
myapp.uat.mydomain.com.au - uat
myapp.mydomain.com.au - production
Then, in my application.cfc I have a getEnvironment() that is called on every load for ease of use:
// get the environment based on cgi variables - top of application.cfc
this.stConfig = THIS.getEnvironment();
//... onApplicationStart
if (!stConfig.validEnvironment) {
writeOutput("Environment #cgi.server_name# not recognised");
return false;
}
// ...
public struct function getEnvironment () {
stConfig=structnew();
stConfig.validEnvironment = 1;
switch (cgi.server_name) {
// my dev environment
case "myapp.dev.mydomain.com.au": {
stConfig.env = "dev";
// +++
}
// my dev environment
case "myapp.systest.mydomain.com.au": {
stConfig.env = "systest";
// +++
}
// etc
}
return stConfig;
}
I will also copy stConfig to the request scope.
Now, I've got a lot of other stuff there too, and there's lots of ways to implement the storage of environments, e.g. but basically I find the combination of DNS and cgi.server_name particularly well suited to managing environments.
Fwiw, I will include ini files in application.cfc based on the environment name that I use for storing environment specific configurations. I find the getProfileSections() very useful for this, as the config files are very easy to work with. I have one common file that is shared between all environments, and then environment specific ones for those settings that need to be tailored to each environment.
Is it possible to get the directory of the currently running application?
Consider this directory structure for the different "instances" of your application:
/home/deploy/DevLevel.0/MyApp
Production Version
/home/deploy/DevLevel.1/MyApp
Preview or Staging Version
/home/deploy/DevLevel.2/MyApp
Development Version
If you can read the path to the current application, it's easy to find the integer after DevLevel. With that in hand (set as a global variable/constant), use it to change settings or behavior at runtime:
DevLevel == 0 means "Production"
DevLevel >= 1 means "Development"
For example, in the credit card authorization code:
if(DevLevel > 0)
enable_test_mode();
In error handling code:
if(DevLevel == 0)
send_error_to_log();
else
print_error();
Conclusion
The primary benefit here is that the code between the versions can remain 100% identical . No more "forgetting to enable this or disable that when moving code live".
Can this be implemented in ColdFusion?