Chef exit codes

Chef uses the standard RFC 062 exit codes.

In your .kitchen.yml file, you can supply an array of exit codes in the “retry_on_exit_code” option to retry the operation in case the Chef script execution is interrupted. The usual values are

 retry_on_exit_code: # An array of exit codes that can indicate that kitchen should retry the converge command. Defaults to an empty array.
   - 35              # Reboot is scheduled
   - 20              # The Windows system cannot find the device specified.
   - 1               # Generic failure

Chef exit codes

  0: SUCCESS            - Successful run     - Any successful execution of a Chef utility should return this exit code
  1: GENERIC_FAILURE    - Failed execution   - Generic error during Chef execution.
  2: SIGINT_RECEIVED    - SIGINT received    - Received an interrupt signal
  3: SIGTERM_RECEIVED   - SIGTERM received   - Received an terminate signal
 35: REBOOT_SCHEDULED   - Reboot Scheduled   - Reboot has been scheduled in the run state
 37: REBOOT_NEEDED      - Reboot Needed      - Reboot needs to be completed
 41: REBOOT_FAILED      - Reboot Failed      - Initiated Reboot failed - due to permissions or any other reason
 42: AUDIT_MODE_FAILURE - Audit Mode Failure - Audit mode failed, but chef converged successfully.
213: CLIENT_UPGRADED    - Chef upgrade       - Chef has exited during a client upgrade

Relevant Windows exit codes

 20: ERROR_BAD_UNIT     - The system cannot find the device specified.

The list of all Windows error codes is located at https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx

The Linux exit codes for

FATAL: Chef::Exceptions::Reboot: Rebooting server at a recipe’s request.

When your Chef recipe requests a reboot using the “reboot” Chef resource, the output window shows an error message:

Chef Client finished, …/… resources updated in … seconds
[…] WARN: Rebooting server at a recipe’s request. Details: {:delay_mins=>1, :reason=>”…”, :timestamp=>…, :requested_by=>”…”}

Running handlers:
[…] ERROR: Running exception handlers
Running handlers complete
[…] ERROR: Exception handlers complete
Chef Client failed. … resources updated in … seconds
[…] FATAL: Stacktrace dumped to C:/Users/…/AppData/Local/Temp/kitchen/cache/chef-stacktrace.out
[…] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[…] FATAL: Chef::Exceptions::Reboot: Rebooting server at a recipe’s request. Details: {:delay_mins=>1, :reason=>”…”, :timestamp=>…, :requested_by=>”…”}

Chef also saves the error message in the stacktrace.out file at C:/Users/…/AppData/Local/Temp/kitchen/cache

As coderanger wrote it, replying to a StackOverflow post, it is not an error, it is a necessity to be able to stop the Chef cookbook execution when a reboot is requested. See https://stackoverflow.com/questions/39057254/why-does-chef-throw-fatal-error-on-restart-request

“Because we want to avoid running anything further in the Chef converge and the easiest way to do that is to raise an exception.”

“It’s a weird special case because Ruby doesn’t have any other non-local code execution flow construct that would work well in this case. You’ll just have to add a filter for it. Such are the realities of building software in an imperfect world :) – coderanger Aug 21 ’16 at 5:24″

 

 

Unable to satisfy constraints on package

When you make a change to the version restrictions in the metadata.rb file and execute berks install in your Chef cookbook directory, you may get the error message:

Unable to satisfy constraints on package … due to solution constraint (…). Solution constraints that may result in a constraint on …: [(…)], [(…) -> (…)]
Demand that cannot be met: (…)
Artifacts for which there are conflicting dependencies: … = … -> [(…), (… ~> …)]Unable to find a solution for demands:…

 

Execute

berks update

to

  • find the latest allowed versions of all referenced cookbooks,
  • update the Berksfile.lock file and
  • download the missing cookbooks to the cookbook cache folder at ~/.berkshelf/cookbooks
  • This command executes berks install too behind the scenes.

 

 

amazon-ebs: Error waiting for SSH: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

When you launch a Linux AWS EC2 instance with Terraform or create a Linux AWS image with Packer, one of the following errors are displayed:

amazon-ebs: Error waiting for SSH: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

aws_instance.default: 1 error(s) occurred:
* ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

Possible causes

Incorrect username

In the Packer template the “ssh_username”, in the Terraform script the “user” attribute contains the username to connect to the instance. It is important to use the correct username for each operating system. For the list of correct usernames for each operating system, see Create a server image with Packer

Wrong SSH key

Make sure you use the correct SSH key to connect to the instance. In the Terraform file, the “key_name”  attribute of the “aws_instance resource” specifies the SSH key to launch the instance with, and the “private_key” attribute of the “connection” contains the key itself as a string.

 

Procedure or function ‘`…_Insert`’ cannot be found in database …

When you use the Microsoft .NET Entity framework to access a MySql database, the autogenerated code throws an error when you try to insert a row into the database with

context.MY_TABLE.Add(MY_OBJECT);

Server Error in ‘/’ Application.
Procedure or function ‘`…_Insert`’ cannot be found in database ‘`…`’.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: MySql.Data.MySqlClient.MySqlException: Procedure or function ‘`…_Insert`’ cannot be found in database ‘`…`’.

The auto-generated class tries to use stored procedures to update the database. To use the Entity Framework Linq commands, comment out the line that contains “MapToStoredProcedures”

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     base.OnModelCreating(modelBuilder);
     // modelBuilder.Entity<twitter_keywords>().MapToStoredProcedures();
 }

 

 

