Last active
December 7, 2024 11:54
-
-
Save princefishthrower/81bc574c747b2a9f37bd2ed70d847d87 to your computer and use it in GitHub Desktop.
Export the source code from any Docker tag!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Extracts the source code of any Docker tag! | |
# Inspired by Sambhav Jain's post on DEV: https://dev.to/sambhav2612/reverse-engineering-a-docker-image-i8c | |
# Simply pass: | |
# 1. The desired Docker image tag you want to get the source code for | |
# 2. The target folder to put the source code in | |
# | |
# Example usage: | |
# ./export-source-from-docker-tag.sh gcr.io/google-samples/gb-frontend:v4 docker-source | |
# | |
#Produces output: | |
# WorkingDir of image is var/www/html | |
# Creating temporary container... | |
# Exporting temporary container... | |
# Extracting contents of WorkingDir to "docker-source"... | |
# Done. Source code from Docker tag "gcr.io/google-samples/gb-frontend:v4" successfully exported into folder "docker-source". | |
# Grep out the "WorkingDir", only first match, then remove everything uneeded, including leading slash (for tar later), and trim out leading or trailing spaces | |
# workingDir=$(docker image inspect gcr.io/google-samples/gb-frontend:v4 | grep -m 1 WorkingDir | sed 's/"WorkingDir"://g; s/"//g; s/,//g; s/\///; s/^[[:space:]]*//') | |
workingDir=$(docker image inspect $1 | grep -m 1 WorkingDir | sed 's/"WorkingDir"://g; s/"//g; s/,//g; s/\///; s/^[[:space:]]*//') | |
echo WorkingDir of image is $workingDir | |
# Count the number of nested folders this folder may be in, this is used for cleaner export further down | |
componentCount=$(echo $workingDir | tr -cd '/' | wc -c) | |
componentCount=$((componentCount+1)) | |
# create a temporary container, redirect hash output to /dev/null | |
echo Creating temporary container... | |
docker create --name="tmp" $1 1>/dev/null | |
# export the container as a tar | |
echo Exporting temporary container... | |
docker export "tmp" > tmp.tar | |
# remove temp container | |
docker rm "tmp" 1>/dev/null | |
# make a folder named by the second argument to move files into | |
echo Extracting contents of WorkingDir to \"$2\"... | |
sourceCodeFolderName=$2 | |
mkdir -p $sourceCodeFolderName | |
# extract the working dir into a folder called 'tmp' | |
tar -xf tmp.tar --strip-components=$componentCount -C $sourceCodeFolderName $workingDir | |
# clean up the no longer needed tar | |
rm tmp.tar | |
echo Done. Source code from Docker tag \"$1\" successfully exported into folder \"$2\". |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have a situation where the first
WorkingDir
item is empty. So I trim empty lines and only use the first item (Line: 21):