Skip to content

Gvegayon usable scripts #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 10 additions & 23 deletions twostep-container-build/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -173,17 +173,11 @@ runs:
id: pull-image
shell: bash
run: |
# Ensuring we can pull the image, if cache exists
docker pull ${{ inputs.registry }}${{ inputs.image }}:dependencies-${{ steps.image-tag.outputs.tag }} || \
export IMAGE_NOT_FOUND=tue

if [ -n "$IMAGE_NOT_FOUND" ]; then
echo "Image was not found, it will be built."
echo "image-found=false" >> $GITHUB_OUTPUT
else
echo "Image found, we will inspect the labels to check for cache."
echo "image-found=true" >> $GITHUB_OUTPUT
fi
python ${GITHUB_ACTION_PATH}/scripts/check_image.py \
--registry ${{ inputs.registry }} \
--image ${{ inputs.image }} \
--tag dependencies-${{ steps.image-tag.outputs.tag }} \
--output $GITHUB_OUTPUT

- name: Checking if matches cache
if: steps.pull-image.outputs.image-found == 'true'
Expand All @@ -192,18 +186,11 @@ runs:
run: |

# Inspecting the image
docker inspect \
${{ inputs.registry }}${{ inputs.image }}:dependencies-${{ steps.image-tag.outputs.tag }} \
--format='{{ index .Config.Labels "TWO_STEP_BUILD_CACHE_KEY" }}' > \
${{ github.sha }}_cache_hash

if [ "$(cat ${{ github.sha }}_cache_hash)" != "${{ inputs.first-step-cache-key }}" ]; then
echo "Cache hash does not match. Rebuilding the image..."
echo "cache-hit=false" >> $GITHUB_OUTPUT
else
echo "Cache hash matches (all good!)."
echo "cache-hit=true" >> $GITHUB_OUTPUT
fi
python ${GITHUB_ACTION_PATH}/scripts/compare_images.py \
--image ${{ inputs.registry }}${{ inputs.image }}:dependencies-${{ steps.image-tag.outputs.tag }} \
--key ${{ inputs.first-step-cache-key }} \
--output $GITHUB_OUTPUT \
--label TWO_STEP_BUILD_CACHE_KEY

- name: Build and push
if: steps.cache.outputs.cache-hit != 'true' || steps.pull-image.outputs.image-found != 'true'
Expand Down
56 changes: 56 additions & 0 deletions twostep-container-build/scripts/check_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import argparse
import subprocess
import sys

def parse_args():
"""
Check if an image exists in a registry.

The script will attempt to pull the image from the registry.
If the image is found, it will write 'image-found=true' to the output file.
If the image is not found, it will write 'image-found=false' to the output file.

Examples:
python check_image.py -r docker.io/library -i alpine -t 3.12 -o output.txt
"""
parser = argparse.ArgumentParser(
description=parse_args.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument('-r', '--registry', required=True, help='The registry where the image is stored.')
parser.add_argument('-i', '--image', required=True, help='The image name.')
parser.add_argument('-t', '--tag', required=True, help='The image tag.')
parser.add_argument('-o', '--output', help='The output file to write the result to.')
parser.add_argument('-s', '--strategy', default='docker', help='The strategy to use for pulling the image. Default: docker')

return parser.parse_args()

def main():
args = parse_args()

registry = args.registry
image = args.image
tag = args.tag
output = args.output
strategy = args.strategy

if not registry.endswith('/'):
registry += '/'

try:
subprocess.run(
[strategy, 'pull', f'{registry}{image}:{tag}'],
check=True
)
image_found = True
except subprocess.CalledProcessError:
image_found = False

if output:
with open(output, 'a') as f:
f.write(f'image-found={"true" if image_found else "false"}\n')

print("Image found." if image_found else "Image was not found.")

if __name__ == "__main__":
main()
89 changes: 89 additions & 0 deletions twostep-container-build/scripts/check_image.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#!/usr/bin/env bash

# Default values
OUTPUT=""
STRATEGY="docker"

# Parse flags
while [[ "$#" -gt 0 ]]; do
case $1 in
-r|--registry) REGISTRY="$2"; shift ;;
-i|--image) IMAGE="$2"; shift ;;
-t|--tag) TAG="$2"; shift ;;
-o|--output) OUTPUT="$2"; shift ;;
-s|--strategy) STRATEGY="$2"; shift ;;
-h|--help)
echo "Check if an image exists in a registry."
echo ""
echo "The script will attempt to pull the image from the registry."
echo "If the image is found, it will write 'image-found=true' to the output file."
echo "If the image is not found, it will write 'image-found=false' to the output file."
echo ""
echo "Usage: $0 -r <registry> -i <image> -t <tag> [-o <output>]"
echo ""
echo "Options:"
echo " -r, --registry The registry where the image is stored."
echo " -i, --image The image name."
echo " -t, --tag The image tag."
echo " -o, --output The output file to write the result to."
echo " -s, --strategy The strategy to use for pulling the image. Default: docker"
echo ""
echo "Examples"
echo "----------"
echo ""
echo "Using GitHub actions, you could use it as follows:"
echo ""
echo "- name: Check if image exists"
echo " run: |"
echo " ./check_image.sh -r docker.io/library -i alpine -t 3.12 -o \$GITHUB_OUTPUT"
echo ""
exit 0
;;
*)
echo "Unknown parameter passed: $1"
echo "Usage: $0 -r <registry> -i <image> -t <tag> [-o <output>]"
exit 1
;;
esac
shift
done

