Execute shell commands using Ansible

0 votes

I want to check on all my hosts and this command is perfect for it

ansible -m shell -a "ps -eo pcpu,user,args | sort -r -k1 | head -n5"

But the problem is I have to execute it in multiple places and that gets annoying. Can I use this shell command in Ansible playbook? 

Jan 24 in Ansible by Nagya
787 views

1 answer to this question.

0 votes

You can use a playbook for this obviously, it will definitely make your work easier. You could use this playbook, it worked for me

hosts: all
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
      register: ps

    - debug: var=ps.stdout_lines
ok: [host1] => {
    "ps.stdout_lines": [
        "%CPU USER     COMMAND",
        " 1.0 root     /usr/bin/python",
        " 0.6 root     sshd: root@ayaan ",
        " 0.2 root     java",
        " 0.0 root     sort -r -k1"
    ]
}
ok: [host2] => {
    "ps.stdout_lines": [
        "%CPU USER     COMMAND",
        " 4.0 root     /usr/bin/python",
        " 0.6 root     sshd: root@ayaan ",
        " 0.1 root     java",
        " 0.0 root     sort -r -k1"
    ]
}
answered Jan 24 by Ayaan

Related Questions In Ansible

0 votes
1 answer

How do I execute a shell script and then use the result in ansible

This can work out for you: - name: ...READ MORE

answered Apr 11, 2018 in Ansible by shubham
• 6,870 points
467 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How can I create a new user using ansible ploybook?

You're switching from the root user. Root ...READ MORE

answered Mar 29, 2018 in Ansible by DareDev
• 6,810 points
86 views
+13 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Execute a command using ansible playbook

Hey @Reshma, You can use the URI ...READ MORE

answered Jan 17 in Ansible by Sameer
95 views
0 votes
1 answer

Trying to execute bash script using Ansible one one node

You could make your task an asynchronous action by ...READ MORE

answered Jan 28 in Ansible by Kavya
49 views