The first step to using an API is being able to connect to the device. The last step should always be to disconnect properly. I want to quickly show you how to utilize the API of the AOS-CX operating system in Ansible.
This initial step will be setting up the Ansible Inventory. In this case, I have used a really simple inventory.
I created a file called “hosts.yml” and filled it with the following content (password censored).
hosts.ymlThis allows us to use the switches “aos_cx1” and “aos_cx2” as hosts in our Ansible Playbook.
Afterwards, I created a Playbook with the name “configure.yml” and filled it with some basic information:
configure.yml - basic information
The first line (“hosts: all”) tells Ansible to run this Playbook for all available hosts. Thus, this will run for “aos_cx1” and “aos_cx2” from the inventory. The Ansible “connection” is set up as “local” because we will connect to both switches using the API manually. I also do not want to gather facts from the local system, so I disabled it by setting “gather_facts” to “no”. Lastly, I set the environment of my Ansible Playbook to not use any HTTP or HTTPS proxy because I want to make sure that Ansible does not start using one of my existing system proxies for the API requests.
The next step is to fill my Playbook with tasks which connect to the Switch, then properly disconnect from the Switch.
configure.yml - Login/LogoutI have used the Ansible URI Module to execute the API requests for me. I am simply passing the correct URI, API Method, Body, and expected status code to the URI Module and it will do everything else. The Switch needs to have web management SSL and REST enabled. The parts of a string which are enclosed by curly brackets are variables which we gather from the inventory or create at runtime. Furthermore, I am making sure that we will logout from the Switch even if we run into an error by specifying the logout below “always:”.
The next step would be to utilize the URI Module to use the API in between the logout and login. I have chosen to let the Playbook display all ports that are up. Therefore, you only need to add the following in between login and logout.
configure.yml - GET Request
You can start the Playbook by entering in the CLI (If the files are in different directories, add the path to the file name): “ansible-playbook configure.yml –i hosts.yml”. Ansible will then print the feedback for each task. Thus we will see all interfaces that are up (in this case for one host).
Ansible Output