I like to share how I used Ansible to change the hostname of all my 2930 devices which run the AOS-Switch operating system using REST API.
In Ansible we need to have two files in place to run an automation:
- Inventory
- Playbook
For the inventory, I created a file “hosts.yml” and filled it with the following content (password censored).
aos_switch1 ip=192.5.6.1 user=manager password=***** hostname=2930M_1
aos_switch2 ip=192.5.6.2 user=manager password=***** hostname=2930M_2
This allows us to use the switches “aos_switch1” and “aos_switch2” as target hosts in our Ansible Playbook.
The second step was to create a Playbook “configure.yml” and filled it with some basic information:
configure.yml - BasicsThe first line (“hosts: all”) tells Ansible to run this Playbook for all available hosts from inventory ( “aos_switch1” and “aos_switch2” in this case). The Ansible “connection” is setup as “local” because we will connect to both Switches using the API manually. To disable gather facts from the local system I set “no to “gather_facts”. Lastly, I set the environment of my Ansible Playbook for HTTP or HTTPS proxy as empty strings 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 and properly disconnect from the Switch again.
Every typical REST API operation has three steps:
- Connect to device
- Use the API
- Disconnect from device
configure.yml - login and logout
The Ansible URI Module helps to execute API requests. Specify the correct URI, API Method, Body, and expected status code in the URI Module and it will do everything else for you. Before running the Ansible playbook make sure switch has 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. Furthermore, make sure to logout from the switch after the execution. The code that is mentioned under “always” section, will execute even if the playbook runs into an error in the previous section.
The final step is to add a similar API call utilizing the URI Module to change the hostname. You might want to try this yourself before looking at the solution! Try to find the correct API call in the API scheme and utilize it.
configure.yml - change hostname
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 (In this case executed with one hosts instead of two).
Ansible CLI Output
The hostname of my switch has changed and the Ansible automation was successful!