如何使用Ansible在virtualenv上安装python包?

vwhgwdsa  于 2023-03-28  发布在  Python
关注(0)|答案(2)|浏览(132)

我不能发射gunicorn我得到这个错误
错误:

fatal: [172.105.102.110]: FAILED! => {
   "changed":false,
   "cmd":"/myproject/myprojectenv/bin/gunicorn -D --chdir /myproject --error-logfile /root/.ansible/tmp/ansible-tmp-1593463703.788082-353660-248038870081082/gunicorn.temp.error.log --pid /root/.ansible/tmp/ansible-tmp-1593463703.788082-353660-248038870081082/gunicorn.temp.pid wsgi",
   "msg":"[Errno 2] No such file or directory: b'/myproject/myprojectenv/bin/gunicorn'",
   "rc":2
}

do_tutorial.yml

---
- hosts: DigitialOceanExample
  become: yes
  tasks: 
  - name: Update apt-get repo and cache
    apt: 
      update_cache: yes 
      force_apt_get: yes 
      cache_valid_time: 3600

  - name: Install a list of packages
    apt:
      pkg:
      - python3-pip
      - python3-dev
      - build-essential
      - libssl-dev
      - libffi-dev
      - python3-setuptools
      - python3-venv

  - name: ensure a directory exists or create it
    file: 
      path: /myproject
      state: directory

  - name: Manually create the initial virtualenv
    command:
      cmd: python3 -m venv /myproject/myprojectenv
      creates: "/myproject/myprojectenv"

  - name: "install python packages with the local instance of pip"
    shell: "pip3 install wheel flask gunicorn"

  - name: copy file to server
    copy: 
      src: "{{ item }}"
      dest: /myproject
    loop:
      - ./myproject.py

  - name: Install ufw
    apt:
      name: ufw
      update_cache: true

  - name: "Allow port 5000"
    shell:  "ufw allow 5000"

  - name: copy file to server
    copy: 
      src: ./wsgi.py
      dest: /myproject 

  # - name: "starting gunicorn"
  #   shell: "gunicorn --bind 0.0.0.0:5000 wsgi:app"

  - name: run gunicorn on a virtualenv
    gunicorn:
      app: 'wsgi'
      chdir: '/myproject'
      venv: '/myproject/myprojectenv'

myproject.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "<h1 style='color:blue'>Hello There!</h1>"

if __name__ == "__main__":
    app.run(host='0.0.0.0')

wsgi.py

from myproject import app

if __name__ == "__main__":
    app.run()

主机

[DigitialOceanExample]
PPP.PPP.PPP.PPP (redacted for StackOverFlow question)

命令

ansible-playbook -i inventory  do_tutorial.yml

我尝试使用Ansible复制this tutorial,但我的虚拟环境出现错误

pb3skfrl

pb3skfrl1#

我认为你是用全局pip安装的,而不是在你的虚拟环境中安装的。在你新创建的venv中尝试使用pip3的绝对路径:

- name: "install python packages with the local instance of pip"
    shell: "/myproject/myprojectenv/bin/pip3 install wheel flask gunicorn"
ttcibm8c

ttcibm8c2#

上面Marsu给出的例子工作得很好。
以防万一,如果有人想通过Jenkins作业在远程机器上执行剧本,那么你需要先切换到绝对路径,然后安装包或requirements.txt
例如:

- name: "install python packages with the local instance of pip"
shell: "cd /myproject && myprojectenv/bin/pip3 install -r requirements.txt"

相关问题