# Check required parameters
if [ -z "${REGISTRY}" ] || [ -z "${IMAGE}" ] || [ -z "${TAG}" ]; then
echo "Error: Missing required parameters."
echo "Usage: $0 -r <registry> -i <image> -t <tag> [-o <output> -s <strategy>]"
exit 1
fi

# Ensuring the registry has a trailing slash
if [ "${REGISTRY: -1}" != "/" ]; then
REGISTRY="${REGISTRY}/"
fi

# Ensuring we can pull the image, if cache exists
if [ "${STRATEGY}" == "docker" ] || [ "${STRATEGY}" == "podman" ]; then

${STRATEGY} pull ${REGISTRY}${IMAGE}:${TAG} || \
export IMAGE_NOT_FOUND=true
else
echo "Error: Unknown strategy '${STRATEGY}'"
exit 1
fi

if [ -n "$IMAGE_NOT_FOUND" ]; then
echo "Image was not found."

if [ -z "${OUTPUT}" ]; then
exit 0
fi

echo "image-found=false" >> ${OUTPUT}
else
echo "Image found."

if [ -z "${OUTPUT}" ]; then
exit 0
fi

echo "image-found=true" >> ${OUTPUT}
fi
84 changes: 84 additions & 0 deletions twostep-container-build/scripts/compare_images.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import argparse
import subprocess
import sys

def main():
"""
This script inspects a given Docker image, checks the TWO_STEP_BUILD_CACHE_KEY
label, and compares it to a provided cache key. If they match, it reports a
cache hit; otherwise, it reports a mismatch.

Examples:
python compare_images.py \
--image ghcr.io/cdcgov/cfa-actions \
--label TWO_STEP_BUILD_CACHE_KEY \
--key first-step-cache-key \
--output $GITHUB_OUTPUT
"""
parser = argparse.ArgumentParser(
description=main.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'-i', '--image', required=True,
help='Full image name (e.g. azurecr.io/cdcgov/cfa-actions).'
)
parser.add_argument(
'-l', '--label', required=True,
help='Label to check for in the image.'
)
parser.add_argument(
'-k', '--key', required=True,
help='Expected cache key (first-step-cache-key).'
)
parser.add_argument(
'-o', '--output', default=None,
help='Optional path for writing outputs.'
)
parser.add_argument(
'-s', '--strategy', default='docker',
help='Strategy to use for pulling the image. Default: docker.'
)


args = parser.parse_args()

# Construct the full image reference, e.g., ghcr.io/cdcgov/cfa-actions:dependencies-latest
image = args.image

try:
# Run docker inspect to get the TWO_STEP_BUILD_CACHE_KEY label
# The --format directive returns only the label's value
result = subprocess.check_output([
args.strategy, "inspect",
"--format={{ index .Config.Labels \"" + args.label + "\" }}",
image
])
except subprocess.CalledProcessError:
print("Error: Unable to inspect the image or the image does not exist.")
sys.exit(1)

label_value = result.decode("utf-8").strip()

# Compare label_value with the expected cache key
print(f"Expected : {args.key}")
print(f"Found : {label_value}")
if label_value != args.key:
print("Cache hash does not match.")
output_line = "cache-hit=false"
else:
print("Cache hash matches (all good!).")
output_line = "cache-hit=true"

# If a GitHub output file is provided, append the result line
if args.output:
try:
with open(args.output, 'a', encoding='utf-8') as f:
f.write(f"{output_line}\n")
except OSError as e:
print(f"Warning: Could not write to GitHub output file ({e}).")
else:
print(output_line)

if __name__ == "__main__":
main()
Loading