Last active
March 7, 2023 18:44
-
-
Save JSONOrona/180a4b4c3d67616f3fe86fa11a12b296 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'chef/server_api' | |
require 'openssl' | |
# Set the Chef Infra Server API endpoint and credentials | |
server_url = 'https://chef-server.example.com/organizations/myorg' | |
client_name = 'myclient' | |
client_key = '/path/to/myclient.pem' | |
# Set the SSL verification mode based on an environment variable | |
ssl_verify_mode = if ENV['CHEF_IGNORE_SSL_CERTIFICATE_VALIDATION'] == 'true' | |
OpenSSL::SSL::VERIFY_NONE | |
else | |
OpenSSL::SSL::VERIFY_PEER | |
end | |
# Create a new instance of Chef::ServerAPI | |
api = Chef::ServerAPI.new(server_url, { | |
client_name: client_name, | |
signing_key_filename: client_key, | |
ssl_verify_mode: ssl_verify_mode | |
}) | |
# The name of the node to check | |
node_name = 'mynode.example.com' | |
# Check if the node exists | |
begin | |
node = api.get("nodes/#{node_name}") | |
puts "Node #{node_name} exists." | |
# Add a recipe to the node's run list | |
if node['run_list'].include?('recipe[mycookbook::myrecipe]') | |
puts "Recipe already in the node's run list." | |
else | |
node.run_list << 'recipe[mycookbook::myrecipe]' | |
api.put("nodes/#{node_name}", node) | |
puts "Recipe added to the node's run list." | |
end | |
rescue Net::HTTPServerException => e | |
if e.response.code == '404' | |
puts "Node #{node_name} does not exist." | |
else | |
puts "Error checking if node #{node_name} exists: #{e.message}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment