Capturing or Trimming the right output from the ansible script

878 views Asked by At

Below is my ansible script -

- name: To delete files
  hosts: current
  gather_facts: true
  tasks:
    - name: Check for the right folder
      win_shell: |
        if (Test-Path -Path 'C:\Program Files (x86)\MF\LGG\bin') {
        Write-Output "LGG"
        setx PATH "$env:path;C:\Program Files (x86)\MF\LGG\bin" -m
        }
        else {
        Write-Output "LRR"
        setx PATH "$env:path;C:\Program Files (x86)\MF\LRR\bin" -m
        }
      register: actualpath
   - name: print output
     debug:
      msg: "output is {{ actualpath.stdout_lines }} "
   - debug: var=actualpath.stdout

My plan here is to capture the output given from the above and run another set of commands based on the output i.e. LRR or LGG

But when i try to print the output, i see it different formats like below -

TASK [print output] ************************************************************
ok: [xxx] => {
    "msg": "output is [u'LGG', u'', u'SUCCESS: Specified value was saved.'] "
}

TASK [debug] *******************************************************************
ok: [xxx] => {
    "actualpath.stdout": "LGG\r\n\r\nSUCCESS: Specified value was saved.\r\n"
}

How to make sure i only get whatever i am printing or how to trim the value and save it in the register?

1

There are 1 answers

2
Kevin C On

My plan here is to capture the output given from the above and run another set of commands based on the output i.e. LRR or LGG

You're almost doing exactly that. You could indeed try:

- name: do something if 'LGG' in previous output
  win_shell: dir
  when: "'LGG' in actualpath.stdout"

But of course, the value of actualpath depends on the output given. You can see the result of the command on the console if you configure:

- debug:
    msg: "{{ actualpath }}"

How to make sure i only get whatever i am printing

See my example above.

How to trim the value and save it in the register?

You do not need to. This is 'system' language, instead of 'human' language. It sounds like you want to make it 'pretty'.

Here are some examples which you can definitely use.

If you expect the output of actualpath to be a directory, e.g. C:\somewhere\something, then you should edit the win_shell command to ensure the output of Ansible actually outputs that value. Right now it is simply a long string.