Opscraft
Makefile · Lesson 3 of 7 · 5 min read

Variables in depth

Defining and referencing

APP      := orders
REGISTRY ?= 123456789012.dkr.ecr.ap-south-1.amazonaws.com
IMAGE     = $(REGISTRY)/$(APP)
TAG      ?= $(GIT_SHA)
GIT_SHA  := $(shell git rev-parse --short HEAD)
FLAGS    += -race

Reference with $(VAR) or ${VAR}. A single-letter variable can be written $X, which is why a literal $ must be doubled (below).

The assignment flavours

Operator Name Behaviour
= Recursive (lazy) Expanded every time it's used; can reference variables defined later
:= (or ::=) Simple (immediate) Expanded once, at definition
?= Conditional Set only if not already set (environment or command line wins)
+= Append Adds to the existing value with a space
!= Shell assignment Runs a shell command and assigns its output (GNU make 4.0+)
Enlarge diagramGIT_SHA = $(shell git …)GIT_SHA := $(shell git …)Lazy: expanded on every useRuns git again and againCan refer to later variablesImmediate: expanded onceRuns git one timeThe default choice
Figure 1. The two assignments you will use most. := runs the shell command once; = runs it again every time the variable is used.
Swipe sideways to see all of it, or tap to open it full screen.

Why it matters:

GIT_SHA = $(shell git rev-parse --short HEAD)    # runs git EVERY time GIT_SHA is used
GIT_SHA := $(shell git rev-parse --short HEAD)   # runs git ONCE — use this

Lazy = can also cause infinite recursion (X = $(X) more is an error; use +=).

Where values come from, and precedence

From highest to lowest:

  1. Command line: make deploy ENV=staging TAG=$GIT_SHA — overrides assignments in the Makefile (unless the Makefile uses override).
  2. Assignments in the Makefile.
  3. Environment variables — visible as make variables, but Makefile assignments override them (unless make -e). ?= lets the environment supply a value.
  4. Built-in defaults.

So IMAGE_TAG ?= dev gives developers a default while CI runs make build IMAGE_TAG=$GIT_COMMIT.

Enlarge diagramCommand linemake deploy ENV=stagingMakefile assignmentTAG := devEnvironment variableexport TAG=… (wins only against ?=)Built-in defaultsCC, MAKE…
Figure 2. Where a variable's value comes from, highest first. ?= gives a default that the environment or CI can replace.
Swipe sideways to see all of it, or tap to open it full screen.

Exporting to recipe shells

Make variables are not automatically environment variables in recipes. Export them:

export AWS_REGION ?= ap-south-1
export KUBECONFIG                 # export an existing variable
.EXPORT_ALL_VARIABLES:            # export everything (blunt instrument)

Automatic variables

Set by make for each rule:

Variable Meaning
$@ The target name
$< The first prerequisite
$^ All prerequisites, de-duplicated
$? Prerequisites newer than the target
$* The stem matched by % in a pattern rule
$(@D) / $(@F) Directory / file part of the target
dist/%.tar.gz: build/%
    mkdir -p $(@D)
    tar -czf $@ -C build $*
Enlarge diagram$@$<$^$*$(@D)dist/orders.tar.gz: build/orders README.mddist/orders.tar.gzthe targetbuild/ordersfirst prerequisitebuild/orders README.mdall prerequisitesorderswhat % matched (pattern rules)distdirectory of the target
Figure 3. Automatic variables for one rule.
Swipe sideways to see all of it, or tap to open it full screen.

Pattern rules

% matches any stem:

%.o: %.c
    $(CC) -c $< -o $@

deploy-%:                          # make deploy-staging, make deploy-prod
    ./scripts/deploy.sh $*

Useful functions

SERVICES := $(notdir $(wildcard services/*))          # list subdirectories
SRC      := $(shell find src -name '*.go')
UPPER    := $(shell echo $(APP) | tr a-z A-Z)
VERSION  := $(patsubst v%,%,$(shell git describe --tags --abbrev=0))   # strip leading v
TARGETS  := $(addprefix test-,$(SERVICES))           # test-orders test-payments ...
$(info Building $(APP) at $(GIT_SHA))                 # print while parsing (debugging)
$(warning Deprecated target)                          # print a warning
$(error ENV is required)                              # stop with an error
$(foreach s,$(SERVICES),$(eval $(call SERVICE_RULES,$(s))))   # generate rules (advanced)

Conditionals evaluated at parse time:

ifeq ($(ENV),prod)
  REPLICAS := 6
else
  REPLICAS := 2
endif
ifndef AWS_PROFILE
  $(warning AWS_PROFILE not set; using default credentials chain)
endif