Error “Cannot unregister the machine” on Jenkins, ‘kitchen test’ command

2017/04/06

Ok, it’s a hack… so don’t use it unless you need it, and on your own risk.
For some reason, although the Windows vagrant box is updated using Matt Wrock’s packer templates from here https://github.com/mwrock/packer-templates, and everything goes well, and also on the first manual kitchen test on the Jenkins server everything goes ok, when run from Jenkin’s pipeline mechanism, the box is not destroyed.
Three VirtualBox processes remain hanged in the system.
It’s not a clean solution, but having this error over and over again:

STDERR: There was an error while executing `VBoxManage`, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below.
Command: [“unregistervm”, “some GUID here”, “–delete”]
Stderr: VBoxManage.exe: error: Cannot unregister the machine ‘kitchen-your_cookbook-default-windows2012r2_default_some_numbers’ while it is locked
VBoxManage.exe: error: Details: code VBOX_E_INVALID_OBJECT_STATE (0x80bb0007), component MachineWrap, interface IMachine, callee IUnknown

it’s really annoying, so until the final solution will reveal itself, this might also be a way:

$cookbook = ‘your_cookbook_name’
gwmi -Query “select * from win32_process where name = ‘virtualbox.exe'” | `
? { $_.CommandLine.Contains(“kitchen-$cookbook”)} | `
Select CommandLine, Handle | `
% { Get-Process -Id $_.Handle } | `
Stop-Process -Force -ErrorAction Continue

You’ll need to execute it from Groovy with the bat command, something like

bat “powershell -File \”../killVBoxes.ps1\” ${cookbookName}”

For the path of the PowerShell script you’ll need to provide the correct path.

Note: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.

Advertisements

Clean VirtualBox virtual machines used by Chef on converge

2017/03/31

From time to time I keep getting strange behavior, on local PC, with virtual machines used by Chef, maybe after a ChefDK or VirtualBox update.
Some VMs do not get destroyed properly, or maybe more than one VM is created for the same cookbook.
The following PowerShell script can be used to destroy all VMs for a Chef cookbook; it must be used from the parent folder of the cookbook, using the syntax:
.\clearCache.ps1 my_chef_cookbook .
And here the script clearCache.ps1, located one level above the cookbook, in order to be usable with all its siblings:

[CmdletBinding()]
param(
[string]$cookbook
)

# VBOX_HOME is a user environment variable specifying
# where the VirtualBox VMs are stored
# Something like C:\Users\[your_user]\VBox_VMs

$dir = (pwd).Path
cd $cookbook
Write-Output “Removing folder content for .kitchen”
rm “.\.kitchen\” -Force -Recurse

Write-Output “Power-off VMs”
((& ‘C:\Program Files\Oracle\VirtualBox\vboxmanage’ list vms) | `
  % { ($_.Replace(‘”‘,”) -split ” “)[0] } | ` # Replace double quotes with nothing
  ? { $_.Contains(“kitchen-“) }) | `
  % { & ‘C:\Program Files\Oracle\VirtualBox\vboxmanage’ controlvm $_ poweroff }
Write-Output “Delete VMs”
((& ‘C:\Program Files\Oracle\VirtualBox\vboxmanage’ list vms) | `
  % { ($_.Replace(‘”‘,”) -split ” “)[0] } | `
  ? { $_.Contains(“kitchen-“) }) | `
  % { & ‘C:\Program Files\Oracle\VirtualBox\vboxmanage’ unregistervm $_ –delete }

Write-Output “Delete the VMs again, just in case we previously had an error …”
rm “$($env.VBOX_HOME)\kitchen-$cookbook*” -Force -Recurse

Write-Output “Destroy kitchen”
kitchen destroy
rm “.\.kitchen\” -Force -Recurse
vagrant global-status –prune
Write-Output “Done”
ls
cd ..

Note: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Add Chef cookbook dependency in Berksfile group for testing

2016/11/24
source `https://supermarket.chef.io`

