Packer provisioners failing on azure-arm - azure-resource-manager

I have the following build in a Packer .hcl file. The first provisioner succeeds but the other two always fail. Does anyone have a working azure-arm provisioner to install software on a Windows image?
build {
sources = ["source.azure-arm.autogenerated_1"]
provisioner "powershell" {
inline = ["Add-WindowsFeature Web-Server", "while ((Get-Service RdAgent).Status -ne 'Running') { Start-Sleep -s 5 }", "while ((Get-Service WindowsAzureGuestAgent).Status -ne 'Running') { Start-Sleep -s 5 }", "& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /quiet /quit", "while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10 } else { break } }"]
}
provisioner "powershell" {
# inline = ["Set-ExecutionPolicy Bypass -Scope Process -Force", "Invoke-Expression((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))"]
# inline = ["Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))"]
inline = ["Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))"]
}
provisioner "powershell" {
inline = ["choco install -y 7zip", "choco install -y notepadplusplus"]
}
}

There is a problem with the order. The following part of your provisioner is responsible for the generalization process, which should be run last
"while ((Get-Service WindowsAzureGuestAgent).Status -ne 'Running') { Start-Sleep -s 5 }", "& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /quiet /quit", "while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10 } else { break } }"
Change the order of provisioners or add your commands above the generalization phase
build {
sources = ["source.azure-arm.autogenerated_1"]
provisioner "powershell" {
inline = ["Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))"]
}
provisioner "powershell" {
inline = ["choco install -y 7zip", "choco install -y notepadplusplus"]
}
provisioner "powershell" {
inline = [
"Add-WindowsFeature Web-Server",
"ADD YOUR COMMANDS HERE"
"while ((Get-Service RdAgent).Status -ne 'Running') { Start-Sleep -s 5 }",
"while ((Get-Service WindowsAzureGuestAgent).Status -ne 'Running') { Start-Sleep -s 5 }",
"& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /quiet /quit",
"while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10 } else { break } }"
]
}
}

Related

SyntaxError: Unexpected token { in Gruntfile.js

I don't manage to configure grunt. I have followed all the steps from Magento2 but I receive this syntax error.
grunt
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected token {
Warning: Task "default" not found. Use --force to continue.
Aborted due to warnings.
I have reinstalled both the grunt and the node.js, but it doesn't work.
Has anybody had the same problem?
Below you can see the Gruntfile.js ( that is original) posted.
Is it an error of this file or is there another problem?
Gruntfile.js
module.exports = function (grunt) {
'use strict';
var _ = require('underscore'),
path = require('path'),
filesRouter = require('./dev/tools/grunt/tools/files-router'),
configDir = './dev/tools/grunt/configs',
tasks = grunt.file.expand('./dev/tools/grunt/tasks/*'),
themes;
filesRouter.set('themes', 'dev/tools/grunt/configs/themes');
themes = filesRouter.get('themes');
tasks = _.map(tasks, function(task){ return task.replace('.js', '') });
tasks.push('time-grunt');
tasks.forEach(function (task) {
require(task)(grunt);
});
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, configDir),
init: true,
jitGrunt: {
staticMappings: {
usebanner: 'grunt-banner'
}
}
});
_.each({
/**
* Assembling tasks.
* ToDo: define default tasks.
*/
default: function () {
grunt.log.subhead('I\'m default task and at the moment I\'m empty, sorry :/');
},
/**
* Production preparation task.
*/
prod: function (component) {
var tasks = [
'less',
'autoprefixer',
'cssmin',
'usebanner'
].map(function(task){
return task + ':' + component;
});
if (typeof component === 'undefined') {
grunt.log.subhead('Tip: Please make sure that u specify prod subtask. By default prod task do nothing');
} else {
grunt.task.run(tasks);
}
},
/**
* Refresh themes.
*/
refresh: function () {
var tasks = [
'clean',
'exec:all'
];
_.each(themes, function(theme, name) {
tasks.push('less:' + name);
});
grunt.task.run(tasks);
},
/**
* Documentation
*/
documentation: [
'replace:documentation',
'less:documentation',
'styledocco:documentation',
'usebanner:documentationCss',
'usebanner:documentationLess',
'usebanner:documentationHtml',
'clean:var',
'clean:pub'
],
'legacy-build': [
'mage-minify:legacy'
],
spec: function (theme) {
var runner = require('./dev/tests/js/jasmine/spec_runner');
runner.init(grunt, { theme: theme });
grunt.task.run(runner.getTasks());
}
}, function (task, name) {
grunt.registerTask(name, task);
});
};
Thanks in advance!
I was getting the same error.
I installed node using the following commands and error resolved.
curl -sL https://deb.nodesource.com/setup_8.x | sudo bash -
sudo apt install nodejs
node -v
npm -v
Hope this helps!

