问题
In the below code snippet:
IMAGES_TO_DELETE := $(aws ecr list-images --region $(ECR_REGION) --repository-name $(ECR_REPO) --filter "tagStatus=UNTAGGED" --query 'imageIds[*]' --output json)
.PHONY: target1 target2 cleanimage
cleanimage:
${DISPLAYINFO} "Clean untagged image from AWS ECR "
aws ecr batch-delete-image --region $(ECR_REGION) --repository-name $(ECR_REPO) --image-ids "$(IMAGES_TO_DELETE)" || true
${DISPLAYINFO} "Done"
target1:
# do something
target2:
# do something
IMAGES_TO_DELETE gives imagelist, in JSON format.
IMAGES_TO_DELETE supposed to be assigned when make cleanimage executes
How to assign values to a variable under cleanimage target?
回答1:
You seem to have a continuing misunderstanding about make variables.
It's not clear why this needs to be a variable at all. Just inline it into the target:
.PHONY: cleanimage
cleanimage:
${DISPLAYINFO} "Clean untagged image from AWS ECR "
aws ecr batch-delete-image --region $(ECR_REGION) --repository-name $(ECR_REPO) \
--image-ids "$$(aws ecr list-images --region $(ECR_REGION) --repository-name $(ECR_REPO) \
--filter "tagStatus=UNTAGGED" --query 'imageIds[*]' --output json)" || true
${DISPLAYINFO} "Done"
As an aside $(aws...) is not a valid make function; you mean $(shell aws ...); but again, there is no need to evaluate this in make at all if it is only needed in a single target.
Where you have repeated information, that's where it makes sense to refactor that into a variable so you only have to change it in one place.
ECRFLAGS := --region $(ECR_REGION) --repository-name $(ECR_REPO)
.PHONY: cleanimage
cleanimage:
${DISPLAYINFO} "Clean untagged image from AWS ECR "
aws ecr batch-delete-image $(ECRFLAGS) \
--image-ids "$$(aws ecr list-images $(ECRFLAGS) \
--filter "tagStatus=UNTAGGED" --query 'imageIds[*]' --output json)" || true
${DISPLAYINFO} "Done"
Remember, a single dollar sign is evaluated by make. If you want to pass through a literal dollar sign to the shell, you need to double it.
回答2:
Make variables must always be surrounded with parens or braces. If not, then only the next character is part of the variable.
So when you write $ECR_REGION, make will expand the variable $E (which is probably empty) then append the string CR_REGION. Not what you want.
You must write $(ECR_REGION) (or ${ECR_REGION} if you prefer: they're equivalent to make).
Ditto for $(ECR_REPO) and $(IMAGES_TO_DELETE).
See https://www.gnu.org/software/make/manual/html_node/Reference.html
来源:https://stackoverflow.com/questions/59883707/makefile-how-to-assign-a-value-to-a-variable-on-specific-target