Ansible Ping from command line not working

Hi There, I am new to Ansible so just learning at the moment and have a question regarding variables and how to access them under specific scenarios.

A bit of background, I’ve setup a couple of inventory files and splitting them out for various different functions and I have a couple of basic playbooks, mostly for discovering information about my network. This all works great.

What I’m struggling to understand, if I want to use the ping module from the command line, how can i get ansible to use my stored variable for username and password. When i do this using a playbook I have an entry in the YAML file pointing at the var_files, like shown below:

- name: Gather Facts from Cisco IOS Devices
  hosts: corp_edge_cisco
  gather_facts: true
  vars_files: ../groupvars/default.yaml
  tasks:
  - name: Gather facts

But when I run the following command:
ansible corp_edge_cisco -i ansible/inventory/corp_edge_network.ansible.yaml -m ping

This does not have a reference to where the variables are stored so throws the following error:

cisco | FAILED! => {
    "msg": "The field 'remote_user' has an invalid value, which includes an undefined variable. The error was: 'netadmin_username' is undefined. 'netadmin_username' is undefined"
}

I’m aware I could create a playbook which defines a task to ping and passes the varible file, but I’m wondering if the structure I have in place is wrong and maybe the inventory file should be linking directly to the variable files?

Ansible inventory will dynamically pick up vars files in the host_vars and group_vars subdirectories in the same directory of the inventory file, if the vars filename matches a respective host/group in the inventory. Your playbook is directly including a groupvars/default.yaml vars file (note the missing underscore _ in the directory), but running against the corp_edge_cisco group.

What you will want instead is to rename ansible/inventory/groupvars/default.yaml to either ansible/inventory/group_vars/corp_edge_cisco.yaml or if all of your inventory will use the same defaults, rename to ansible/inventory/group_vars/all.yaml

Then your ad-hoc ping should work, and your playbook no longer needs to specify the vars_files for basic inventory information.

For reference:
How to build your inventory — Ansible Community Documentation

3 Likes

That’s worked a treat. We figured out that I can pass --extra-vars to the command line and pass the path to the vars file but what you suggested is exactly what I needed.

Had a feeling my files and folder structure wasn’t right. Thanks!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.