在ansible中检查文件的真实性

Check authenticity of file in ansible

我有下载脚本文件的ansible角色,我如何在执行前使用md5sum检查文件的真实性?

- name: Add xx official repository for ubuntu/debain
  get_url:
     url:  https://script.deb.sh
     dest: /opt/script.db.sh

- name: Execute the script
  script: /opt/script.db.sh

get_url 有一个您可以使用的校验和参数。

- name: Add xx official repository for ubuntu/debain
  get_url:
    url:  https://script.deb.sh
    dest: /opt/script.db.sh
    checksum: md5:1234

http://docs.ansible.com/ansible/latest/get_url_module.html

如果您不使用 get_url 选项,在文件位于该位置后,使用 get_checksum 选项调用 stat 模块,如 documented here

- name: Get sha256 sum of script
  stat:
    path: /opt/script.db.sh
    checksum_algorithm: sha256
    get_checksum: yes
  register: shell_stat

- name: Verify sha256sum of script before execution.
  fail:
    msg: "Failure, file is not correct."
  when: shell_stat.stat.checksum != '19d6105fa1a581cf3ad38f67080b6d55cb152b5441ae8bdf194e593f292f31e9'

- name: Execute the script
  script: /opt/script.db.sh

更新 when: 行的总和以匹配您期望的文件。

生成校验和(本例中为 sha256)因操作系统而异。在大多数 Linux 发行版上使用 sha256sum {filename} 命令,在 OSX 上使用 shasum -a 256 {filename}.

您可以使用“校验和”参数“get_url”模块。我向您展示了一个剧本示例,该剧本仅在 md5sum 正确时才执行 "role" 以下载 OpenJDK8。

文件:playbook.yml

---
- name: "Download binaries"
  hosts: localhost
  roles:
  - openjdk

文件:openjdk/tasks/main.yml

- name: "Download OpenJDK {{ openjdk_version }} binaries"
  get_url:
    url: https://download.java.net/openjdk/jdk8u40/ri/{{ openjdk_file }}
    dest: "{{ download_destination }}"
    checksum: "{{ openjdk_md5 }}"
    mode: 0750
  tags:
    - always

文件:openjdk/vars/main.yml

---
download_destination: /var/tmp
openjdk_version: "8u40-b25"
openjdk_file: "openjdk-{{ openjdk_version }}-linux-x64-10_feb_2015.tar.gz"
openjdk_md5: "md5: 4980716637f353cfb27467d57f2faf9b"

Ansible 2.7 中可用的加密算法是:sha1sha224sha384sha256, sha512, md5.

对我有用,希望对你也有用。