Search code examples
jenkinsjenkins-pluginsjenkins-api

Access Jenkins S3Publisher artifacts via python api or REST call?


How can we access S3Publisher artifacts via REST or python lib like jenkinsapi?

I guess, I can do something like this but then I'll need to handle auth whereas all the other jenkinsapi calls have auth baked in already.

from jenkinsapi.build import Build

def get_build_url(self, build: Build):
    """url for build page"""
    return build.get_result_url().split(str(build.get_number()))[0]

def get_s3_artifact(self, build: Build, artifact_name:str):
    url = "{}/s3/download/{}".format(self.get_build_url(build))
    wget.download(url)

Solution

  • We can use a standard process for downloading a file via python requests library as jenkinsapi uses requests.

    Assuming that self._server is an instance of jenkinsapi.jenkins.Jenkins.Jenkins class. We can build a url to match what we'd expect to download an artifact via the links beneath build/s3. We then use requests to get that url content and write it to a file.

    def get_s3_artifact(self, build: Build, artifact_name:str, output_dir: Path) -> Path:
        output_file = output_dir / artifact_name
        if output_file.exists():
            raise FileExistsError('[ERROR] {}:get_s3_artifact - cannot overwrite {}'.format(self.__class__,
                                                                                            output_file.absolute()))
        output_dir.mkdir(exist_ok=True, parents=True)
    
        url = "{}{}/s3/download/{}".format(self.get_build_url(build), str(build.get_number()), artifact_name)
        r = self._server.requester.get_url(url, stream=True)
        with output_file.open('wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
    
        return output_file