case-kの備忘録

日々の備忘録です。データ分析とか基盤系に興味あります。

DigdagのPythonオペレータでPipenvを使う

DigdagのPythonオペレータでPipenvで作ったpython環境を使うようにしました。Dockerfileは次の通りです。

FROM python:3

# use pipenv command in digdag python operator
RUN mkdir -p /var/lib/python
WORKDIR /var/lib/python
RUN pip3 install pipenv
COPY Pipfile .
COPY Pipfile.lock .
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
# https://qiita.com/tonluqclml/items/cd0d2a2cb0197cbaee42
ENV PIPENV_VENV_IN_PROJECT=1
RUN pipenv install
ENV VIRTUAL_ENV=/var/lib/python/.venv
# https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3
COPY pipenv.sh /usr/bin/pipenv
RUN chmod +x /usr/bin/pipenv
RUN update-alternatives --install /usr/bin/python bash /usr/bin/pipenv 10

次のようにラッパースクリプトを用意して、pipenv run pythonの実行結果をpythonコマンドで使えるようにします。
pipenv.sh

#!/bin/bash

exec pipenv run python $*

次にpipenvで作った環境を他のディレクトリからも参照できるようにします。仮想環境の場所を固定したかったので「PIPENV_VENV_IN_PROJECT」を使いプロジェクト直下に「.venv/」を作ります。
その後「VIRTUAL_ENV」を使い、構築した仮想環境を他のディレクトリからも参照できるようにします。

ENV PIPENV_VENV_IN_PROJECT=1
RUN pipenv install
ENV VIRTUAL_ENV=/var/lib/python/.venv

qiita.com

次にupdate-alternativesを使い/usr/bin/pythonの実行結果を/usr/bin/pipenvの実行結果にします。。
DigdagのPythonオペレータはpythonコマンドの実行結果が適用されるので、python3の実行結果をpythonで使いたい場合に使えます。

RUN update-alternatives --install /usr/bin/python bash /usr/bin/pipenv 10

askubuntu.com



参考
digdag の rb オペレータで bundle exec を使う3つの方法 - Qiita