Auto-delete Compute Engine VM with custom Docker image

Viewed 35

I try to create a VM that can run a python script and delete itself at the end of the run.

For compatibility and simplicity I would like to run my script using a Docker image.

Currently I create the Compute Engine VM using gcloud as follow :

gcloud compute instances create-with-container test --container-image=my-image [...]

I tried with startup-script but it won't work with custom Docker image, the docker container is created, it runs fine, and at the end the VM stays on.

My Dockerfile is something like that (I need gcloud for later during script run)

Dockerfile

FROM python:3.9

ENV PYTHONUNBUFFERED True
ENV GOOGLE_APPLICATION_CREDENTIALS my-project-creds.json
ENV GCP_PROJECT_ID my-project

RUN curl https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz > /tmp/google-cloud-sdk.tar.gz

RUN mkdir -p /usr/local/gcloud \
    && tar -C /usr/local/gcloud -xvf /tmp/google-cloud-sdk.tar.gz \
    && /usr/local/gcloud/google-cloud-sdk/install.sh

ENV PATH $PATH:/usr/local/gcloud/google-cloud-sdk/bin

WORKDIR /app/
COPY . .

RUN gcloud auth activate-service-account --key-file $GOOGLE_APPLICATION_CREDENTIALS
RUN gcloud config set project $GCP_PROJECT_ID

RUN pip install --no-cache-dir -r requirements.txt

CMD python3 main.py

Is there a way (if possible directly in the Dockerfile) to tell the VM to delete itself at the end of the container run ?

0 Answers
Related