Skip to content

Instantly share code, notes, and snippets.

@leejones
Last active April 15, 2016 15:52
Show Gist options
  • Save leejones/e978ad325dbc19713876b36a14ebec6f to your computer and use it in GitHub Desktop.
Save leejones/e978ad325dbc19713876b36a14ebec6f to your computer and use it in GitHub Desktop.
Interactive Console for Chef Server

If you want to interact with the chef server using the chef gem, you can get an interactive console using knife exec. This can be useful when trying out ideas for automation.

For example, how do I get the IP for a single (random) node for a role (example requires that pry is available):

$> bundle exec knife exec -E "require 'pry'; binding.pry"
[1] pry(#<Object>)> search(:node, 'role:solr-search').shuffle.first.ipaddress
=> "10.45.10.189"

To see all methods available, use pry's ls method:

[2] pry(#<Object>)> ls
Shell::Extensions::ObjectCoreExtensions#methods:
  all_help_descriptions  ensure_session_select_defined  explain_command             help_banner        off  singleton_method_added
  desc                   explain                        find_or_create_session_for  help_descriptions  on   subcommands
Chef::DSL::PlatformIntrospection#methods: platform?  platform_family?  value_for_platform  value_for_platform_family
Chef::DSL::DataQuery#methods: data_bag  data_bag_item  search
self.methods:
  api              become_node  clients    databags      echo   edit          halp  ls    nodes  recipe_mode  roles     shell  trace?   tracing?
  attributes_mode  chef_run     cookbooks  doppelganger  echo?  environments  help  node  ohai   reset        run_chef  trace  tracing  version
instance variables: @desc  @explain  @help_descriptions  @subcommand_help
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_  context  script  scripts

We can see that cookbooks is a method available in this context. Let's see how many we have:

[7] pry(#<Object>)> cookbooks.all.count
=> 202
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment