如何防止dpkg安装任务在第二次运行时通知已更改的状态?

10

没有直接安装 .deb 包的模块。当您必须将 dpkg 作为命令运行时,它总是将安装任务标记为已更改。我在正确配置它方面遇到了一些问题,所以我在这里发布了一个公共笔记本。

以下是使用 dpkg 安装的任务:

- name: Install old python 
  command: dpkg -i {{ temp_dir }}/{{ item }}
  with_items: 
    - python2.4-minimal_2.4.6-6+precise1_i386.deb
    - python2.4_2.4.6-6+{{ ubuntu_release }}1_i386.deb
    - libpython2.4_2.4.6-6+{{ ubuntu_release }}1_i386.deb
    - python2.4-dev_2.4.6-6+{{ ubuntu_release }}1_i386.deb

文件已在另一个任务中上传到{{temp_dir}}目录。

3个回答

13

以下答案仍然有效,但是更新的Ansible版本有apt模块。Mariusz Sawicki的回答现在是首选,我已将其标记为被接受的答案。

它只能在Ansible 1.3版本中使用,该版本添加了changed_when参数。这有点笨拙,也许有人可以改进这个解决方案。我没有找到这个“register”对象的文档。

- name: Install old python 
  command: dpkg --skip-same-version -i {{ temp_dir }}/{{ item }}
  register: dpkg_result
  changed_when: "dpkg_result.stdout.startswith('Selecting')"
  with_items: 
    - python2.4-minimal_2.4.6-6+precise1_i386.deb
    - python2.4_2.4.6-6+{{ ubuntu_release }}1_i386.deb
    - libpython2.4_2.4.6-6+{{ ubuntu_release }}1_i386.deb
    - python2.4-dev_2.4.6-6+{{ ubuntu_release }}1_i386.deb

在这里,您可以运行相同的任务,并且它只会在第一次安装时安装软件包。在第一次之后,软件包将不会被安装。

有两个修改。一个是参数--skip-same-version,用于防止dpkg重新安装软件。另一个是注册和changed_when属性。第一次运行dpkg时,它会向stdout打印以“Selecting”开头的字符串,并通知更改。稍后它将有不同的输出。我尝试了更易读的条件,但无法使用更复杂的条件(如“not”或搜索子字符串)使其工作。


6
不错的技巧!不过我更愿意检查 STDERR:changed_when: "'already installed' not in dpkg_result.stderr" - tokarev
2
从Ansible文档中:覆盖更改结果 - user272735
由于在使用1.6+ deb参数时,with_items、with_dict等不起作用,因此这是循环安装多个本地.deb文件的最佳方法。 - senorsmile

8
在 Ansible 1.6(及更新版本)中,apt 模块提供了一个 deb 选项:
- apt: deb=/tmp/mypackage.deb

2

您可以使用apt模块,带有dpkg_options参数:

- name: Install old python 
  apt: deb={{ temp_dir }}/{{ item }} dpkg_options="skip-same-version"
  register: dpkg_result
  changed_when: dpkg_result.stderr.find("already installed") == -1
  with_items: 
    - python2.4-minimal_2.4.6-6+precise1_i386.deb
    - python2.4_2.4.6-6+{{ ubuntu_release }}1_i386.deb
    - libpython2.4_2.4.6-6+{{ ubuntu_release }}1_i386.deb
    - python2.4-dev_2.4.6-6+{{ ubuntu_release }}1_i386.deb

我已经将接受的答案更改为这个,因为新的apt模块解决了这个问题。 - neves

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接