File: foremancli

package info (click to toggle)
foremancli 1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 92 kB
  • ctags: 9
  • sloc: ruby: 173; makefile: 8
file content (209 lines) | stat: -rwxr-xr-x 6,204 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env ruby
# Copyright (C) 2011 Vijay Brian Gupta brian.gupta@brandorr.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
# USA.

require "optparse"

collections_filterable = [
  :architectures,
  :common_parameters,
  :config_templates,
  :domains,
  :environments,
  :fact_values,
  :hosts,
  :hostgroups,
  :media,
  :puppetclasses,
  :reports,
  :roles,
  :settings,
  :lookup_keys,
  :dashboard,
  :operatingsystems,
  :subnets,
  :ptables,
  :users
]

collections = [
  :auth_source_ldaps,
  :hypervisors,
  :lookup_values,
  :smart_proxies,
  :statistics,
  :usergroups,
]

collections_not_implemented = [ :audits, :bookmarks ]

@foreman_user = ENV['FOREMAN_USER']     if ENV['FOREMAN_USER']
@foreman_pass = ENV['FOREMAN_PASSWORD'] if ENV['FOREMAN_PASSWORD']
@foreman_url  = ENV['FOREMAN_SERVER']   if ENV['FOREMAN_SERVER']

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: " + File.basename($0) + " [options] ..."

  options[:debug] = false
  opts.on( "-d", "--debug", "Output more information" ) do
    options[:debug] = true
  end
  options[:username] = false
  opts.on( '-u', '--user USER', "Foreman user") do |f|
    options[:username] = f
  end
  options[:password] = false
  opts.on( "-p", "--pass PASSWORD", "Foreman password" ) do |f|
    options[:password] = f
  end
  options[:server] = false
  opts.on( "-s", "--server URL", "Foreman Server URL" ) do |f|
    options[:server] = f
  end
  options[:json] = false
  opts.on( "--json", "JSON output" ) do
    options[:json] = true
  end
  options[:yaml] = false
  opts.on( "--yaml", "YAML output" ) do
    options[:yaml] = true
  end
  options[:status] = false
  opts.on( "--status", "Foreman status" ) do
    options[:status] = true
  end
# options[:dashboard] = false
# opts.on( "--dashboard", "Foreman dashboard" ) do |f|
#   options[:dashboard] = f
# end
  options[:custom] = false
  opts.on( "--custom COLLECTION", "Custom COLLECTION string, see: http://theforeman.org/projects/foreman/wiki/API" ) do |f|
    options[:custom] = f
  end
  collections_filterable.each do |collection|
    options[collection] = false
    opts.on("--#{collection} [filter]", "Retrieve a list of #{collection}") do |f|
      options[collection] = f || true
    end
  end
  collections.each do |collection|
    options[collection] = false
    opts.on("--#{collection}", "Retrieve a list of #{collection}") do
      options[collection] = true
    end
  end
  collections_not_implemented.each do |collection|
    options[collection] = false
    opts.on("--#{collection}", "Not implemented") do
      options[collection] = true
    end
  end
  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    puts ""
    puts "     ENVIRONMENT VARIABLES:"
    puts ""
    puts "     FOREMAN_SERVER                  Foreman Server URL"
    puts "     FOREMAN_USER                    Foreman user"
    puts "     FOREMAN_PASSWORD                Foreman password"
    puts ""
    puts "     CLI options take precedence over ENVIRONMENT VARIABLES"
    puts ""
    puts "     FILTERS:"
    puts ""
    puts "     Please see:"
    puts "     http://theforeman.org/projects/foreman/wiki/Search_API"
    puts ""
    puts "     Examples:"
    puts "     --hosts \"domain = domain.com AND class = squid\""
    puts "     --hosts \"domain = domain.com AND facts.architecture = x86_64 AND \\"
    puts "       class = module::class"
    puts "     --classes \"name = squid\""
    puts "     --domains \"name = domain.com\""
    puts ""
    exit 1
  end
end.parse!
if options.values.uniq == [false]
  warn "Use -h, --help for usage."
  exit 1
end

require "rest_client"
require "json"
require "yaml"

@foreman_user = options.delete(:username) if options[:username]
@foreman_pass = options.delete(:password) if options[:password]
@foreman_url  = options.delete(:server)   if options[:server]
@usejson      = options.delete(:json)     if options[:json]
@useyaml      = options.delete(:yaml)     if options[:yaml]
@custom       = options.delete(:custom)   if options[:custom]
@status       = options.delete(:status)   if options[:status]

RestClient.log = 'stdout' if options.delete(:debug)

def get_collection(path, options = {})
  JSON.parse(RestClient::Request.new({:method  => :get,
                                     :url     => "#{@foreman_url}/#{path.to_s.chomp('/')}",
                                     :user    => @foreman_user, :password => @foreman_pass,
                                     :headers => { :accept => :json, :content_type => :json }}.merge(options)).execute.to_s)
end

def search_collection(path,search)
  get_collection(path, :url => "#{@foreman_url}/#{path}?search=#{URI.encode(search)}")
end

def format
  return "json" if @usejson
  return "yaml" if @useyaml
end

def print_response response
  puts(case format
      when "json"
        JSON.pretty_generate(response)
      when "yaml"
        YAML.dump(response)
      else
        r = response.first
        if r.is_a?(Hash)
          # we simply return host list
          if r.first[0] == "host"
            response.map{|h| h["host"]["name"]}
          else
            response.map{|o| o.inspect}
          end
        else
          response.join("\n")
        end
      end)
end

options.each do |collection, filter|
  next unless filter
  if filter == true
    print_response(get_collection(collection))
  else
    print_response(search_collection(collection, filter))
  end
end

print_response(get_collection(@custom)) if @custom

puts JSON.pretty_generate(get_collection("status")) if @status