Ansible ad-hoc mode is your friend if you need to gather, well, ad-hoc information from your networking infrastructure, or servers for that matter.

Of course, if you have a (single) source of truth, you’d be better off searching there :-)

Let’s say you want to know where to find a device with a certain MAC address :

ansible -c network_cli \
  -m nxos_command -a "commands='show mac address-table address 0011.0022.0033'" \
  datacenter_switches \
  | egrep -B 3 'Eth'

If you’re not (yet) using a centralized dynamic inventory, this assumes you’re in the directory where your inventory file lives and what’s more it’s rather a lot to type innit ?

To make life a little less unpleasant, let’s add a Unix/Linux shell ‘shortcut’ by defining a couple of (bash) functions in either system wide /etc/profile.d or your ~/.bash_profile :

function net_cli() {
  local _inventory_directory="/home/ops/ansible"
  limit=${4:+--limit "$4"}
  pushd . &> /dev/null
  cd "$_inventory_directory" && \
  ansible "$3" -c network_cli -m "$1" -a "commands='$2'" $limit
  popd &> /dev/null
}
function nxos_cmd() { net_cli "nxos_command" "$1" "$2" "$3"; }
function ios_cmd() { net_cli "ios_command" "$1" "$2" "$3"; }
function datacenter() { nxos_cmd "$1" 'datacenter_switches'${2:+,"$2"} "${@:3}"; }

 

After sourcing this (or logging out/in), you can enter: datacenter 'show ver' , or include more host patterns: datacenter 'show ver' 'pattern1,pattern2' , or limit to certain host(s): datacenter ',' 'my_inventory_host'

If you’ve changed the Ansible stdout callback in ansible.cfg or your environment, you may need to add -v to show the stdout results. Either that, or change the call to Ansible in net_cli() into:

  cd "$_inventory_directory" && \
   ANSIBLE_STDOUT_CALLBACK='default' ANSIBLE_BIN_ANSIBLE_CALLBACKS='1' \
    ansible -i switches.yaml "$3" -c network_cli -m "$1" -a "commands='$2'" $limit