First install Ruby 2.6 or higher. Then gem install samanage
Run from the command:
ruby script_name.rb API_TOKEN 2018-01-01 2018-12-31
or ruby script_name.rb API_TOKEN 2018-01-01 2018-12-31 eu
if on the EU datacenter.
require 'samanage'
require 'csv'
api_token, start_date, end_date, datacenter = ARGV
@samanage = Samanage::Api.new(token: api_token, datacenter: datacenter)
DEFAULT_FILENAME = "Incident Report #{DateTime.now.strftime("%b-%d-%Y-%l%M")}.csv"
# Simple hash to csv
def log_to_csv(row: , filename: DEFAULT_FILENAME)
write_headers = !File.exists?(filename)
CSV.open(filename, 'a+', write_headers: write_headers, force_quotes: true, headers: row.keys) do |csv|
csv << row.values
end
end
# Save specific fields from incident and flatten to key pair
def format_incident(incident: )
custom_fields = incident.dig('custom_fields_values').to_a
{
id: incident.dig('id'),
number: incident.dig('number'),
name: incident.dig('name'),
state: incident.dig('state'),
assignee: incident.dig('assignee','name'), # I picked assignee->name because groups do not have an email
requester: incident.dig('requester','email'), # All requesters have email
category: incident.dig('category','name'),
subcategory: incident.dig('subcategory','name'),
some_custom_field: custom_fields.find{|cf| cf['name'] == 'Custom Field Name'}.to_h['value'],
# ...
}
end
query_options = {
'updated[]' => 'Select Date Range',
'updated_custom_gte[]' => start_date,
'updated_custom_lte[]' => end_date,
verbose: true
}
# Request and save incidents
incident_ids = @samanage.incidents(options: query_options).map{|i| i['id']}.uniq
puts "Exporting #{incident_ids.count} incidents"
incident_ids.each do |incident_id|
incident = @samanage.find_incident(id: incident_id, options: {layout: 'long'})[:data]
puts "Exporting Incident ##{incident['number']}"
formatted_incident = format_incident(incident: incident)
log_to_csv(row: formatted_incident)
end