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, 2019 in Ansible by Nagya
• 6,373 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, 2019 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
• 7,340 points
• 8,410 views
0 votes
1 answer

How do I wget a file from web server using shell in the ansible playbook

Hey Ayaan, you could probably use this ...READ MORE

answered Jan 24, 2019 in Ansible by Anushri
• 5,539 views
0 votes
1 answer
0 votes
0 answers

How do I execute MySqL query using Ansible playbook

Dear team, I'm trying to execute MySQL , ...READ MORE

Oct 4, 2021 in Ansible by anonymous
• 140 points
• 4,341 views
+15 votes
2 answers

Git management technique when there are multiple customers and need multiple customization?

Consider this - In 'extended' Git-Flow, (Git-Multi-Flow, ...READ MORE

answered Mar 27, 2018 in DevOps & Agile by DragonLord999
• 8,450 points
• 9,057 views
+2 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, 2019 in Ansible by Sameer
• 6,608 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 29, 2019 in Ansible by Kavya
• 3,338 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP