我需要通过Ansible在远程服务器上安装Pythonpip
。我这样做,它工作:
- 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
进一步的问答;A
- 在Ansible中检查命令是否可用的最佳方法是什么
- Ansible:如何只在未安装相同版本的情况下安装软件包
文档
- 定义失败
- 定义";"已更改">
- 使用
check_mode
。。。只是一个带有shell操作符的示例插件
- name: Install 'pip' only if it not exist
shell:
cmd: pip --version || /usr/bin/python /tmp/get-pip.py
- 使用
&&
和||
运算符 - 布尔运算符
通过使用shell
和uri
的creates
参数,可以轻松绕过这两项任务。它需要一个将被检查是否存在的文件名。如果该文件存在,则不会运行该任务。
注意:在下面未完全测试的示例中,我推断您的脚本将二进制文件安装在/usr/local/bin/pip
中。如果不同,请根据确切的安装位置进行调整
---
- name: Install pip
hosts: all
gather_facts: false
vars:
pip_location: /usr/local/bin/pip
tasks:
- name: Download pip installer
get_url:
url: https://bootstrap.pypa.io/pip/2.7/get-pip.py
dest: /tmp/get-pip.py
creates: "{{ pip_location }}"
- name: Install pip
shell:
cmd: /usr/bin/python /tmp/get-pip.py
creates: "{{ pip_location }}"
参考文献:
shell
模块中的creates
参数
uri
模块中的creates
参数这个好人William Yeh正是为此写了一本不错的剧本:
---
# file: tasks/install-pip.yml
# Mini installer for pip; only to enable the Ansible `pip` module.
#
# For full installer, use something like:
#
# - Stouts.python
# - bobbyrenwick.pip
#
# @see https://github.com/gmacon/ansible-pip/blob/variable_executables/tasks/main.yml
#
- name: check to see if pip is already installed
command: "pip --version"
ignore_errors: true
register: pip_is_installed
changed_when: false
- block:
- name: download get-pip.py
get_url: url=https://bootstrap.pypa.io/get-pip.py dest=/tmp
- name: install pip
command: "python /tmp/get-pip.py"
- name: delete get-pip.py
file: state=absent path=/tmp/get-pip.py
when: pip_is_installed.rc != 0