在 Ansible playbook 中激活 Conda 环境

jef*_*f73 6 python ansible anaconda conda virtual-environment

我正在尝试运行需要在现有 Conda 环境中执行的任务列表此处运行气流,但实际上可以是任何东西)。

我想做这些任务:

- name: activate conda environment
 # does not work, just for the sake of understanding
 command: source activate my_conda_env

- name: initialize the database
  command: airflow initdb

- name: start the web server
  command: 'airflow webserver -p {{ airflow_webserver_port }}'

- name: start the scheduler
  command: airflow scheduler
Run Code Online (Sandbox Code Playgroud)

当然,这行不通,因为每个任务都是独立的conda environment,第一个任务中的激活被后续任务忽略。

我想如果使用 apython virtualenv而不是conda.

如何实现在 Conda 环境中运行的每个任务?

tec*_*raf 8

您的每个命令都将在不同的进程中执行。

source另一方面,command 仅用于将环境变量读入当前进程(及其子进程),因此它仅适用于activate conda environment任务。

您可以尝试做的是:

- name: initialize the database
  shell: source /full/path/to/conda/activate my_conda_env && airflow initdb
  args:
    executable: /bin/bash

- name: start the web server
  shell: 'source /full/path/to/conda/activate my_conda_env && airflow webserver -p {{ airflow_webserver_port }}'
  args:
    executable: /bin/bash

- name: start the scheduler
  shell: source /full/path/to/conda/activate my_conda_env && airflow scheduler
  args:
    executable: /bin/bash
Run Code Online (Sandbox Code Playgroud)

之前,检查activate目标机器上的完整路径是什么which activate(您需要在获取任何环境之前执行此操作)。如果 Conda 安装在用户空间中,您应该使用相同的用户进行 Ansible 连接。