well… there’s no way to do it the way you’d like it but you can always use a workaround with multistage builds:
FROM solr:alpine as build
RUN whoami
FROM build as prepare_dependencies
USER root
RUN echo 'I am root' > /the_root_important_message
FROM build
COPY --from=prepare_dependencies /the_root_important_message /the_root_vital_message
RUN echo "now I'm $( whoami )"
RUN cat /the_root_vital_message
CMD echo 'this is a pain'
Somehow I’m fairly sure this is not what you’re looking for…
Well, since this topic is pretty fun, I decided to attempt a different approach:
FROM solr:alpine as build
RUN whoami
FROM build as prepare_dependencies
USER root
RUN apk --no-cache --update add sudo \
&& echo 'ALL ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers
RUN echo "this is secret" > /secretfile
RUN chmod 400 /secretfile
FROM build
COPY --from=prepare_dependencies /usr/bin/sudo /usr/bin/sudo
COPY --from=prepare_dependencies /usr/lib/sudo /usr/lib/sudo
COPY --from=prepare_dependencies /etc/sudoers /etc/sudoers
COPY --from=prepare_dependencies /secretfile /secretfile
RUN sudo -l
RUN sudo cat /secretfile
RUN echo "now I'm $( whoami )"
RUN echo "cleanup" \
&& sudo rm -rf \
/etc/sudoers /secretfile \
/usr/lib/sudo /usr/bin/sudo
CMD echo 'this is a pain'
CLICK HERE to find out more related problems solutions.