Running scripts with special conditions in Atom

I used to use the build system in Sublime text where I could add my own customize build systems. For example, for CLisp, I created a build system as such:
{
"cmd": ["clisp", "-q", "-modern", "-L", "french", "$file"],
"selector": "source.lisp"
}
Similarly, I had a custom one for C:
{
"cmd" : ["gcc $file_name -Wall -o ${file_base_name} && ./${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path"
}
How can I do this in Atom?
For tthat task atom has a nice package called Atom Build package, you can find it here: https://github.com/noseglid/atom-build
It is using javascript here is an example for:
module.exports = {
cmd: 'make',
name: 'Makefile',
sh: true,
functionMatch: function (output) {
const enterDir = /^make\[\d+\]: Entering directory '([^']+)'$/;
const error = /^([^:]+):(\d+):(\d+): error: (.+)$/;
// this is the list of error matches that atom-build will process
const array = [];
// stores the current directory
var dir = null;
// iterate over the output by lines
output.split(/\r?\n/).forEach(line => {
// update the current directory on lines with `Entering directory`
const dir_match = enterDir.exec(line);
if (dir_match) {
dir = dir_match[1];
} else {
// process possible error messages
const error_match = error.exec(line);
if (error_match) {
// map the regex match to the error object that atom-build expects
array.push({
file: dir ? dir + '/' + error_match[1] : error_match[1],
line: error_match[2],
col: error_match[3],
message: error_match[4]
});
}
}
});
return array;
}
};

ASP.NET Core System.Runtime not found on test

Been trying to run ASP.NET Core 1.1 xunit tests coverage from PowerShell with no success. When running I get the following error:
System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified
.
On PowerShell line (the last one):
$solutionDir = "C:\Projects\AdministrationPortal.RestAPI"
$openCoverDir = (Get-ChildItem $packagesDir -filter "OpenCover*" -Directory | % { $_.fullname })
$openCoverRunner = "$openCoverDir\tools\OpenCover.Console.exe"
$packagesDir = $solutionDir + "\packages"
$xunitRunnerDir = (Get-ChildItem $packagesDir -filter "xunit.runner.console*" -Directory | % { $_.fullname })
$xunitRunner = "$xunitRunnerDir\tools\xunit.console.exe"
$unitTestsProjDir = (Get-ChildItem $solutionDir\test -filter "*Test*" - Directory | % { $_.fullname })
$testsDllDir = "$unitTestsProjDir\bin\Debug\netcoreapp1.1"
$testDllFile = (Get-ChildItem $testsDllDir -File | Where-Object {$_.Name -like "*Test*.dll" -and $_.Name -notlike "*xunit.runner.visualstudio.testadapter*" } )
$testDll = "$testsDllDir\$testDllFile"
$categories = "Integration;Unit"
$nameSpaceToTest = "AdminPortal.RestAPI.Areas.FeatureToggle.Services;AdminPortal.RestAPI.Areas.FeatureToggle.Storage;AdminPortal.RestAPI.Areas.Text.Services;AdminPortal.RestAPI.Areas.Text.Storage"
$nameSpaceToSkip = ""
$assemblyToTest = "AdminPortal.RestAPI"
$categoriesArray = (($categories -split ';') | ? {$_})
$nameSpaceToTestArray = (($nameSpaceToTest -split ';') | ? {$_})
$nameSpaceToSkipArray = (($nameSpaceToSkip -split ';') | ? {$_})
ForEach ($item In $nameSpaceToTestArray) {
$nameSpaceArray += "+[$assemblyToTest*]" + $item + "* " }
ForEach ($item In $nameSpaceToSkipArray) {
$nameSpaceArray += "-[$assemblyToTest*]" + $item + "* " }
$coverageReportDir = "C:\tmp\Coverage"
foreach ($item in $categoriesArray) {
$coverageReportXML = $coverageReportDir + "\coverage." + $item + ".xml"
Write-Output $coverageReportXML
& $openCoverRunner -register:user -target:"$xunitRunner" "-targetargs:$testDll" -targetdir:"$testsDllDir" -output:"$coverageReportXML" "-filter:$nameSpaceArray"
}
The initial thought was that .NET Framework 4.6 does not have System.Runtime but then I added additional framework imports that do have it, yet the results are the same. project.json file of the test project:
{
"version": "1.0.0-*",
"testRunner": "xunit",
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
},
"xunit": "2.2.0-beta5-build3474",
"dotnet-test-xunit": "2.2.0-preview2-build1029",
"xunit.runner.visualstudio": "2.2.0-beta3-build1187",
"Moq": "4.6.38-alpha",
"System.Linq": "4.3.0",
"Microsoft.DotNet.InternalAbstractions": "1.0.0",
"OpenCover": "4.6.519",
"ReportGenerator": "2.5.2",
"Microsoft.CodeCoverage": "1.0.2",
"xunit.runner.console": "2.2.0-beta5-build3474",
"System.Runtime": "4.3.0",
"AdminPortal.RestAPI": "1.0.0-*"
},
"frameworks": {
"netcoreapp1.1": {
"imports": [
"dnxcore50",
"dotnet5.6",
"portable-net46"
]
}
}
}

