Sunday, March 16, 2025

Chef client cookbook to run from local system : Check validity of the certificates and remove expired certificates

To perform this activity using the chef client we will create new cookbook display_certificates.

First go to the chef cookbook location and create below directories

  cd cookbooks
  mkdir -p display_certificates/recipes
  mkdir -p display_certificates/files/default 

Once we create the default directories. We need to create a sh script in default directory and rb script in recipes directory.
our directory structure will now looks like this

  ~/cookbooks
     display_certifies
        recipes
           display_certificates.sh
        files
           default
           	display_certificates.rb 

Copy the below content into the display_certificates.sh. change keystore path and password as per keystore location. aliasname is certificatename which can be used to delete certificate from keystore.

   #!/bin/bash
  KEYSTORE_PATH="/opt/sw/keystore/keystore.jks"
  KEYSTORE_PASSWORD="changeit"
  keytool -list -v -keystore "$KEYSTORE_PATH" -storepass "$KEYSTORE_PASSWORD" | grep -E "Alias|Valid"
  keytool -delete -alias "aliasname" -keystore "$KEYSTORE_PATH" -storepass "$KEYSTORE_PASSWORD" 
Copy the below content into the display_certificates.rb
#recipes/display_certificates.rb
cookbook_file '/tmp/display_certificates.sh' do
  source 'display_certificates.sh'
  mode '0755'
  owner 'root'
  group 'root'
  action :create
end

execute 'display_certificates' do
  command 'bash /tmp/display_certificates.sh'
  live_stream true
end 
Save the files and run the chef client using the below code
chef-client -zr recipe[display_certificates::display_certificates]
It will display the certificates in the keystore file with certificatename and its expiry date.

No comments: