Ansible:仅当 Python 模块不存在时才安装它

标签 ansible devops

我需要通过 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

进一步问答

文档


...只是一个带有 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/

相关文章:

azure - Kubernetes 中的 Flink 作业部署

linux - 我可以安排 ansible playbook 在每天的特定时间运行吗

ansible重启网络服务

Ansible 中的 Git 模块在 tmp 目录上获得权限被拒绝

docker - 使用 Docker 提供软件更新

linux - 追踪高 CPU 平均负载

Docker 卷 : Docker Volume does not get mounted correctly on Amazon Linux

kubernetes - 如何等到分配 EXTERNAL-IP?

ansible - ansible playbook 任务中 shell 命令执行失败时如何仅打印 stderr_lines

kubernetes - 版本 "DaemonSet"中的种类 "extensions/v1beta1"没有匹配项