2 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
16 # @author: David Blaisonneau <david.blaisonneau@orange.com>
17 # @author: Arnaud Morin <arnaud1.morin@orange.com>
21 from requests_futures.sessions import FuturesSession
22 from pprint import pformat
28 Class to deal with the foreman API v2
30 def __init__(self, password, login='admin', ip='127.0.0.1', printErrors=False):
32 Init the API with the connection params
34 @param password: authentication password
35 @param password: authentication login - default is admin
36 @param ip: api ip - default is localhost
39 self.base_url = 'http://{}/api/v2/'.format(ip)
40 self.headers = {'Accept': 'version=2',
41 'Content-Type': 'application/json; charset=UTF-8'}
42 self.auth = (login, password)
44 self.printErrors = printErrors
46 def list(self, obj, filter=False, only_id=False, limit=20):
48 Get the list of an object
50 @param obj: object name ('hosts', 'puppetclasses'...)
51 @param filter: filter for objects
52 @param only_id: boolean to only return dict with name/id
53 @return RETURN: the list of the object
55 self.url = '{}{}/?per_page={}'.format(self.base_url, obj, limit)
57 self.url += '&search={}'.format(filter)
58 self.resp = requests.get(url=self.url, auth=self.auth,
61 if self.__process_resp__(obj) is False:
63 if type(self.res['results']) is list:
64 return dict((x['name'], x['id']) for x in self.res['results'])
65 elif type(self.res['results']) is dict:
67 for v in self.res['results'].values():
69 r[vv['name']] = vv['id']
74 return self.__process_resp__(obj)
76 def get(self, obj, id, sub_object=None):
80 @param obj: object name ('hosts', 'puppetclasses'...)
81 @param id: the id of the object (name or id)
82 @return RETURN: the targeted object
84 self.url = '{}{}/{}'.format(self.base_url, obj, id)
86 self.url += '/' + sub_object
87 self.resp = requests.get(url=self.url, auth=self.auth,
89 if self.__process_resp__(obj):
93 def get_id_by_name(self, obj, name):
94 """ Function get_id_by_name
95 Get the id of an object
97 @param obj: object name ('hosts', 'puppetclasses'...)
98 @param id: the id of the object (name or id)
99 @return RETURN: the targeted object
101 list = self.list(obj, filter='name = "{}"'.format(name),
102 only_id=True, limit=1)
103 return list[name] if name in list.keys() else False
105 def set(self, obj, id, payload, action='', async=False):
109 @param obj: object name ('hosts', 'puppetclasses'...)
110 @param id: the id of the object (name or id)
111 @param action: specific action of an object ('power'...)
112 @param payload: the dict of the payload
113 @param async: should this request be async, if true use
114 return.result() to get the response
115 @return RETURN: the server response
117 self.url = '{}{}/{}'.format(self.base_url, obj, id)
119 self.url += '/{}'.format(action)
120 self.payload = json.dumps(payload)
122 session = FuturesSession()
123 return session.put(url=self.url, auth=self.auth,
124 headers=self.headers, data=self.payload)
126 self.resp = requests.put(url=self.url, auth=self.auth,
127 headers=self.headers, data=self.payload)
128 if self.__process_resp__(obj):
132 def create(self, obj, payload, async=False):
136 @param obj: object name ('hosts', 'puppetclasses'...)
137 @param payload: the dict of the payload
138 @param async: should this request be async, if true use
139 return.result() to get the response
140 @return RETURN: the server response
142 self.url = self.base_url + obj
143 self.payload = json.dumps(payload)
145 session = FuturesSession()
146 return session.post(url=self.url, auth=self.auth,
147 headers=self.headers, data=self.payload)
149 self.resp = requests.post(url=self.url, auth=self.auth,
150 headers=self.headers,
152 return self.__process_resp__(obj)
154 def delete(self, obj, id):
156 Delete an object by id
158 @param obj: object name ('hosts', 'puppetclasses'...)
159 @param id: the id of the object (name or id)
160 @return RETURN: the server response
162 self.url = '{}{}/{}'.format(self.base_url, obj, id)
163 self.resp = requests.delete(url=self.url,
165 headers=self.headers, )
166 return self.__process_resp__(obj)
168 def __process_resp__(self, obj):
169 """ Function __process_resp__
170 Process the response sent by the server and store the result
172 @param obj: object name ('hosts', 'puppetclasses'...)
173 @return RETURN: the server response
176 if self.resp.status_code > 299:
177 self.errorMsg = ">> Error {} for object '{}'".format(self.resp.status_code,
180 self.ret = json.loads(self.resp.text)
181 self.errorMsg += pformat(self.ret[list(self.ret.keys())[0]])
183 self.ret = self.resp.text
184 self.errorMsg += self.ret
188 self.res = json.loads(self.resp.text)
189 if 'results' in self.res.keys():
190 return self.res['results']
194 ret = pformat(self.base_url) + "\n"
195 ret += pformat(self.headers) + "\n"
196 ret += pformat(self.auth) + "\n"