LWRP for deleting old builds

2016/12/07

In your cookbook, in libraries folder, create the following:

provider_cache_cleaner.rb

class BuildCacheCleaner
  # Provider for build_cache_cleaner
  class BuildCacheCleanerProvider < Chef::Provider::LWRPBase
    provides :build_cache_cleaner
    use_inline_resources
    action :delete do
      delete_count = 0
      if ::File.directory?(new_resource.cache_path)
        search_path = ::File.join(new_resource.cache_path.to_path, “#{new_resource.suffix}*\.#{new_resource.extension}”)
        cached_files = ::Dir.glob(search_path).sort_by { |f| ::File.ctime(f) }
        if cached_files.count > new_resource.keep_count
          delete_count = cached_files.count – new_resource.keep_count
        end
        files_to_delete = cached_files.first(delete_count)
        unless files_to_delete.empty?
          Chef::Log.info(“#{delete_count} cached builds will be deleted !”)
          files_to_delete.each do |file_name|
            Chef::Log.info(“Deleting file #{::File.basename(file_name)} …”)
            ::File.delete(file_name)
          end
        end
      end
      new_resource.updated_by_last_action(true) if delete_count > 0
    end
  end
end

resource_cache_cleaner.rb

class BuildCacheCleaner
  # Resource for build_cache_cleaner
  class BuildCacheCleanerResource < Chef::Resource::LWRPBase
    resource_name :build_cache_cleaner
    provides :build_cache_cleaner

    actions(:delete)
    default_action(:delete)

    attribute :keep_count, :kind_of => Integer, :required => false, :default => 5
    attribute :suffix, :kind_of => String, :required => false, :default => ‘Build’
    attribute :extension, :kind_of => String, :required => false, :default => ‘zip’
    attribute :cache_path, :kind_of => String, :required => false, :default => Chef::Config[:file_cache_path]
  end
end

string_util.rb

# String utility extension methods
class String
  def to_path(end_slash = false)
    “#{‘/’ if self[0] == ‘\\’}#{split(‘\\’).join(‘/’)}#{‘/’ if end_slash}”
  end
end

matchers.rb

# ChefSpec is a tool to unit test cookbooks in conjunction with rspec
# Learn more on the README or at https://github.com/sethvargo/chefspec.
if defined?(ChefSpec)
  def delete_build_cache_cleaner(resource_name)
    ChefSpec::Matchers::ResourceMatcher.new(:build_cache_cleaner, :delete, resource_name)
  end
end

In your recipe, use the resource as follow:

build_cache_cleaner ‘delete cached builds’ do
  keep_count 7
end

In your ChefSpec test, add the following:

it ‘deletes unused cached builds’ do
  expect(chef_run).to delete_build_cache_cleaner(‘delete cached builds’)
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.
Note 3: While I may have tested myself most of the bits of code posted here, please be aware that you’re trying the code/scripts at your own risk, and I take no responsibility for any damage that may occur on your system(s).

Advertisements

Disable Windows Server firewall with PowerShell in Chef

2015/10/13

First of all, as I said in the previous post, be aware that is a very BAD practice to disable the firewall; do so only for test purposes and a short period of time.

The following code was tested under Windows Server 2008 R2, but it should also work for Windows Server 2012.
In the default.rb file from the recipe subfolder of your cookbook, add the code:

require ‘chef/win32/version’
win_version = Chef::ReservedNames::Win32::Version.new

if (win_version.windows_server_2008_r2? ||
    win_version.windows_server_2008? ||
    win_version.windows_server_2003_r2? ||
    win_version.windows_server_2003? ||
    win_version.windows_2000?)
      disableFirewallScript =<<-EOH
        netsh advfirewall set allprofiles state off
      EOH
elsif (win_version.windows_server_2012_r2? ||
    win_version.windows_server_2012?)
      disableFirewallScript =<<-EOH
        Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
      EOH
else
  raise “Unsupported Windows version !”
end

Chef::Log.debug(“Executing ' #{disableFirewallScript} ' in PowerShell.”)

disableFirewallResult = powershell_out(disableFirewallScript)

if (disableFirewallResult.stderr.to_s != “” || disableFirewallResult.exitstatus != 0)
  raise “ExitStatus : #{disableFirewallResult.exitstatus} \r\n STDOUT : [ #{disableFirewallResult.stdout} ] \r\n STDERR : [ #{disableFirewallResult.stderr} ]”
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.


Chef error NoMethodError – nil:NilClass

2015/09/22

Had several times the error from below

NoMethodError
————-
undefined method `[]’ for nil:NilClass

and each time I forgot which was the root cause.

What’s happening is that Chef can’t find some attributes, or some array of attributes that it needs to successfully converge the cookbook.

Run the converge in debug mode: kitchen converge -l=DEBUG and on the first line containing the error, see at what .rb files it points, including the line number, and you’ll discover what attributes you’re missing from the cookbook

Update: Another form of this error that I’ve encountered was

NoMethodError
————-
private method `select’ called for nil:NilClass

and this was happening when using artifact_deploy resource from artifact cookbook.
What was really causing the problem was the fact that I was specifying a deploy_to location that was not existing (set to drive D:, when the virtual machine had only a C: drive)


Issue when zipping folder with Chef resource windows_zipfile

2015/09/18

If you receive the warning

Single directory must be specified for compression, and [folder] does not meet that criteria.

when trying to zip a file with Chef resource provider windows_zipfile from windows cookbook, well… it just means what it says: the specified folder is not a folder or doesn’t exists.

The reason I’ve spend more than an hour investigating this is because I was using artifact_deploy resource to first download a build, from which I wanted afterwards to zip only a subfolder; and also, there were several cookbook dependencies, which also had to be compiled… so there goes wasted time.

But the problem is that artifact_deploy uses versioning, so I had to add a current subfolder to point to the right location.
Just to be sure you have the right folder specified, do a

Chef::Log.warn(“Source: #{backup_path}/current/#{app_name}/subfolder

in your cookbook, and paste the output into the file manager from the virtual machine used for testing the cookbook.

Note: Chef::Log.info doesn’t work for me on simple kitchen converge (Chef 12.4), that’s why I used the warn method. Of course, on DEBUG, it’s displayed either way.

Hope this helps someone.

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


Error when deploying ZIP archive with Chef artifact cookbook

2015/09/16

If you receive the following error when trying to deploy a ZIP archive with artifact_deploy resource:

=====================================================================
Error executing action `deploy` on resource ‘artifact_deploy[sampleArchive]’
=====================================================================
Chef::Exceptions::WindowsNotAdmin
———————————
[…]
Chef::Exceptions::WindowsNotAdmin: can not get the security information for ‘C:/Users/ADMINI~1/AppData/Local/Temp/kitchen/cache/artifact_deploys/sampleArchive/0.0.1/YourArchiveHere.zip’ due to missing Administrator privileges.

you might want to try to add the following configuration to your kitchen.yml file:

  client_rb:
    file_atomic_update: false

just under

provisioner:
  name: chef_zero

The reason that I’ve used it globally in the client.rb file and not in the resource is because so far artifact_deploy doesn’t support this feature.

If you’d like that feature, modify yourself the cookbook, or contact the Riot Games team

More about atomic update under Chef: Atomic File Updates
Chef version: 12.4.0
Operating system: Windows 7 Professional

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: