haeminish
haeminish

Reputation: 1078

ansible - if statement and redirect to a file with shell module doesn't work

I understand it's best to use ansible modules as much as possible, however for a good reason, I am being forced to use shell module.

I have a date_list file with a list of dates:

20170811
20170802
20170812
and so on..

I need to compare this dates with ansible time with shell module:

- name: Read file date and compare with server date and redirect to a file
  shell: |
    if [ {{ item.split('\n')[0] }} -lt ${{ gv_remote_date.stdout }} ]; then 
        echo {{ item.split('\n')[0] }} >> final_output
    fi
   args:
     executable: /bin/bash
   with_lines: "{{ date_list.stdout_lines }}"

I get no output at all. In the debug: I can see it's switching items but I get nothing in the final_output file.

Upvotes: 0

Views: 3619

Answers (2)

René Pijl
René Pijl

Reputation: 4738

I'd use Ansible's template module to create the shell script in a file. In that way you can inspect the generated shell script and debug it outsite of Ansible.

Upvotes: 0

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

Why not use native when statement:

- name: Read file date and compare with server date and redirect to a file
  shell: echo {{ item }} >> final_output
  args:
    executable: /bin/bash
  when: item | int < gv_remote_date.stdout | int
  with_items: "{{ date_list.stdout_lines }}"

Or even like this (to make it idempotent):

- lineinfile:
    dest: final_output
    line: "{{ item }}"
    state: "{{ (item | int < gv_remote_date.stdout | int) | ternary('present','absent') }}"
  with_items: "{{ date_list.stdout_lines }}"

This will make sure line is in the file if it should be and line is absent if condition is false.

Upvotes: 2

Related Questions