Ansible script to change ospf cost on an interface
If you ever were in a situation where you needed to quickly change the ospf cost on multiple interfaces to manipulate traffic, an easy way to do this would be to run an ansible playbook.
Here’s an example of an Ansible playbook that changes the OSPF cost on a single interface on a Cisco device. You can modify it further to include multiple interfaces as needed.
---
- name: Change OSPF cost on Cisco device
hosts: cisco_device
gather_facts: no # Disable gathering facts for efficiency
vars:
ospf_process_id: 1
ospf_interface: GigabitEthernet0/1 # Replace with the appropriate interface name
new_cost: 1000 # Replace with the desired OSPF cost value
tasks:
- name: Configure OSPF cost
ios_command:
commands:
- "router ospf {{ ospf_process_id }}"
- "interface {{ ospf_interface }}"
- "ip ospf cost {{ new_cost }}"
register: ospf_output
- name: Check OSPF output
debug:
var: ospf_output
In this playbook, we assume that you have already set up Ansible and have the necessary inventory file configured with the target Cisco device. The inventory file should contain an entry for cisco_device
with its IP address or hostname.
To use the playbook, save it in a file like change_ospf_cost.yaml
and run the following command:
ansible-playbook -i inventory.ini change_ospf_cost.yaml
Make sure to replace inventory.ini
with the path to your actual inventory file.
Please note that this playbook uses the ios_command
module, which is part of the ansible.netcommon
collection. You may need to install this collection using the ansible-galaxy
command before running the playbook:
ansible-galaxy collection install ansible.netcommon
Also, ensure that you have the necessary connectivity and credentials to access and configure the Cisco device using Ansible.