Got it! You want to download a Helm chart, pull all the container images the chart uses, and package both the Helm chart and all the pulled images together as a single artifact (e.g., a tarball) for offline or reproducible use.
Here's a full detailed approach to do exactly that:
Goal
code
Download Helm chart archive (.tgz)
Extract and parse image references from the chart (via helm template)
Pull all referenced container images
Save each image as a tar archive (docker save)
Package the Helm chart archive and all image tarballs together into a single artifact (tarball)
Prerequisites
code
helm installed and configured
docker installed and running
bash and standard Unix tools
(Optional) jq, yq if you want to parse YAML more robustly
Save the script as package-helm-images.sh
Make executable: chmod +x package-helm-images.sh
Run it: ./package-helm-images.sh
Result
code
$OUTPUT_DIR will contain:
The Helm chart .tgz
All container images saved as tar (.tar) files
./${CHART_NAME}_${CHART_VERSION}_artifact.tar.gz that bundles everything
To consume this artifact later:
code
Extract the artifact on offline machine:
tar xzvf mysql_8.7.0_artifact.tar.gz
code
Load the Docker images:
for f in *.tar; do docker load -i "$f"; done
code
Use the Helm chart locally:
helm install my-release ./mysql-8.7.0.tgz
Your script and approach is solid and should work well for packaging a Helm chart and all its container images into a single artifact for offline usage.
Below is a clean, slightly enhanced version of your script with additional comments and minor robustness improvements that you may find useful:
bash
#!/bin/bash
set -euo pipefail
# === Parameters ===
CHART_REPO="stable"
CHART_NAME="mysql"
CHART_VERSION="8.7.0"
OUTPUT_DIR="./artifact"
# === Prepare output dir ===
mkdir -p "$OUTPUT_DIR"
echo "Adding Helm repo (if needed)..."
helm repo add "$CHART_REPO" "https://charts.helm.sh/stable" || true
helm repo update
echo "Downloading Helm chart..."
helm pull "$CHART_REPO/$CHART_NAME" --version "$CHART_VERSION" --destination "$OUTPUT_DIR"
CHART_FILE="$OUTPUT_DIR/${CHART_NAME}-${CHART_VERSION}.tgz"
echo "Extracting image references from Helm chart templates..."
# Render templates, then grep for image references.
# This uses a simple regex matching 'image: <image-name>'
# You can customize or enhance with yq/jq for more complex extraction.
IMAGES=$(helm template "$CHART_FILE" | grep -oP '(?<=image:\s)[^ ]+' | sort -u)
if [ -z "$IMAGES" ]; then
echo "No images found in Helm chart templates, exiting..."
exit 1
fi
echo "Images found:"
echo "$IMAGES"
echo "Pulling and saving images..."
for img in $IMAGES; do
echo "Pulling image: $img"
docker pull "$img"
# Replace / and : with _ for safe filenames
filename=$(echo "$img" | sed 's/[\/:]/_/g')
tarball="${OUTPUT_DIR}/${filename}.tar"
echo "Saving image $img to $tarball"
docker save "$img" -o "$tarball"
done
echo "Packaging the Helm chart and all saved images into a single artifact..."
pushd "$OUTPUT_DIR" > /dev/null
tar czvf "../${CHART_NAME}_${CHART_VERSION}_artifact.tar.gz" ./
popd > /dev/null
echo "Artifact created at ./${CHART_NAME}_${CHART_VERSION}_artifact.tar.gz"
echo "Done."
Notes and Suggestions
The grep -oP '(?<=image:\s)[^ ]+' assumes the Helm templates expose images with image: <image>. Some charts have images defined differently or split into repository + tag fields. For a fully robust solution, consider parsing the rendered YAML with yq or directly inspecting .Values keys for image information.
Alternatively, you can render with helm template and then use a tool like yq to extract all fields named image:
Assign the full path of the downloaded chart archive file to the variable CHART_FILE.
This helps reuse the path later in the script.
bash
echo "Extracting image references from Helm chart templates..."
Print a message indicating you will now parse the chart templates to find Docker image references contained in them.
bash
# Render templates, then grep for image references.
# This uses a simple regex matching 'image: <image-name>'
# You can customize or enhance with yq/jq for more complex extraction.
IMAGES=$(helm template "$CHART_FILE" | grep -oP '(?<=image:\s)[^ ]+' | sort -u)
Run helm template on the chart archive. This renders all Helm templates without deploying, outputting Kubernetes manifests in plain YAML.
Use grep with Perl-compatible regex (-P) to find all image references:
Regex (?<=image:\s)[^ ]+ means:
Look for the text that follows the literal image: plus one whitespace (positive lookbehind (?<=...)).
Then match any characters until the next space (i.e., the image name).
Extract all matched image strings.
sort -u sorts and removes any duplicate images, producing a unique list assigned to the variable IMAGES.
bash
if [ -z "$IMAGES" ]; then
echo "No images found in Helm chart templates, exiting..."
exit 1
fi
Check if IMAGES is empty (no image references found).
If empty, print a warning message and exit the script with a status code 1 (error).
bash
echo "Images found:"
echo "$IMAGES"
Print all the extracted image references for the user to see.
bash
echo "Pulling and saving images..."
Notify that the script will now pull each image from its registry and save it locally.
bash
for img in $IMAGES; do
Start a loop over each image name stored in $IMAGES.
bash
echo "Pulling image: $img"
docker pull "$img"
For the current image:
Print a message indicating that you are pulling the image.
Use Docker to pull the image from its remote container registry.
bash
# Replace / and : with _ for safe filenames
filename=$(echo "$img" | sed 's/[\/:]/_/g')
Convert the image name into a safe filename:
Replace literal / and : characters (commonly found in image names, e.g. repo/image:tag) with underscores _.
This avoids issues with slashes or colons in filenames during saving.
bash
tarball="${OUTPUT_DIR}/${filename}.tar"
Define a full filepath to save the image tar in the output directory, using the sanitized filename and .tar extension.
bash
echo "Saving image $img to $tarball"
docker save "$img" -o "$tarball"
Announce saving the image locally.
Use docker save to export the pulled Docker image into a tarball file.
bash
done
End loop over all images.
bash
echo "Packaging the Helm chart and all saved images into a single artifact..."
Print a message stating the packaging step is beginning.
bash
pushd "$OUTPUT_DIR" > /dev/null
Change directory to the artifact output dir.
pushd saves the current directory on stack so you can return easily.
Redirect output to /dev/null to suppress directory output message.
bash
tar czvf "../${CHART_NAME}_${CHART_VERSION}_artifact.tar.gz" ./
Create a compressed tarball archive:
c: create
z: gzip compression
v: verbose (show files added)
f: specify filename
Archive all contents of the current directory (./) — this includes the .tgz Helm chart and all .tar image files.
Save archive one folder level up with a descriptive filename (e.g., mysql_8.7.0_artifact.tar.gz).
bash
popd > /dev/null
Return to the original directory before pushd.
Again suppress directory output.
bash
echo "Artifact created at ./${CHART_NAME}_${CHART_VERSION}_artifact.tar.gz"
Inform the user of the location of the final packaged artifact.
bash
echo "Done."
Print simple completion message indicating the script has finished successfully.
Summary:
This script automates:
Adding and updating a Helm repo.
Downloading a specific chart version.
Rendering the Helm chart to detect Docker images needed.
Pulling container images.
Saving those images locally as .tar files.
Packaging everything (chart + images) into a single compressed tarball artifact.
This artifact can then be transferred to environments without internet and installed offline with Helm and Docker.
Your script is quite solid and straightforward! Here are some possible improvements and enhancements you might consider to make it more robust, flexible, and maintainable:
1. Better Image Extraction: Use yq or smarter parsing
The grep approach works for many cases but can miss images defined separately as repository + tag, or images nested deeper in manifests.
E.g. many charts split image parts:
yaml
image:
repository: mysql
tag: 8.0.22
Improvement: Use yq to extract all image fields, and optionally combine .repository + .tag if needed.
For private registries, add optional support for docker login before pulling images.
4. Check for required tools
At start, verify helm, docker, and optionally yq are installed:
bash
command -v helm >/dev/null || { echo >&2 "helm is required but not installed. Aborting."; exit 1; }
command -v docker >/dev/null || { echo >&2 "docker is required but not installed. Aborting."; exit 1; }
5. Handle multiple image fields per chart
Some charts use multiple containers, initContainers, sidecars, etc. Image references can appear in image:, initContainer.image, extraContainers.image, etc.
Parsing all manifests for image: fields irrespective of indentation can be done, e.g.:
After downloading the Helm chart, verify checksums if available from repo metadata or helm show chart.
7. Improve filename sanitization
Instead of sed replacing / and :, you may want to:
Replace all non-alphanumeric characters ([^a-zA-Z0-9._-]) with underscores.
Or use a hash of the image name if you want guaranteed uniqueness without weird characters.
Example:
bash
filename=$(echo "$img" | sed 's/[^a-zA-Z0-9._-]/_/g')
8. Parallelize docker pulls
If you have lots of images and a fast connection, use GNU parallel or background jobs to pull/save images in parallel (with job control limits).
9. Handle chart dependencies
Some charts have dependencies (subcharts) which may have their own images. Consider running helm dependency update and pulling images from subcharts as well.
10. Add verbose/debug mode
Add a flag (-v or --debug) to make script verbose or print commands.
11. Add comments and error handling
Add traps or cleanup actions if needed. For example check disk space before large image pulls.
Optional: Example refining image extraction via yq
Here’s a snippet to extract images more reliably with yq from rendered manifests:
Your script works well if images always appear as image: <image> in Helm templates. If you want to handle more complex charts (like those splitting repo/tag, with subcharts, or multiple containers), consider using yq and parsing values.yaml and rendered manifests more thoroughly.
Let me know if you want me to help you incorporate any of these improvements!