Lara
Lara

Reputation: 3174

Combining ansible tasks to one task with one definition of "changed"

As part of deployment there is a bit of compilation I want to do on the host. This consists of moving the source files, compiling the program, and removing the source files. I would want it to work in such a way that this results in just ok rather than changed if the program did not change.

This would accurately describe the situation, because if the program did not change, then by running the playbook a (assumedly) non-existent directory would be created, a command run resulting in some file that's then moved to where a identical copy used to be, and then the source files are removed and the created directory is once again non-existent.

Concretely, the tasks would be something like:

- copy:
    src: src/
    dest: /tmp/my_program_src/
- shell: my_compiler -o /usr/local/bin/my_program /tmp/my_program_src/main.file
  become: true
- file:
    path: /tmp/my_program_src/
    state: absent

Of course what actually happens is that all three report "changed"; because for shell I would have to define changed_when myself, and copy as well as file change something, though they cancel each other out.

Can I group this together into one task which reports ok if /usr/local/bin/my_program did not change? If yes, then how? If no, then what would be the 'right' way to do something like this?

Upvotes: 1

Views: 1315

Answers (1)

imjoseangel
imjoseangel

Reputation: 3936

IMHO, I recommend doing the Ansible way like this. Other option is generating a script and calling it by command:. Then checking the sha1 with Ansible, but I don't like that option.

---
- name: Example
  hosts: localhost
  gather_facts: False
  connection: local

  tasks:

    - name: Get cksum of my program
      stat:
        path : "/usr/local/bin/my_program"
      register: myprogram1

    - name: Current SHA1
      set_fact:
        mp1sha1: "{{ myprogram1.stat.checksum }}"

    - name: Copy File
      copy:
        src: src/
        dest: /tmp/my_program_src/
      changed_when: False

    - name: Compile
      shell: my_compiler -o /usr/local/bin/my_program /tmp/my_program_src/main.file
      become: true
      changed_when: False

    - name: Remove src
      file:
        path: /tmp/my_program_src/
        state: absent
      changed_when: False

    - name: Get cksum of my program
      stat:
        path : "/usr/local/bin/my_program"
      register: myprogram2

    - name: Current SHA1
      set_fact:
        mp2sha1: "{{ myprogram2.stat.checksum }}"

    - name: Compilation Changed
      debug:
        msg: "Check Compilation"
      changed_when:  mp2sha1 == mp1sha1

Upvotes: 2

Related Questions