Skip to content

Instantly share code, notes, and snippets.

@jtimberman
Created May 8, 2020 21:32
Show Gist options
  • Save jtimberman/0012a3c842c8866037b6ff85e4dd75a7 to your computer and use it in GitHub Desktop.
Save jtimberman/0012a3c842c8866037b6ff85e4dd75a7 to your computer and use it in GitHub Desktop.
Reminder that Chef has an rich set of data and an API

Did you know that every time the chef-client runs, it knows what time it is, and it stores that value as a node attribute, ohai_time? Did you know that you can use this value for searching a Chef Infra Server? It's a Unix Epoch!

For example, let's look for the nodes that were updated in the last 10-15 minutes:

now=$(date +%s)
range_start=$(expr $now - 900)
range_end=$(expr $now - 600)

knife search node "ohai_time:[$range_start TO $range_end]" -a ohai_time -F json
{ json blob snipped }

You may be thinking "Okay Joshua, that's useless, I can't translate Unix Epochs into dates in my head. How can I make this useful?"

Enter jq - this handy utility is superb and it has a number of built in functions for data transformation. The following command will translate all valid Unix Epoch times in the ohai_time attribute into human readable date strings.

jq -cr '.rows[] | {name: to_entries[].key, last_run: (if to_entries[].value.ohai_time then (to_entries[].value.ohai_time | strflocaltime("%Y-%m-%d %H:%M")) else "-" end)}'

I set this to a shell function in my zsh profile:

function last_run() {
  jq -cr '.rows[] | {name: to_entries[].key, last_run: (if to_entries[].value.ohai_time then (to_entries[].value.ohai_time | strflocaltime("%Y-%m-%d %H:%M")) else "-" end)}'

And then I can combine it with my knife command:

% knife search node "ohai_time:[$range_start TO $range_end]" -a ohai_time -F json | last_run
{"name":"i-mycool-node-instance","last_run":"2020-05-08 15:02"}
{"name":"i-my-less-cool-thing","last_run":"2020-05-08 15:03"}
{"name":"i-an-entry-for-practice","last_run":"2020-05-08 15:03"}

Enjoy!

(Feel free to copy/paste and modify to use this as you need.)

@jtimberman
Copy link
Author

Yes, I know knife status is a thing, but it's a little inflexible for the specific use case I had (which was actually to find nodes that had been updated between a certain timeframe).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment