Skip to content

Instantly share code, notes, and snippets.

@vinyar
Forked from alexpop/kitchen_sink.rb
Created August 3, 2016 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinyar/10793bb535599fd55b8b1a1923c2b11d to your computer and use it in GitHub Desktop.
Save vinyar/10793bb535599fd55b8b1a1923c2b11d to your computer and use it in GitHub Desktop.
Script to export Chef Server nodes and add them to Chef Compliance
# encoding: utf-8
### Sample script to export Chef Server nodes and import them to Chef Compliance
### Change the 'api_url', 'api_user', 'api_pass' and 'api_org' variables below
### Change the nodes_array json suit your environment
### Go to your chef-repo and check Chef Server access first
# cd chef-repo; knife environment list
### Save this Ruby script as kitchen_sink.rb and run it like this:
# cat kitchen_sink.rb | knife exec
### Chef Compliance API docs: https://docs.chef.io/api_compliance.html
require 'json'
require 'uri'
require 'net/http'
require 'openssl'
# This extracts data from the Chef Server. Auth done by `knife exec`
# Change loginKey and any other details that will be posted to the Chef Compliance API:
nodes_array = []
nodes.find('*:*') { |n|
nodes_array << { id: n.name,
name: n.name,
hostname: n.name,
environment: n.environment,
loginUser: 'root',
loginMethod: 'ssh',
loginKey: 'my-private-key' }
}
puts "*** Successfully exported #{nodes_array.length} nodes from the Chef Server"
# This posts data to the Chef Compliance(tested against 1.3.1)
# Change these to fit your Chef Compliance server
api_url = 'https://my-chef-compliance.example.com'
api_user = 'admin'
api_pass = 'mySUPERpassword'
api_org = 'admin'
uri = URI.parse(api_url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
# Get the API_TOKEN token first
request = Net::HTTP::Post.new('/api/login')
request.content_type = 'Content-Type: application/json'
request.body = { 'userid' => api_user,
'password' => api_pass }.to_json
response = http.request(request)
if response.code == '200'
puts '*** Successfully authenticated, using the api_token now...'
else
puts "*** Failed to authenticate, reason: #{response.body} code: #{response.code}"
end
api_token = response.body
# Post the nodes to the Compliance Server
request = Net::HTTP::Post.new("/api/owners/#{api_org}/nodes")
request.add_field('Content-Type', 'application/json')
request.add_field('Authorization', "Bearer #{api_token}")
request.body = nodes_array.to_json
response = http.request(request)
if response.code == '200'
puts '*** Successfully imported the nodes in Chef Compliance'
else
puts "*** Failed to import, reason: #{response.body} code: #{response.code}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment