Last active
March 13, 2020 14:54
-
-
Save cw2908/8d4d8a8dc677020b4d12c35ec58c2003 to your computer and use it in GitHub Desktop.
Samanage Format Export
This file contains hidden or 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
# Export incidents within date range | |
# | |
# First install the lastest Ruby version and our library via command `gem install samanage` | |
# | |
# Run with the command: `ruby script_name.rb API_TOKEN 2019-01-01 2019-12-31` | |
# or in the EU datacenter `ruby script_name.rb API_TOKEN 2019-01-01 2019-12-31 eu` | |
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 CSV writer | |
def log_to_csv(row: , filename: DEFAULT_FILENAME, headers: ) | |
write_headers = !File.exists?(filename) | |
CSV.open(filename, 'a+', write_headers: write_headers, force_quotes: true, headers: headers) do |csv| | |
csv << row | |
end | |
end | |
# Save specific fields from incidents | |
def format_incident(incident: ) | |
custom_fields = incident.dig('custom_fields_values').to_a | |
request_variables = incident.dig('request_variables').to_a | |
{ | |
'Id': incident.dig('id'), | |
'Number': incident.dig('number'), | |
'Name': incident.dig('name'), | |
'State': incident.dig('state'), | |
'Assignee': incident.dig('assignee','email') || incident.dig('assignee','name'), # Display email if user, otherwise print group name | |
'Requester': incident.dig('requester','email'), # All requesters have email | |
'Site': incident.dig('site','name'), | |
'Created At': incident.dig('created_at'), | |
'Updated At': incident.dig('updated_at'), | |
# Custom Fields | |
'My Custom Field': custom_fields.find{|cf| cf['name'] == 'My Custom Field'}.to_h.dig('value'), | |
'Impacting Work': custom_fields.find{|cf| cf['name'] == 'Impacting Work'}.to_h.dig('value'), | |
# Request Variables | |
'Some Catalog Variable': request_variables.find{|rv| rv['name'] == 'Variable Name'}.to_h.dig('value'), | |
'Software Requested': request_variables.find{|rv| rv['name'] == 'Software Requested'}.to_h.dig('value') | |
# ... | |
} | |
end | |
query_options = { | |
'created[]' => 'Select Date Range', | |
'created_custom_gte[]' => start_date, | |
'created_custom_lte[]' => end_date, | |
'layout' => 'long' | |
} | |
# Request and save incidents | |
@samanage.incidents(options: query_options).map do |incident| | |
csv_data = format_incident(incident: incident) | |
log_to_csv(row: csv_data.values, headers: csv_data.keys) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment