Need to execute complex unix commands

Hi All,

I need to execute complex shell commands on remote or local hosts. What is the best way to this?

I tried multiple ways. Either it is not passing Ansible syntax, or shell script syntax

Example:

Suppose I want to execute this command

echo “ps -ef|grep data”|sed ‘s~[[1]/]+~~g’|sed “s/$/$(date +”%d_%m_%Y_%H_%M_%S")/"

It gives following output on shell :
psefgrepdata09_04_2018_12_08_55

But somehow I am not able to execute. Urgent help please ?

Thanks,
Akash


  1. :alnum: ↩︎

How about

  1. a creating a script with commands ,
  2. execute
  3. and remove

Thanks,
Suren VB

If you need to execute complex shell command, a script file run by the script module is your best bet.

This particular examples look like you’re analyzing running processes and getting a string back, not making changes to the system. This type of thing is better done by a facts plugin. Look at service_facts for an example.

`

  • hosts: localhost

tasks:

  • name: fact command
    set_fact:
    fact_command: echo “ps -ef|grep data”|sed ‘s~[[1]/]+~~g’|sed “s/$/$(date +”%d_%m_%Y_%H_%M_%S")/"

  • name: run command
    shell: “{{ fact_command }}”
    `

`
ansible-playbook test.yml -v
Using /etc/ansible/ansible.cfg as config file
[WARNING]: provided hosts list is empty, only localhost is available

PLAY ***************************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [fact command] ************************************************************
ok: [localhost] => {“ansible_facts”: {“fact_command”: “echo "ps -ef|grep data"|sed ‘s~[[2]/]\+~~g’|sed "s/$/$(date +"%d_%m_%Y_%H_%M_%S")/"”}, “changed”: false}

TASK [run command] *************************************************************
changed: [localhost] => {“changed”: true, “cmd”: “echo "ps -ef|grep data"|sed ‘s~[[3]/]\+~~g’|sed "s/$/$(date +"%d_%m_%Y_%H_%M_%S")/"”, “delta”: “0:00:00.002489”, “end”: “2018-04-16 00:47:44.957419”, “rc”: 0, “start”: “2018-04-16 00:47:44.954930”, “stderr”: “”, “stdout”: “psefgrepdata16_04_2018_00_47_44”, “stdout_lines”: [“psefgrepdata16_04_2018_00_47_44”], “warnings”: }

PLAY RECAP *********************************************************************
localhost : ok=3 changed=1 unreachable=0 failed=0
`


  1. :alnum: ↩︎

  2. :alnum: ↩︎

  3. :alnum: ↩︎

Thanks!

Is it possible to run a list of commands using this. I was able to read the commands from a file; paas it to a custom bash module and execute it.
Which is the better way ?

Thanks,
Akash

`

  • name: fact command
    set_fact:
    fact_command: >
    echo “ps -ef|grep data”|sed ‘s~[[1]/]+~~g’|sed “s/$/$(date +”%d_%m_%Y_%H_%M_%S")/"
    ;
    echo something else

`


  1. :alnum: ↩︎