How to make a build arg mandatory during Docker build?

后端 未结 6 1944
后悔当初
后悔当初 2020-12-23 16:15

Is there any way to make a build argument mandatory during docker build? The expected behaviour would be for the build to fail if the argument is missing.

6条回答
  •  长情又很酷
    2020-12-23 16:44

    Long time ago I had a need to introduce a required (mandatory) ARG, and for better UX include the check at the beginning:

    FROM ubuntu:bionic
    ARG MY_ARG
    RUN [ -z "$MY_ARG" ] && echo "MY_ARG is required" && exit 1 || true
    
    ...
    
    RUN ./use-my-arg.sh
    

    But this busts the build cache for every single layer after the initial MY_ARG, because MY_ARG=VALUE is prepended to every RUN command afterwards.

    Whenever I changed MY_ARG it would end up rebuilding the whole image, instead of rerunning the last RUN command only.

    To bring caching back, I have changed my build to a multi-staged one:

    • The first stage uses MY_ARG and checks it's presence.
    • The second stage proceeds as usual and declares ARG MY_ARG right at the end.
    FROM alpine:3.11.5
    ARG MY_ARG
    RUN [ -z "$MY_ARG" ] && echo "MY_ARG is required" && exit 1 || true
    
    FROM ubuntu:bionic
    ...
    ARG MY_ARG
    RUN ./use-my-arg.sh
    

    Since ARG MY_ARG in the second stage is declared right before it's used, all the previous steps in that stage are unaffected, thus cache properly.

提交回复
热议问题