building docker image using a remote docker file in github using python sdk

290 views Asked by At

I am able to build docker image using python sdk. if the dockerfile is available on my local machine.

client = docker.from_env()
image, build_log = client.images.build(path = "./", tag=image_name,rm=True)   

Now, My docker files will be maintained in github repository, I should pull them and build the images. python sdk doc says build method accepts path or file objects.

I was able to read the content of the docker file from github using pyGithub (API3) repository

g = Github(base_url=url, login_or_token=accessToken, verify=False)
dmc = g.get_organization(org_name)
repo = dmc.get_repo(repoName)
contents = repo.get_contents(dockerfile_name, "master")

I am not sure how to convert above contents object(ContentFile.ContentFile) to a python file object so that I can use it to build the image as below

client = docker.from_env()
image, build_log = client.images.build(fileobj = contents_file_obj, tag=image_name,rm=True)
1

There are 1 answers

6
Roshan Chauhan On

Below working piece of code can be used to bring out Python file obj from ContentFile.ContentFile:

import io
from github import Github 
import docker

# docker client
client = docker.from_env()

# github repo
g = Github(base_url=url, login_or_token=accessToken, verify=False)
dmc = g.get_organization(org_name)
repo = dmc.get_repo(repoName)
contents = repo.get_contents(dockerfile_name, "master")

# decoding contents of file and creating file obj out of it
decoded_content_str = contents.decoded_content.decode('utf-8')
contents_file_obj = io.StringIO(decoded_content_str)

# building image out of contents file obj
client = docker.from_env()
image, build_log = client.images.build(
                       fileobj=contents_file_obj,
                       tag=image_name,
                       rm=True)

In above code,
method decoded_content of contents (obj of class ContentFile.ContentFile) returns byte string content of file. which decoded into string by .decode('utf-8').
then decoded_content_str is used to create IO object (same as file object in python) using io.StringIO