Method: InspecPlugins::Compliance::API.profiles

Defined in:
lib/plugins/inspec-compliance/lib/inspec-compliance/api.rb

.profiles(config, profile_filter = nil) ⇒ Object

return all compliance profiles available for the user the user is either specified in the options hash or by default the username of the account is used that is logged in



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/plugins/inspec-compliance/lib/inspec-compliance/api.rb', line 25

def self.profiles(config, profile_filter = nil) # rubocop:disable PerceivedComplexity, Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength
  owner = config['owner'] || config['user']

  # Chef Compliance
  if is_compliance_server?(config)
    url = "#{config['server']}/user/compliance"
  # Chef Automate2
  elsif is_automate2_server?(config)
    url = "#{config['server']}/compliance/profiles/search"
  # Chef Automate
  elsif is_automate_server?(config)
    url = "#{config['server']}/profiles/#{owner}"
  else
    raise ServerConfigurationMissing
  end

  headers = get_headers(config)
  if profile_filter
    _owner, id, ver = profile_split(profile_filter)
  else
    id, ver = nil
  end

  if is_automate2_server?(config)
    body = { owner: owner, name: id }.to_json
    response = InspecPlugins::Compliance::HTTP.post_with_headers(url, headers, body, config['insecure'])
  else
    response = InspecPlugins::Compliance::HTTP.get(url, headers, config['insecure'])
  end
  data = response.body
  response_code = response.code
  case response_code
  when '200'
    msg = 'success'
    profiles = JSON.parse(data)
    # iterate over profiles
    if is_compliance_server?(config)
      mapped_profiles = []
      profiles.values.each { |org|
        mapped_profiles += org.values
      }
    # Chef Automate pre 0.8.0
    elsif is_automate_server_pre_080?(config)
      mapped_profiles = profiles.values.flatten
    elsif is_automate2_server?(config)
      mapped_profiles = []
      profiles['profiles'].each { |p|
        mapped_profiles << p
      }
    else
      mapped_profiles = profiles.map { |e|
        e['owner_id'] = owner
        e
      }
    end
    # filter by name and version if they were specified in profile_filter
    mapped_profiles.select! do |p|
      (!ver || p['version'] == ver) && (!id || p['name'] == id)
    end
    return msg, mapped_profiles
  when '401'
    msg = '401 Unauthorized. Please check your token.'
    return msg, []
  else
    msg = "An unexpected error occurred (HTTP #{response_code}): #{response.message}"
    return msg, []
  end
end