No connection string named ‘…’ could be found in the application config file.

Two-tier applications separate the presentation layer and the data layer, and all database access related objects are located in the data-tier.

When the application runs, the config file of the main project is read. In web applications, it is the web.config, in console applications the app.config file.

When you get the following runtime exception

Exception thrown: ‘System.InvalidOperationException’ in EntityFramework.dll
An exception of type ‘System.InvalidOperationException’ occurred in EntityFramework.dll but was not handled in user code
No connection string named ‘…Entities’ could be found in the application config file.

 

  1. Copy the connection string from the app.config file of the data-tier to the main project’s config file.
 <add name="USC_SocialMediaMSSQLEntities" connectionString="metadata=res://*/USC_SocialMedia_MSSQL.csdl|res://*/USC_SocialMedia_MSSQL.ssdl|res://*/USC_SocialMedia_MSSQL.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MY_SERVER;initial catalog=MY_DATABASE;user id=MY_USER;password=MY_PASWORD;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

2. This is a sample data access class in the data-layer to read data from the aspNetRoles table.

using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SocialMedia_Data {
	public class SocialMediaData {

		private USC_SocialMediaMSSQLEntities _web;

		public SocialMediaData() {

			// Set up the database connections
			_web = new USC_SocialMediaMSSQLEntities();

		}

		/// Returns the list of Roles
		public List GetRoles() {

			IEnumerable foundRoles = from aspNetRoles in _web.AspNetRoles
						 orderby aspNetRoles.DisplayOrder
						 select aspNetRoles;

			if (null == foundRoles || 0 == foundRoles.Count()) {
				return null;
			}

			return foundRoles.ToList();

		}
	}
}

delimited by end-of-file (wanted `EOF’)

When you create a file in a script and use an end of file delimiter,

if ...
  cat <<EOF> $chef_dir/attrib.json
    $json
  EOF
fi

and you indent the word EOF to look nicer, you will get the error message

warning: here-document at line … delimited by end-of-file (wanted `EOF’)
STDERR> …: line …: syntax error: unexpected end of file

To correct the script, move the EOF to the beginning of the line

if ...
  cat <<EOF> $chef_dir/attrib.json
    $json
EOF
fi

could not find filename for attribute .DS_Store in cookbook

The Macintosh workstation saves application states in .DS_Store files. When you edit your Chef cookbooks the MacOS leaves these files in many folders.

When the Chef cookbook is executed, the Chef Client reads all files in the attributes folder and tries to extract values from them. If the .DS_Store file is uploaded with the rest of the cookbook to the Chef server, the Chef cookbook execution stops with the error message:

=============================================================
Recipe Compile Error in /var/chef/cache/cookbooks/…/attributes/.DS_Store
=============================================================

Chef::Exceptions::AttributeNotFound
———————————–
could not find filename for attribute .DS_Store in cookbook …

When you test your cookbook with Test Kitchen, there is no error, so you cannot detect the existence of the file until the Chef cookbook starts to run on the instance.

Even though the.DS_Store file cannot be seen in Finder, it still can be there. It is a hidden file, and even if you enable the display of hidden files, Finder does not show it.

$ cd attributes
$ ls -a
. .. .DS_Store default.rb

To remove the .DS_Store file from the cookbook

  1. Make sure the .DS_Store file is added to the chefignore file
  2. Delete the file from the folder on your workstation
    rm .DS_Store
  3. Increment the version of the cookbook in the metadata.rb file
  4. Upload the new version of the cookbook to the Chef server
    knife cookbook upload MY_COOKBOOK --freeze

 

NotSupportedException: Unable to determine the provider name for provider factory of type ‘MySql.Data.MySqlClient.MySqlClientFactory’. Make sure that the ADO.NET provider is installed or registered in the application config

In a two-tier web application, the data layer is in a separate project. This allows better separation between the presentation layer and the data layer. This way you can reuse the data project in another application that targets the same database.

To access a MySql database you need to add the MySql.Data and MySql.Data.Entity NuGet packages to the data project.

When you develop a two-tier application that targets a MySql database you may get the runtime error

NotSupportedException: Unable to determine the provider name for provider factory of type ‘MySql.Data.MySqlClient.MySqlClientFactory’. Make sure that the ADO.NET provider is installed or registered in the application config.

Even if all database interaction is handled in the data project, and you added the MySql NuGet packages to it, you need to add the MySql.Data and MySql.Data.Entity NuGet packages to the web project too, because the Web.config file contains the connection string that includes the reference to MySql.Data.MySqlClient.

<add name="MY_CONNECTION_NAME" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=MY_DATABASE;uid=MY_USERNAME;password=MY_PASSWORD" />

At the time of writing do not use version 6.10.6.0 of the packages, it causes the error

Exception thrown: ‘System.TypeLoadException’ in mscorlib.dll
An exception of type ‘System.TypeLoadException’ occurred in mscorlib.dll but was not handled in user code
Inheritance security rules violated by type: ‘MySql.Data.MySqlClient.MySqlProviderServices’. Derived types must either match the security accessibility of the base type or be less accessible.

Until a new, corrected version is published, install version 6.9.11.0 of both packages in both projects.

For more information on how to connect to a MySql database from Visual Studio see Connect to a MySQL database from Visual Studio 2017