This playbook let’s you to replace existing NTP server on Cisco switch/router, by using regex.
From line 50 – 65 it’s extra/additional and optional- Create an empty YAML file and name it ntp.yaml with below codes:
# @author [Hawar Koyi] and [Roger Perkin] # @email [hawar@koyi.it] # @create date 2023-03-25 22:56 # @desc [Network Automation - Add/replace NTP Server & Regex Example] # @Thanks to Roger Perkin - https://www.rogerperkin.co.uk #Start of codes --- - name: Configure NTP server by using regex hosts: Cisco connection: network_cli gather_facts: false tasks: #Get running config on the devices - name: Show Run on devices #Register/save data of show running-config as value "config" register: config ios_command: commands: #show running command on the devices - show run #Get current configured NTP server - name: Store current NTP line in running-config #Go through the running-config and find the start line with the word "ntp server" #-and (\S+) any mumber match a single character that is a non-whitespace. Continue with the next line. set_fact: _ntpServeres="{{ config.stdout[0] | regex_findall('^ntp server (\S+)', multiline=True) }}" #Remove old NTP server if detected - name: Remove old ntp server ios_config: lines: #show running command on the devices - "no ntp server {{ item }}" #Register/save data of show running-config as value "config" with_items: "{{ _ntpServeres }}" #Configure new NTP server - name: Config new NTP server ios_config: lines: - "ntp server {{ ntp_server_1 }}" - "ntp server {{ ntp_server_2 }}" #Saving the configurations on start-config - name: Save running-config to start-config ios_config: save_when: modified #EXTRA (Optional) #Display final results on the device run and start-config #Get retur output from show commands - name: Get retur output from show commands #Register data as value get_ntp register: get_ntp ios_command: commands: - "show run | include ntp" - "show start | i ntp" #Display final results for run and start-config on the devices. - name: Show finally configurations on both start and running-config debug: var: get_ntp.stdout #End of codes
- Create an empty text file and name it hosts with devices IP-addresses, vars and values for ntp_server variable.
[Cisco] 192.168.0.100 192.168.xx.xx [Cisco:vars] ansible_connection=network_cli ansible_network_os=ios ansible_user=cisco ansible_password=cisco ansible_become=yes ansible_become_method=enable ansible_become_password=cisco ntp_server_1=193.150.22.36 ntp_server_2=192.36.143.130
- Finally run the playbook with this command
ansible-playbook -i hosts ntp.yaml
Results looks like the video below.
Like it if you want too Linkedin