0

Can Ansible hash files using lookup similar to how it can hash strings (e.g., {{ 'test1' | hash('sha1') }})?

See, https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#hashing-and-encrypting-strings-and-passwords

Linux command line (WORKS)

sha1sum /etc/default/grub

returns hash: f2de8d3dfe08c34615145f212e5a32facf575cb3

Ansible stat module (WORKS)

- name: checksum | /etc/default/grub (stat)
  delegate_to: localhost
  stat:
    path: "/etc/default/grub"
    checksum_algorithm: sha1
  register: local_grub_orig_sha1

returns hash: f2de8d3dfe08c34615145f212e5a32facf575cb3

Ansible lookup with hash filter (FAILS)

- name: checksum | /etc/default/grub (lookup)
  delegate_to: localhost
  set_fact:
    local_grub_sha1: "{{ lookup('file', '/etc/default/grub') | hash('sha1') }}"

returns hash: 834f3f662f6a19cf273d87a00d4af2645ab18dcd

NOTE: This implementation is limited to localhost. See @Vladimir Botka's answer below for a general solution using stat.

user2514157
  • 545
  • 6
  • 24

2 Answers2

2

Use stat. Test it, for example

    - stat:
        path: /etc/passwd
        checksum_algorithm: sha256
      register: result
    - debug:
        var: result.stat.checksum

    - command: sha256sum /etc/passwd
      register: result
    - debug:
        var: result.stdout

You should see the same results from the command and stat.

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Right, as also shown under [Save part of a result in Ansible using register, set_fact, or filter](https://stackoverflow.com/a/71348638/6771046). – U880D Mar 04 '22 at 10:36
0

The issue was solved by using lookup('template', ...) rather than lookup('file', ...). However, it is not clear to me what is causing the difference in behavior.

- name: set_fact checksum | /etc/default/grub
  set_fact:
    grub_template_result_sha1: "{{ lookup('template', '/etc/default/grub') | hash('sha1') }}"

returns hash: f2de8d3dfe08c34615145f212e5a32facf575cb3

user2514157
  • 545
  • 6
  • 24
  • 2
    I"d put a dime on a trailing new line that one or the other lookup add/trim. – Zeitounator Mar 04 '22 at 08:26
  • 1
    Please keep in mind that [Lookups](https://docs.ansible.com/ansible/latest/user_guide/playbooks_lookups.html) "_like all templating, ... execute and are evaluated on the Ansible Control Machine_" only. Therefore it is non distributable solution, it will not work for Remote Nodes. – U880D Mar 04 '22 at 10:12