1

Let's say that content of file "/etc/my_file.txt" is like this:

a b CC d
a c BB d
a d DD e

I am checking it and writing output to variable:

- name: Check 3rd column of file
  shell: cat /etc/my_file.txt | awk '{print $3}'
  register: test

Is there a way to check if the 3rd column of that file has values EXACTLY the same as given in debug section bellow ?

I've tried to converting it into a list:

- set_fact:
   std_out: "{{ test.stdout.split()|list   }}"

... and then comparing it with particular list items:

- name: Test if it worked
  debug:
     msg: Values are differrent
  when: std_out[0] == "CC" and std_out[1] == "BB" and std_out[2] == "DD"

but got errors like this:

The error was: template error while templating string: unexpected char u'"'

Tried couple more things but still got some issues and feeling like banging my head against the wall :-) Any help would be apprieciated.

My setup is:

ansible 2.9.14
python version = 2.7.5
3
  • You are missing a closing double quote in your set fact task => std_out: "{{ test.stdout.split()|list }}", and your when clause is also missing a double quote => when: std_out[0] == "CC" and std_out[1] == "BB" and std_out[2] == "DD" Commented Mar 10, 2021 at 17:04
  • Note: I am absolutely not sure this will actually solve your logic problem... Commented Mar 10, 2021 at 17:13
  • Well spoted, but of course it was not the real case. I was simply re-writing code and made that silly mistakes. Sorry for that. Commented Mar 10, 2021 at 17:36

1 Answer 1

1

Use the registered value, e.g.

    - name: Check 3rd column of file
      shell: cat my_file.txt | awk '{print $3}'
      register: test

gives

  test.stdout_lines:
  - CC
  - BB
  - DD

You can compare the lists, e.g.

    - debug:
        msg: Values are differrent
      when: test.stdout_lines != ['CC', 'BB', 'DD']
    - debug:
        msg: Values are not differrent
      when: test.stdout_lines == ['CC', 'BB', 'DD']

gives

TASK [debug] *******************************************************************
skipping: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => 
  msg: Values are not different
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.