我需要通过 Ansible 在远程服务器上安装 Python pip
。我这样做并且有效:
- name: Download pip installer
get_url:
url: https://bootstrap.pypa.io/pip/2.7/get-pip.py
dest: /tmp/get-pip.py
- name: Install pip
shell: /usr/bin/python /tmp/get-pip.py
一个问题 - 每次我运行剧本时,它的状态都会“改变”。我不需要每次运行 playbook 时都安装它。
如果pip
模块之前没有安装,我如何检查并安装它?
最佳答案
由于未安装 pip
的系统会报告
pip --version; echo $?
-bash: pip: command not found
127
您可以在运行下载和安装任务之前进行安装和版本测试。
---
- hosts: test
become: false
gather_facts: false
tasks:
- name: Gather installed pip version, if there is any
shell:
cmd: pip --version | cut -d ' ' -f 2
register: result
failed_when: result.rc != 0 and result.rc != 127
# Since this is a reporting task, it should never change
# as well run and register a result in any case
changed_when: false
check_mode: false
- name: Set default version, if there is no
set_fact:
result:
stdout_lines: "00.0.0"
when: "'command not found' in result.stdout"
- name: Report result
debug:
msg: "{{ result.stdout }}"
check_mode: false
when: result.stdout != "20.3.4"
导致输出
TASK [Gather installed pip version, if there is any] ***
ok: [test.example.com]
TASK [Report result] ***********************************
ok: [test.example.com] =>
msg: 20.3.4
进一步问答
- Whats the best way in Ansible to check if a command is available?
- Ansible: How to install a package only if same version not installed?
文档
...只是一个带有 shell 操作符的附加组件示例
- name: Install 'pip' only if it not exist
shell:
cmd: pip --version || /usr/bin/python /tmp/get-pip.py
关于Ansible:仅当 Python 模块不存在时才安装它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73293401/