Consider the following makefile snippet:
COMMIT := $(shell git rev-parse HEAD)
build:
docker build -f Dockerfile --no-cache=false -t $(COMMIT) .
rebuild:
docker build -f Dockerfile --no-cache=true -t $(COMMIT) .
The only difference between build
and rebuild
is the value of the --no-cache
parameter. Obviously, rewriting the same command with a slight change is a bad practice; it breaks the DRY principle, and if I ever need to change something else in the command - for example, the value of -t
- I would have to change it across all relevant targets.
I had something like this in mind:
COMMIT := $(shell git rev-parse HEAD)
NO_CACHE := false
build:
docker build -f Dockerfile --no-cache=$(NO_CACHE) -t $(COMMIT) .
rebuild:
NO-CACHE = true
make build
I tried playing with the variables, with no luck.
What would be an elegant way to write the docker build
command once, and have each target alter its parameter?
You can use constructed variable names:
COMMIT := $(shell git rev-parse HEAD)
build_NOCACHE = false
rebuild_NOCACHE = true
build rebuild:
docker build -f Dockerfile --no-cache=$($@_NOCACHE) -t $(COMMIT) .
Or you can use target-specific variables:
COMMIT := $(shell git rev-parse HEAD)
build: NOCACHE = false
rebuild: NOCACHE = true
build rebuild:
docker build -f Dockerfile --no-cache=$(NOCACHE) -t $(COMMIT) .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With