For loop in grunt to run the same script but pass in different args

so I have this javascript file that I can currently run with the cmd node runfile.js accountName.
I am trying to make a grunt task that will loop through an array of accountNames to pass into this cmd using grunt-exec.
I am pretty new to grunt and apologize if this is not worded well. Any help is very appreciated!
Current grunt file looks like:
grunt.initConfig({
exec: {
login: function(acct){
return 'node runfile.js' + acct;
}
},
});
I was able to successfully do this with the following code.
module.exports = function(grunt) {
grunt.initConfig({
exec: {
runMobile: {
cmd: function(account, password){
return 'node javascript.js ' + account + ' ' + password
}
},
runDesktop: {
cmd: function(account, password, first_name){
return 'node javascript2.js ' + account + ' ' + password + ' ' + first_name
}
}
}
});
grunt.loadNpmTasks('grunt-exec');
//get our list of accounts
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('node_modules/selenium-webdriver/example/accounts.json', 'utf-8'));
grunt.registerTask('default', 'Running The task',function(){
data.accounts.forEach(function(payload){
grunt.task.run('exec:runMobile:'+payload.account+':'+payload.password);
grunt.task.run('exec:runDesktop:'+payload.account+':'+payload.password+':'+payload.first_name);
});
});
};

QML WebEngineView flick content

