Allow adding extra HTTP headers to Jenkins requests

In some network setups Jenkins may be hidden behind complex reverse
proxy setups that require additional custom headers to be set on
each request in order to pass them trough

Allow providing such headers using JENKINS_API_EXTRA_HEADERS environment
variable

Change-Id: If071c5c707f916ba5f4f2c371ec600b7476bf723
This commit is contained in:
Aigars Mahinovs 2018-08-13 15:41:08 +02:00
parent 93515ae07d
commit 811a6cffc8
2 changed files with 36 additions and 0 deletions

View File

@ -321,6 +321,14 @@ class Jenkins(object):
self.timeout = timeout
self._session = WrappedSession()
extra_headers = os.environ.get("JENKINS_API_EXTRA_HEADERS", "")
if extra_headers:
logging.warning("JENKINS_API_EXTRA_HEADERS adds these HTTP headers: %s", extra_headers.split("\n"))
for token in extra_headers.split("\n"):
if ":" in token:
header, value = token.split(":", 1)
self._session.headers[header] = value.strip()
if os.getenv('PYTHONHTTPSVERIFY', '1') == '0':
logging.debug('PYTHONHTTPSVERIFY=0 detected so we will '
'disable requests library SSL verification to keep '

View File

@ -120,6 +120,34 @@ class JenkinsMaybeAddCrumbTest(JenkinsTestBase):
self.assertFalse('.crumb' in request.headers)
class JenkinsMaybeAddHeaders(JenkinsTestBase):
@patch('jenkins.requests.Session.send', autospec=True)
def test_simple(self, session_send_mock):
session_send_mock.return_value = build_response_mock(
404, reason="Not Found")
request = jenkins.requests.Request('GET', 'http://example.com/job/TestJob')
with patch.dict('os.environ', {}):
j = jenkins.Jenkins(self.base_url, 'test', 'test')
request = j._session.prepare_request(request)
self.assertEqual(request.headers, self.j._session.headers)
self.assertNotIn("X-Auth", request.headers)
@patch('jenkins.requests.Session.send', autospec=True)
def test_add_header(self, session_send_mock):
session_send_mock.return_value = build_response_mock(
404, reason="Not Found")
request = jenkins.requests.Request('GET', 'http://example.com/job/TestJob')
with patch.dict('os.environ', {"JENKINS_API_EXTRA_HEADERS": "X-Auth: 123\nX-Key: 234"}):
j = jenkins.Jenkins(self.base_url, 'test', 'test')
request = j._session.prepare_request(request)
self.assertEqual(request.headers["X-Auth"], "123")
self.assertEqual(request.headers["X-Key"], "234")
class JenkinsOpenTest(JenkinsTestBase):
@patch('jenkins.requests.Session.send', autospec=True)