Pip 共享python虚拟环境的Ansible角色
我有一个将任务委托给本地主机的责任角色:Pip 共享python虚拟环境的Ansible角色,pip,ansible,virtualenv,ansible-role,Pip,Ansible,Virtualenv,Ansible Role,我有一个将任务委托给本地主机的责任角色: - name: Test role hosts: my_hosts gather_facts: no tasks: - name: Register remote hosts include_role: name=register_remote_hosts delegate_to: localhost 角色注册\u远程\u系统必须适用于my\u hosts中的每个主机,但必须从调用Ansible
- name: Test role
hosts: my_hosts
gather_facts: no
tasks:
- name: Register remote hosts
include_role: name=register_remote_hosts
delegate_to: localhost
角色注册\u远程\u系统必须适用于my\u hosts中的每个主机,但必须从调用Ansible的框中运行,这就是为什么存在委托\u to的原因
角色register\u remote\u hosts检查本地主机上的特定应用程序,如果未安装,则创建虚拟环境,然后安装:
- name: Check if my_app is installed system-wide
shell: |
my_app --version >/dev/null 2>&1
register: my_app_cmd
failed_when: my_app_cmd.rc not in [0, 127]
- name: Install My App
block:
- name: Create temporary directory for my_app
tempfile:
state: directory
suffix: my_app
register: my_app_temp
- name: Create virtual environment
command: virtualenv "{{ my_app_temp.path }}"
- name: Install my_app
pip:
name: my_app
state: latest
virtualenv: "{{ my_app_temp.path }}"
virtualenv_site_packages: yes
- name: Set Virtual Environment variable
set_fact:
venv_activate: "source {{ my_app_temp.path }}/bin/activate"
when: my_app_cmd.rc != 0
- name: Use my_app
shell: |
{{ venv_activate | default('echo "Using my_app from system path"') }}
my_app --version
一切都很好,但是如果my_hosts中有很多主机,那么就会创建很多VenV
创建角色的最佳方法是在安装my_应用程序的情况下重用相同的venv。请注意,角色包含在许多不同的剧本中,我不想在使用Register remote hosts included角色的每个剧本中都包含其他角色。在其他剧本中使用venv之前,当然存在创建venv的并发性问题
上述解决方案有效,我可以接受,但Ansible中可能有更好的设计模式来解决此类问题。解决方案是运行一次,谢谢@ssbarnea:
when: my_app_cmd.rc != 0
run_once: yes
尝试将run_添加一次:yes到块内的每个任务。