I'm trying to make a simple web-browser for desktop with Ubuntu 14.04 using QML and WebEngineView component. The application will be working on devices with touchpad so it would be nice to make the content displayed inside WebEngineView flickable.
I tried to do it this way, but it does not work:
...
WebEngineView {
id: webView
url: "http://google.com"
width: parent.width
height: winternet.height-navigationBar.height-iStatusBar.height-iBackButton.height
anchors.top: navigationBar.bottom
MouseArea {
anchors.fill: parent
drag.target: parent.data
}
onLinkHovered: {
webView.url = hoveredUrl
}
}
...
If you have any idea's or experience with this, please help!
I wanted to make WebEngineView flickable too. I decided, that it's better to do it using Flickable. But naive approach of making something like:
...
Flickable {
WebEngineView {...}
}
...
will not work.
Further investigation led me to Qt based Web browser for embedded touch devices. I have tried it out on my PC. It seems like it's doing exactly what I want, but it's too complicated and GPL license renders it useless for any kind of use.
After some experiments I found out that flicking will work if Flickable.contentHeight and Flickable.contentWidth at least match the actual size of Web page being shown by WebEngineView. Those properties of Flickable may have greater values than actual page size have. In this case you'll be able to flick beyond content of page. If Flickable.contentHeight and/or Flickable.contentWidth are less than page size you'll still be able to flick. It's up to you whether you want it this way or not)
So it ended up to acquiring actual page size shown and setting it as Flickable.contentHeight and Flickable.contentWidth. I'll give you a short story here: there is no way to get desired values with WebEngineView API (or at least I didn't find anything in Qt 5.7/5.8 documentation). But I've accidentally found this answer on SO. Using this answer I've managed to make everything work:
...
Item {
Layout.fillHeight: true
Layout.fillWidth: true
Flickable {
id: flick
anchors.fill: parent
WebEngineView {
anchors.fill: parent
id: webView
}
}
webView.onLoadingChanged: {
if (webView.loadProgress == 100) {
webView.runJavaScript(
"document.documentElement.scrollHeight;",
function (i_actualPageHeight) {
flick.contentHeight = Math.max (
i_actualPageHeight, flick.height);
})
webView.runJavaScript(
"document.documentElement.scrollWidth;",
function (i_actualPageWidth) {
flick.contentWidth = Math.max (
i_actualPageWidth, flick.width);
})
}
}
}
...
The code snipped above may need some adjustments but it's nearly a copy of the code I have that works.
UPD 1: I have found out that this is not the final solution, because for some reason after new page is loaded document.documentElement.scrollWidth may not be reset and remain the same it was for previous page.
UPD 2: I've resolved the aforementioned problem, but the solution is a bit ugly: reset Flickable.contentWidth in WebEngineView.onLoadingChanged to Flickable.width. Setting Flickable.contentWidth to 0 will result in inappropriately large height of content after loading.
Another adjustment I've made was removing of requirement for 100% loading state.
UPD 3: A more complete version of the flickable WebEngiveView. User scripts are used instead of directly invoking JavaScript because I encountered some strange errors with the latter that resulted in WebEngineView closing.
// Copyright 2019 Utility Tool Kit Open Source Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
// Author: Innokentiy Alaytsev <alaitsev#gmail.com>
//
// File name: qml/Utk/Qml/FlickableWebEngineView.qml
//
// Description: The QML FlickableWebEngineView QtQuick 2 component.
import QtQuick 2.7
import QtWebEngine 1.3
Item {
property alias flickable: flickable;
property alias webView: webView;
property bool userDragImgEnabled: true;
property bool userSelectEnabled: true;
readonly property string kDisableUserDragCssId:
"utk_qml_flickable_web_engine_view_disable_user_drag_css";
readonly property string kDisableUserSelectCssId:
"utk_qml_flickable_web_engine_view_disable_user_select_css";
readonly property string kDisableUserDragCss:
"{ \\ \
-webkit-user-drag: none; \\ \
-khtml-user-drag: none; \\ \
-moz-user-drag: none; \\ \
-ms-user-drag: none; \\ \
user-drag: none; \\ \
}";
readonly property string kDisableUserSelectCss:
"{ \\ \
-webkit-touch-callout: none; \\ \
-webkit-user-select: none; \\ \
-khtml-user-select: none; \\ \
-moz-user-select: none; \\ \
-ms-user-select: none; \\ \
user-select: none; \\ \
}";
WebEngineScript {
id: disableUserDragScript;
name: kDisableUserDragCssId;
injectionPoint: WebEngineScript.DocumentReady;
sourceCode: applyCssJavaScript ("img", kDisableUserDragCss, kDisableUserDragCssId);
worldId: WebEngineScript.MainWorld;
}
WebEngineScript {
id: disableUserSelectScript;
name: kDisableUserSelectCssId;
injectionPoint: WebEngineScript.DocumentReady;
sourceCode: applyCssJavaScript ("body", kDisableUserSelectCss, kDisableUserSelectCssId);
worldId: WebEngineScript.MainWorld;
}
Flickable {
id: flickable;
anchors.fill : parent;
clip: true;
WebEngineView {
id: webView;
anchors.fill : parent;
scale: 1;
onLoadingChanged: {
if (loadRequest.status !== WebEngineView.LoadSucceededStatus) {
return;
}
flickable.contentHeight = 0;
flickable.contentWidth = flickable.width;
runJavaScript (
"document.documentElement.scrollHeight;",
function (actualPageHeight) {
flickable.contentHeight = Math.max (
actualPageHeight, flickable.height);
});
runJavaScript (
"document.documentElement.scrollWidth;",
function (actualPageWidth) {
flickable.contentWidth = Math.max (
actualPageWidth, flickable.width);
});
}
}
}
onUserDragImgEnabledChanged: {
if (userDragImgEnabled &&
(webView.loadRequest.status === WebEngineView.LoadSucceededStatus)) {
runJavaScript (revertCssJavaScript (kDisableUserDragCssId));
}
else {
webView.userScripts = currentUserScripts ();
}
}
onUserSelectEnabledChanged: {
if (userSelectEnabled &&
(webView.loadRequest.status === WebEngineView.LoadSucceededStatus)) {
runJavaScript (revertCssJavaScript (kDisableUserSelectCssId));
}
else {
webView.userScripts = currentUserScripts ();
}
}
function currentUserScripts () {
var userScriptsToSkip = [
disableUserDragScript.name,
disableUserSelectScript.name
];
var updatedUserScripts = [];
for (var i in webView.userScripts) {
var script = webView.userScripts[ i ];
if (-1 == userScriptsToSkip.indexOf (script.name)) {
updatedUserScripts.push (script);
}
}
if (!userDragImgEnabled) {
updatedUserScripts.push (disableUserDragScript);
}
if (!userSelectEnabled) {
updatedUserScripts.push (disableUserSelectScript);
}
return updatedUserScripts;
}
function applyCssJavaScript (selector, css, cssId) {
var applyCssJavaScript =
"(function () { \
cssElement = document.createElement ('style'); \
\
head = document.head || \
document.getElementsByTagName ('head')[ 0 ]; \
\
head.appendChild (cssElement); \
\
cssElement.type = 'text/css'; \
cssElement.id = '%1'; \
\
if (cssElement.styleSheet) \
{ \
cssElement.styleSheet.cssText = '%2 %3'; \
} \
else \
{ \
cssElement.appendChild ( \
document.createTextNode ('%2 %3')); \
} \
})();";
return applyCssJavaScript
.arg (cssId)
.arg (selector)
.arg (css);
}
function revertCssJavaScript (cssId) {
var revertCssJavaScript =
"(function () { \
var element = document.getElementById('%1'); \
\
if (element) { \
element.outerHTML = ''; \
\
delete element; \
} \
})()";
return revertCssJavaScript.arg (cssId);
}
}

Resources