metadata

group :integration do
cookbook ‘some_cookbook’, path: ‘./test/fixtures/cookbooks/some_cookbook’

# not a strict dependency, but necessary for testing
cookbook ‘java’
end

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Install latest ChefDK nightly build through crontab

2016/10/24

To install the latest ChefDK nightly build at 1 AM every day, put this in the root crontab:

0 1 * * * curl https://omnitruck.chef.io/install.sh | bash -s —- -p -P chefdk

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Upload a ZIP to Azure storage account in PowerShell

2016/06/23

This was tested under PowerShell 5, with Azure PowerShell module installed.

After you download your Azure publish settings file from https://manage.windowsazure.com/publishsettings/index?client=powershell&schemaVersion= you can use Get-AzureSubscription to choose a subscription for the upload (if you have several on your account)

if(-not (Get-Module Azure)) {
  Import-Module Azure
}

Import-AzurePublishSettingsFile “path/to/your/azure/publish/settings/file”

(Get-AzureSubscription).SubscriptionName # Choose subscription if several present

Select-AzureSubscription -SubscriptionName “YourSubscritionNameHere”
$storAcc = ‘companyartifacts’
$storCntr = ‘builds’
$blob = ‘Buildxyz.zip’
$key = (Get-AzureStorageKey -StorageAccountName $storAcc).Primary

$ctxt = New-AzureStorageContext -StorageAccountName $storAcc -StorageAccountKey $key

Write-Output “Uploading ZIP to Azure…”

Set-AzureStorageBlobContent -File “path\to\Buildxyz.zip” -Container $storCntr -Blob $blob -BlobType Block -Context $ctxt -Force

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Useful Chef development prerequisites

2016/03/02

The PowerShell commands below are some main steps needed to configure Chef on a development machine; still, they are not the only needed steps, there are others, like adding the SSH key to GitLab, downloading PEM key from Chef server, maybe Azure configuration, etc.

# Installing packages with Chocolatey
choco install atom -y
choco install git -y
choco install poshgit -y
choco install chefdk -y
choco install virtualbox -y
choco install virtualbox.extensionpack -y
choco install vagrant -y
choco install vagrant-winrm-config -y

# Restart required after packages installation
Restart-Computer

# Install gems for Pester and chef-vault, if used for tests
chef gem install kitchen-pester
chef gem install chef-vault-testfixtures

# Environment variables configuration
$home_folder = “d:\home”
$chef_user = “”
$chef_repo = “d:\repos”
$chef_module = “your-chef-module”
if (!(Test-Path $home_folder)) {
  mkdir $home_folder
}
[Environment]::SetEnvironmentVariable(“Path”, $env:Path + “;C:\Program Files\Git\usr\bin”, “Machine”)
[Environment]::SetEnvironmentVariable(“HOME”, “$home_folder”, “User”)
[Environment]::SetEnvironmentVariable(“CHEF_ORG”, “your-organization”, “User”)
[Environment]::SetEnvironmentVariable(“CHEF_USER”, $chef_user, “User”)
[Environment]::SetEnvironmentVariable(“Path”, $env:Path + “;C:\HashiCorp\Vagrant\bin”, “Machine”)
[Environment]::SetEnvironmentVariable(“VAGRANT_HOME”, “$env:HOME\vagrant.d”, “User”)

# Git configuration
git config –global user.name “”
git config –global user.email “”
git config –global push.default simple

# SSH key generation
ssh-keygen -t rsa -b 4096 -C “”

# Handle Git repository locally
cd $chef_repo
git clone git@gitlab.com:cookbooks-parent-folder/$chef_module.git
cd $chef_module
git submodule update –init –remote

# Handle knife settings
Copy-Item “$chef_repo\$chef_module\chef\.chef\knife.rb” “$env:HOME\.chef\knife.rb”

