Clear all pending devices with script

I got fed up with the clearing of pending devices all the time during development/testing and I didn’t want to use the reject option from the web ui. So playing a bit with the API from bash I got this:

MENDER_SERVER_URI='https://hosted.mender.io';
MENDER_SERVER_USER='[YOUR_USERNAME HERE]';
JWT=$(curl -X POST -u $MENDER_SERVER_USER $MENDER_SERVER_URI/api/management/v1/useradm/auth/login);
curl -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer $JWT" -d '{"status": "pending"}' -X POST https://hosted.mender.io/api/management/v2/devauth/devices/search?per_page=500 | jq '[.[] | {id}]' | grep id | sed -r 's/\"//g' | sed -r 's/\ //g' | cut -d':' -f2 | while read i; do  \
    curl \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -H "Authorization: Bearer $JWT" \
    -X DELETE https://hosted.mender.io/api/management/v2/devauth/devices/{$i}; done

Which decommissions/dismisses the latest 500 pending devices.

The above as an oneliner:

sudo apt-get install curl jq && MENDER_SERVER_URI='https://hosted.mender.io' && MENDER_SERVER_USER='[YOUR_USERNAME HERE]' && JWT=$(curl -X POST -u $MENDER_SERVER_USER $MENDER_SERVER_URI/api/management/v1/useradm/auth/login) && curl -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer $JWT" -d '{"status": "pending"}' -X POST https://hosted.mender.io/api/management/v2/devauth/devices/search?per_page=500 | jq '[.[] | {id}]' | grep id | sed -r 's/\"//g' | sed -r 's/\ //g' | cut -d':' -f2 | while read i; do curl -H 'Content-Type: application/json' -H 'Accept: application/json' -H "Authorization: Bearer $JWT" -X DELETE https://hosted.mender.io/api/management/v2/devauth/devices/{$i}; done

What the above commands do is authenticate with the server, get the list of (last 500) pending devices, and calls the decommission command for each one in a bash-based while loop. Apart from the loop the rest are REST API calls. The script was used in Ubuntu but could easily be modified (curl, jq and while parts) to work in your OS.

I am happy now :slight_smile:

1 Like

Nice. Thanks for posting this.

Could be nicer but does the work :wink:

Just added the script in a code-block for future viewers :slight_smile:
Thank you @bender

Was looking for this but tried the triple backticks and the preview got blank so I didn’t try it. Fixed the top post. Thanks!

1 Like