Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mrxinu/0b848627c90ef3b05a7df5312fd60c5e to your computer and use it in GitHub Desktop.
Save mrxinu/0b848627c90ef3b05a7df5312fd60c5e to your computer and use it in GitHub Desktop.

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.

# ruby script_name.rb API_TOKEN 2019-01-01 2019-12-31
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 incident and flatten to key pair
def format_incident(incident: )
  {
    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'),
    # ...
  }
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).each 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