# Install vagrant plugin for WinRM
vagrant plugin install vagrant-winrm


Install useful stuff on Fedora 23

2016/01/12

Execute the following commands within sudo:

su –

## Install updates
dnf update

## Add additional repositories
#rpm -ivh http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-stable.noarch.rpm
dnf install http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm
dnf install http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm

## Install audio and video codecs
## Next command represents a single line
dnf install gstreamer1-plugins-base gstreamer1-plugins-good gstreamer1-plugins-ugly gstreamer1-plugins-bad-free gstreamer1-plugins-bad-free gstreamer1-plugins-bad-freeworld gstreamer1-plugins-bad-free-extras ffmpeg
## Add HandBrake repo
dnf config-manager –add-repo=http://negativo17.org/repos/fedora-handbrake.repo
dnf install libdvdcss -y
dnf install HandBrake-gui -y

## Install additional desktop environments
## Check available and installed environments
dnf grouplist -v | grep environment
## Fedora 23 Workstation comes with Gnome, so comment corresponding line
## Fedora 23 Games comes with Xfce, so comment corresponding line
dnf install @xfce-desktop -y
dnf install @kde-desktop -y
dnf install @lxde-desktop -y
dnf install @gnome-desktop -y
dnf install @cinnamon-desktop -y
dnf install @mate-desktop -y
## If you want even more from mate environment, execute the following
dnf groupinstall mate-compiz -y
dnf groupinstall mate-applications -y

## If you have issues seeing the newly installed desktop environments
## run one of the following commands to switch the desktop manager:
systemctl enable lxdm.service -f
systemctl enable lightdm.service -f
systemctl enable gdm.service -f
systemctl enable kdm.service -f
## You can check the current running desktop manager like this:
systemctl list-units | grep -i manager

## You might consider useful to install a switcher for desktop environments
## if the default one is not shown in Gnome at the top-right corner
## The switcher will be available when logging to Fedora
## at the bottom-left corner
dnf install system-switch-displaymanger -y

## Install additional environments
dnf groupinstall workstation-product-environment -y
## The below environments are needed only if you want to code
dnf groupinstall developer-workstation-environment -y
dnf groupinstall web-server-environment -y

## Install utilities
dnf install smplayer -y
dnf install vlc -y
dnf install unzip -y
dnf install gimp -y
dnf install pidgin -y
dnf install qbittorrent -y
dnf install uget -y
dnf install VirtualBox -y
dnf install youtube-dl -y
dnf install wine -y # To run Windows programs

## Install Steam
dnf config-manager –add-repo=http://negativo17.org/repos/fedora-steam.repo
dnf -y install steam

## Install Adobe Flash player
## Adobe Repository 64-bit x86_64 ##
rpm -ivh http://linuxdownload.adobe.com/adobe-release/adobe-release-x86_64-1.0-1.noarch.rpm
rpm –import /etc/pki/rpm-gpg/RPM-GPG-KEY-adobe-linux
dnf install -y flash-plugin nspluginwrapper alsa-plugins-pulseaudio libcurl

## Install cool games
dnf install -y supertuxkart
dnf install -y BlockOutII

## Install extra wallpapers on Fedora 23 environments
## Path for installed backgrounds is /usr/share/backgrounds/f23/extras
dnf install f23-backgrounds-extras-gnome -y
dnf install f23-backgrounds-extras-kde -y
dnf install f23-backgrounds-extras-xfce -y
dnf install f23-backgrounds-extras-mate -y

## Disable password entering on mounting NTFS partitions
cp /usr/share/polkit-1/actions/org.freedesktop.udisks2.policy /usr/share/polkit-1/actions/org.freedesktop.udisks2.policy.bak
sed -i ‘s/auth_admin_keep/yes/g’ /usr/share/polkit-1/actions/org.freedesktop.udisks2.policy

Useful content: www.if-not-true-then-false.com

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


%d bloggers like this: