# Base directories IMAGES_PATH := images LIBRARY_PATH := library SYMLINK_PREFIX := library_ # Docker registry variables REGISTRY := git.query.consul OWNER := unkin #GIT_COMMIT := $(shell git rev-parse --short HEAD) DATE_TAG := $(shell date +%Y%m%d) BRANCH=$(shell git branch --show-current) # Find all subdirectories under the IMAGES_PATH DIRS := $(shell find $(IMAGES_PATH) -mindepth 3 -maxdepth 3 -type d | sed 's|$(IMAGES_PATH)/||') .PHONY: list $(DIRS) .DEFAULT_GOAL := default default: ./ci/build.sh # Make all images all: @for dir in $(DIRS); do \ $(MAKE) $$dir; \ done # List all directories list: @echo "Images:" @for dir in $(DIRS); do \ echo " '$$dir'"; \ done # Dynamically create targets for each directory .ONESHELL: $(DIRS): @echo "Building for $@" # Export environment export VAULT_TOKEN=$$(vault write -field=token auth/approle/login role_id=$$VAULT_ROLEID) export VAULT_ADDR=https://vault.service.consul:8200 @for kv in $$(vault kv get -format=json kv/service/packer/builder/env | jq -r '.data.data | to_entries[] | "\(.key)=\(.value)"'); do \ export "$kv"; \ done # Check if on master branch @if [ "$(BRANCH)" = "master" ]; then \ echo "Current branch is $(BRANCH), checking latest timestamp in consul."; \ LAST_BUILD_TIMESTAMP=$$(consul kv get infra/packer/$@/timestamp || echo "0"); \ CURRENT_TIME=$$(date +%s); \ if [ $$((CURRENT_TIME - LAST_BUILD_TIMESTAMP)) -lt 86400 ]; then \ echo "Skipping build for $@ (built within the last 24 hours)"; \ exit 0; \ fi; \ fi # Link .hcl files @find $(LIBRARY_PATH) -name '*.hcl' -exec sh -c 'ln -sf $$PWD/{} $(IMAGES_PATH)/$@/$(SYMLINK_PREFIX)$$(basename {})' \; # Link builds @for build in $$(cat $(IMAGES_PATH)/$@/builds); do \ ln -sf ../../../../builds/$${build}.pkr.hcl $(IMAGES_PATH)/$@/library_$${build}.build.pkr.hcl; \ done # Build the image @(cd $(IMAGES_PATH)/$@ && \ export DATE=$(DATE_TAG) && \ export OS_NAME=$$(echo $@ | cut -d'/' -f1) && \ export OS_VERSION_FULL=$$(echo $@ | cut -d'/' -f2) && \ export OS_IMAGE=$$(echo $@ | cut -d'/' -f3) && \ export OS_VERSION_MAJOR=$$(echo $$OS_VERSION_FULL | cut -d'.' -f1) && \ export DOCKER_SOURCE=$$OS_NAME:$$OS_VERSION_FULL && \ export DOCKER_SERVER='git.query.consul' && \ export INCUS_SOURCE="images:$$OS_NAME/$$OS_VERSION_MAJOR" && \ export SUFFIX=$$(basename $$(mktemp -u) | cut -d . -f 2) && \ export GIT_BRANCH=$(BRANCH) && \ packer init . && \ packer build . ) # Update build timestamp and date in Consul if on master branch @if [ "$(BRANCH)" = "master" ]; then \ echo "Current branch is $(BRANCH), updating consul."; \ CURRENT_TIMESTAMP=$$(date +%s); \ READABLE_DATE=$$(date '+%Y-%m-%d %H:%M:%S %Z'); \ consul kv put infra/packer/$@/timestamp $$CURRENT_TIMESTAMP; \ consul kv put infra/packer/$@/date "$$READABLE_DATE"; \ fi # Clean all symlinks clean: @echo "Cleaning up symlinks..." @find $(IMAGES_PATH) -name 'library_*' -type l -delete @echo "All symlinks removed!"