mpenning / ciscoconfparse

Parse, Audit, Query, Build, and Modify Arista / Cisco / Juniper / Palo Alto / F5 configurations.
http://www.pennington.net/py/ciscoconfparse/
GNU General Public License v3.0
793 stars 220 forks source link

Proper use of insert_after and insert_before? #199

Closed netopsengineer closed 3 years ago

netopsengineer commented 3 years ago

Hello @mpenning ,

I have tried to understand from the docs how to use these two methods, but having troubles, essentially I want to find a line in the config as an anchor point that I know exists,

!
!
cable profile downstream DS1
!
!

and add several blocks of config before or after it

afterSection= '''!
cable profile load-balance XXXX
 method utilization us-method modems
 threshold load 30
 threshold stability 70
 policy pure-ds-load
 docsis-policy 1
 interval 300
!
cable profile load-balance YYYY
 restricted
 interval 5
 tag TAG_STB
!
'''

Any guidance would be appreciated!

mpenning commented 3 years ago

I apologize for the delay in my response... without getting into too much detail, recently something bizarre happened simultaneously to my personal and work github logins and it took me a while to come back...

In short, insert_after() can be run from the base CiscoConfParse() parse instance, or from an interface object itself... let's consider the interface object case...

I'm using your terminology of the "anchor point"; this is how you can insert config lines after the anchor point... the .reverse() on your list of afterSection config lines is a little non-intuitive and I'll improve that in the future...

from ciscoconfparse import CiscoConfParse

config = """!
!
!
cable profile downstream DS1
!
!"""

afterSection= """!
cable profile load-balance XXXX
 method utilization us-method modems
 threshold load 30
 threshold stability 70
 policy pure-ds-load
 docsis-policy 1
 interval 300
!
cable profile load-balance YYYY
 restricted
 interval 5
 tag TAG_STB
!
"""

parse = CiscoConfParse(config.splitlines())

all_changes_list = afterSection.splitlines()
# If you have a list of lines to add in order, reverse() the list...
all_changes_list.reverse()

for anchor_obj in parse.find_objects("^cable\s+profile\s+downstream"):
    # Iterate over your *reversed config* and insert lines after the anchor
    for line in all_changes_list:
        anchor_obj.insert_after(line)
parse.commit()  # commit() is req'd any time you finish modifying the config...
netopsengineer commented 3 years ago

@mpenning hey buddy, no problem! Glad you got your account sorted out! This helps alot, appreciate you showing the sample, the reverse() was definitely a piece I was missing and would have taken me a while to try the obvious on! I have chopped through thousands of lines of config that we were going to change by hand on hundreds of devices, so thank you for sharing your work!