Soo saarista tooska ah iyo buuxinta walxaha qaabaynta aaladaha shabakada iyadoo la adeegsanayo Nornir

Soo saarista tooska ah iyo buuxinta walxaha qaabaynta aaladaha shabakada iyadoo la adeegsanayo Nornir

Haye Habr!

Dhawaan waxaa halkan ka soo baxay maqaal Mikrotik iyo Linux. Caadi ah iyo automation halkaas oo dhibaato la mid ah lagu xalliyey iyadoo la isticmaalayo hab fosil. In kasta oo hawshu gabi ahaanba tahay mid caadi ah, ma jiraan wax la mid ah oo ku saabsan Habré. Waxaan ku dhiiraday inaan baaskiilkayga u bandhigo bulshada IT-ga ee ixtiraamka leh.

Tani maaha baaskiilkii ugu horreeyay ee hawshan oo kale ah. Doorashadii ugu horreysay waxaa la hirgeliyay dhowr sano ka hor oo dib loo soo galay macquul ah nooca 1.x.x. Baaskiilku si naadir ah ayaa loo isticmaali jiray, sidaas darteedna si joogto ah ayuu u daxalaystay. Macnaha ah in hawsha lafteedu aanay soo bixin inta jeer ee nuqullada la cusbooneysiiyo macquul ah. Mar kasta oo aad u baahato in aad baabuur wadato, silsiladdu way ka dhacaysaa ama taayirku wuu ka dhacaa. Si kastaba ha ahaatee, qaybta hore, abuurista configs, had iyo jeer u shaqeeya si cad, nasiib wanaag jinja2 Matoorku waa dheeraa. Laakiin qaybta labaad - soo-rogid configs - inta badan waxay keentay yaabab. Iyo tan iyo markii aan ku qasbanahay in aan u soo saaro qaabeynta meel fog ilaa nus boqol qalab, kuwaas oo qaar ka mid ah ay ku yaalaan kumanaan kiiloomitir, isticmaalka qalabkani wuxuu ahaa mid caajis ah.

Halkan waa inaan qirto in hubanti la'aantayda ay u badan tahay inay ku jirto aqoon la'aantayda macquul ahmarka loo eego cilladaheeda. Oo tani, habka, waa qodob muhiim ah. macquul ah waa mid gebi ahaanba gooni ah, aag u gaar ah oo aqoon leh DSL (Domain Specific Language), kaas oo ay tahay in lagu ilaaliyo heer kalsooni leh. Hagaag, markaas macquul ah Si degdeg ah ayay u horumaraysaa, iyada oo aan tixgelin gaar ah loo yeelan is-waafajinta dambe, kuma soo kordhinayso kalsooni.

Sidaa darteed, wax aan sidaas u fogayn ayaa la hirgeliyay nooca labaad ee baaskiilka. Markan waa python, ama halkii qaab-dhismeedka ku qoran python iyo python loo yaqaan Nornir

Markaa - Nornir waa qaab-dhismeed yar oo ku qoran python iyo python oo loogu talagalay otomaatiga. La mid ah kiiskii macquul ah, si loo xalliyo dhibaatooyinka halkan, diyaarinta xogta karti leh ayaa loo baahan yahay, i.e. liiska martida loo yahay iyo xuduudahooda, laakiin qoraallada kuma qorna DSL gaar ah, laakiin isku mid ma aha, laakiin aad u wanaagsan p[i|i] ton.

Aynu eegno waxa ay adeegsanayso tusaalahan soo socda.

Waxaan leeyahay shabakad laan ah oo leh dhowr iyo toban xafiis oo dalka oo dhan ah. Xafiis kastaa wuxuu leeyahay WAN router kaas oo joojiya dhowr kanaal oo isgaarsiineed oo kala duwan. Hab-maamuuska hab-socodka waa BGP. WAN router waxay u kala baxaan laba nooc: Cisco ISG ama Juniper SRX.

Hadda hawshu: waxaad u baahan tahay inaad dejiso shabakad-hoosaad u go'an oo loogu talagalay Ilaalinta Fiidiyowga ee deked gooni ah dhammaan jiheeyayaasha WAN ee shabakadda laanta - ku xayeysiiso subnet-kan BGP - habee xadka xawaaraha dekeddu u go'an tahay.

Marka hore, waxaan u baahanahay inaan diyaarino dhowr qaab, oo ku saleysan qaabeynta loo soo saari doono si gaar ah Cisco iyo Juniper. Waxa kale oo lagama maarmaan ah in la diyaariyo xogta dhibic kasta iyo xuduudaha isku xirka, i.e. ururiyaan alaab isku mid ah

Nashqada u diyaarsan Cisco:

$ cat templates/ios/base.j2 
class-map match-all VIDEO_SURV
 match access-group 111

policy-map VIDEO_SURV
 class VIDEO_SURV
    police 1500000 conform-action transmit  exceed-action drop

interface {{ host.task_data.ifname }}
  description VIDEOSURV
  ip address 10.10.{{ host.task_data.ipsuffix }}.254 255.255.255.0
  service-policy input VIDEO_SURV

router bgp {{ host.task_data.asn }}
  network 10.40.{{ host.task_data.ipsuffix }}.0 mask 255.255.255.0

access-list 11 permit 10.10.{{ host.task_data.ipsuffix }}.0 0.0.0.255
access-list 111 permit ip 10.10.{{ host.task_data.ipsuffix }}.0 0.0.0.255 any

Qaabka Juniper:

$ cat templates/junos/base.j2 
set interfaces {{ host.task_data.ifname }} unit 0 description "Video surveillance"
set interfaces {{ host.task_data.ifname }} unit 0 family inet filter input limit-in
set interfaces {{ host.task_data.ifname }} unit 0 family inet address 10.10.{{ host.task_data.ipsuffix }}.254/24
set policy-options policy-statement export2bgp term 1 from route-filter 10.10.{{ host.task_data.ipsuffix }}.0/24 exact
set security zones security-zone WAN interfaces {{ host.task_data.ifname }}
set firewall policer policer-1m if-exceeding bandwidth-limit 1m
set firewall policer policer-1m if-exceeding burst-size-limit 187k
set firewall policer policer-1m then discard
set firewall policer policer-1.5m if-exceeding bandwidth-limit 1500000
set firewall policer policer-1.5m if-exceeding burst-size-limit 280k
set firewall policer policer-1.5m then discard
set firewall filter limit-in term 1 then policer policer-1.5m
set firewall filter limit-in term 1 then count limiter

Templates, dabcan, kama soo baxaan hawo khafiif ah. Kuwani asal ahaan way ku kala duwan yihiin qaabaynta shaqada kuwaas oo ahaa iyo ka dib markii ay xaliyeen hawsha laba router gaar ah oo noocyo kala duwan ah.

Laga soo bilaabo qaab-dhismeedkayada waxaan ku aragnaa in si loo xalliyo dhibaatada, waxaan u baahanahay kaliya laba qaybood oo loogu talagalay Juniper iyo 3 xuduudaha Cisco. waa kuwan:

  • haddii magac
  • ipsuffix
  • asn

Hadda waxaan u baahanahay inaan u dhigno xuduudahan qalab kasta, i.e. same wax la mid ah Liiska.

Si aad u Liiska Waxaan si adag u raaci doonaa dukumentiyada Bilaabida Nornir

taasi waa, aynu abuurno isla qalfoofka faylka:

.
├── config.yaml
├── inventory
│   ├── defaults.yaml
│   ├── groups.yaml
│   └── hosts.yaml

Faylka config.yaml waa faylka qaabeynta caadiga ah ee nornir

$ cat config.yaml 
---
core:
    num_workers: 10

inventory:
    plugin: nornir.plugins.inventory.simple.SimpleInventory
    options:
        host_file: "inventory/hosts.yaml"
        group_file: "inventory/groups.yaml"
        defaults_file: "inventory/defaults.yaml"

Waxaan ku tusi doonaa xuduudaha ugu muhiimsan ee faylka martigeliyay.yaml, kooxda (xaaladkayga kuwani waa login/passwords) gudaha kooxaha.yaml, halka caadyaal.yaml Waxba ma tilmaamayno, laakiin waxaad u baahan tahay inaad geliso saddex minuses halkaas - taas oo muujinaysa inay tahay yaml faylku waa madhan yahay.

Tani waa waxa hosts.yaml u eg:

---
srx-test:
    hostname: srx-test
    groups: 
        - juniper
    data:
        task_data:
            ifname: fe-0/0/2
            ipsuffix: 111

cisco-test:
    hostname: cisco-test
    groups: 
        - cisco
    data:
        task_data:
            ifname: GigabitEthernet0/1/1
            ipsuffix: 222
            asn: 65111

Oo halkan waa kooxaha.yaml:

---
cisco:
    platform: ios
    username: admin1
    password: cisco1

juniper:
    platform: junos
    username: admin2
    password: juniper2

Sidan ayaa dhacday Liiska hawsheenna. Inta lagu jiro bilawga, cabbirada faylalka alaabada ayaa lagu sawiray qaabka shayga Qaybta Alaabada.

Qaswada hoose waxaa ku yaal jaantuska qaabka InventoryElement

print(json.dumps(InventoryElement.schema(), indent=4))
{
    "title": "InventoryElement",
    "type": "object",
    "properties": {
        "hostname": {
            "title": "Hostname",
            "type": "string"
        },
        "port": {
            "title": "Port",
            "type": "integer"
        },
        "username": {
            "title": "Username",
            "type": "string"
        },
        "password": {
            "title": "Password",
            "type": "string"
        },
        "platform": {
            "title": "Platform",
            "type": "string"
        },
        "groups": {
            "title": "Groups",
            "default": [],
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "data": {
            "title": "Data",
            "default": {},
            "type": "object"
        },
        "connection_options": {
            "title": "Connection_Options",
            "default": {},
            "type": "object",
            "additionalProperties": {
                "$ref": "#/definitions/ConnectionOptions"
            }
        }
    },
    "definitions": {
        "ConnectionOptions": {
            "title": "ConnectionOptions",
            "type": "object",
            "properties": {
                "hostname": {
                    "title": "Hostname",
                    "type": "string"
                },
                "port": {
                    "title": "Port",
                    "type": "integer"
                },
                "username": {
                    "title": "Username",
                    "type": "string"
                },
                "password": {
                    "title": "Password",
                    "type": "string"
                },
                "platform": {
                    "title": "Platform",
                    "type": "string"
                },
                "extras": {
                    "title": "Extras",
                    "type": "object"
                }
            }
        }
    }
}

Habkani wuxuu u ekaan karaa wax yar oo jahawareer ah, gaar ahaan marka hore. Si loo ogaado, habka is-dhexgalka ayaa ku jira Python.

 $ ipython3
Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from nornir import InitNornir                                                                           

In [2]: nr = InitNornir(config_file="config.yaml", dry_run=True)                                                

In [3]: nr.inventory.hosts                                                                                      
Out[3]: 
{'srx-test': Host: srx-test, 'cisco-test': Host: cisco-test}

In [4]: nr.inventory.hosts['srx-test'].data                                                                                    
Out[4]: {'task_data': {'ifname': 'fe-0/0/2', 'ipsuffix': 111}}

In [5]: nr.inventory.hosts['srx-test']['task_data']                                                     
Out[5]: {'ifname': 'fe-0/0/2', 'ipsuffix': 111}

In [6]: nr.inventory.hosts['srx-test'].platform                                                                                
Out[6]: 'junos'

Ugu dambeyntiina, aan u gudubno qoraalka laftiisa. Ma hayo wax aan si gaar ah ugu faano halkan. Kaliya waxaan ka soo qaatay tusaale diyaarsan waxbarashada oo u adeegsaday ku dhawaad ​​aan isbeddelin. Tani waa sida qoraalka shaqadu u ekaado:

from nornir import InitNornir
from nornir.plugins.tasks import networking, text
from nornir.plugins.functions.text import print_title, print_result

def config_and_deploy(task):
    # Transform inventory data to configuration via a template file
    r = task.run(task=text.template_file,
                 name="Base Configuration",
                 template="base.j2",
                 path=f"templates/{task.host.platform}")

    # Save the compiled configuration into a host variable
    task.host["config"] = r.result

    # Save the compiled configuration into a file
    with open(f"configs/{task.host.hostname}", "w") as f:
        f.write(r.result)

    # Deploy that configuration to the device using NAPALM
    task.run(task=networking.napalm_configure,
             name="Loading Configuration on the device",
             replace=False,
             configuration=task.host["config"])

nr = InitNornir(config_file="config.yaml", dry_run=True) # set dry_run=False, cross your fingers and run again

# run tasks
result = nr.run(task=config_and_deploy)
print_result(result)

U fiirso halbeegga dry_run=Run bilowga shayga xariiqda nr.
Halkan la mid ah sida in macquul ah Imtixaan tijaabo ah ayaa la hirgeliyay kaas oo isku xirka router-ka la sameeyay, qaab cusub oo wax laga beddelay ayaa la diyaariyey, ka dibna lagu ansixiyay aaladda (laakiin tani lama hubo; waxay kuxirantahay taageerada aaladda iyo hirgelinta darawalka ee NAPALM) , laakiin qaabeynta cusub si toos ah looma dabaqo. Isticmaalka dagaalka, waa inaad ka saartaa cabbirka qallalan ama u beddelo qiimaheeda Beenta.

Marka qoraalka la fuliyo, Nornir wuxuu soo saaraa qoraallo faahfaahsan console-ka.

Qaswada hoose waxaa ku yaal soo-saarka dagaal ee ku socda laba router oo tijaabo ah:

config_and_deploy***************************************************************
* cisco-test ** changed : True *******************************************
vvvv config_and_deploy ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
---- Base Configuration ** changed : True ------------------------------------- INFO
class-map match-all VIDEO_SURV
 match access-group 111

policy-map VIDEO_SURV
 class VIDEO_SURV
    police 1500000 conform-action transmit  exceed-action drop

interface GigabitEthernet0/1/1
  description VIDEOSURV
  ip address 10.10.222.254 255.255.255.0
  service-policy input VIDEO_SURV

router bgp 65001
  network 10.10.222.0 mask 255.255.255.0

access-list 11 permit 10.10.222.0 0.0.0.255
access-list 111 permit ip 10.10.222.0 0.0.0.255 any
---- Loading Configuration on the device ** changed : True --------------------- INFO
+class-map match-all VIDEO_SURV
+ match access-group 111
+policy-map VIDEO_SURV
+ class VIDEO_SURV
+interface GigabitEthernet0/1/1
+  description VIDEOSURV
+  ip address 10.10.222.254 255.255.255.0
+  service-policy input VIDEO_SURV
+router bgp 65001
+  network 10.10.222.0 mask 255.255.255.0
+access-list 11 permit 10.10.222.0 0.0.0.255
+access-list 111 permit ip 10.10.222.0 0.0.0.255 any
^^^^ END config_and_deploy ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* srx-test ** changed : True *******************************************
vvvv config_and_deploy ** changed : True vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv INFO
---- Base Configuration ** changed : True ------------------------------------- INFO
set interfaces fe-0/0/2 unit 0 description "Video surveillance"
set interfaces fe-0/0/2 unit 0 family inet filter input limit-in
set interfaces fe-0/0/2 unit 0 family inet address 10.10.111.254/24
set policy-options policy-statement export2bgp term 1 from route-filter 10.10.111.0/24 exact
set security zones security-zone WAN interfaces fe-0/0/2
set firewall policer policer-1m if-exceeding bandwidth-limit 1m
set firewall policer policer-1m if-exceeding burst-size-limit 187k
set firewall policer policer-1m then discard
set firewall policer policer-1.5m if-exceeding bandwidth-limit 1500000
set firewall policer policer-1.5m if-exceeding burst-size-limit 280k
set firewall policer policer-1.5m then discard
set firewall filter limit-in term 1 then policer policer-1.5m
set firewall filter limit-in term 1 then count limiter
---- Loading Configuration on the device ** changed : True --------------------- INFO
[edit interfaces]
+   fe-0/0/2 {
+       unit 0 {
+           description "Video surveillance";
+           family inet {
+               filter {
+                   input limit-in;
+               }
+               address 10.10.111.254/24;
+           }
+       }
+   }
[edit]
+  policy-options {
+      policy-statement export2bgp {
+          term 1 {
+              from {
+                  route-filter 10.10.111.0/24 exact;
+              }
+          }
+      }
+  }
[edit security zones]
     security-zone test-vpn { ... }
+    security-zone WAN {
+        interfaces {
+            fe-0/0/2.0;
+        }
+    }
[edit]
+  firewall {
+      policer policer-1m {
+          if-exceeding {
+              bandwidth-limit 1m;
+              burst-size-limit 187k;
+          }
+          then discard;
+      }
+      policer policer-1.5m {
+          if-exceeding {
+              bandwidth-limit 1500000;
+              burst-size-limit 280k;
+          }
+          then discard;
+      }
+      filter limit-in {
+          term 1 {
+              then {
+                  policer policer-1.5m;
+                  count limiter;
+              }
+          }
+      }
+  }
^^^^ END config_and_deploy ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Qarinta ereyada sirta ah ee ansible_vault

Bilowgii maqaalka waxaan yara dul maray macquul ah, laakiin intaas oo dhan ma xuma. Runtii waan jeclahay iyaga vault sida, kaas oo loogu talagalay in lagu qariyo macluumaadka xasaasiga ah ee aan la arki karin. Iyo malaha qaar badan ayaa ogaaday inaan haysano dhammaan gelitaanka / ereyada sirta ah ee dhammaan router-yada dagaalka ee ku dhalaalaya qaab furan oo fayl ah. gorups.yaml. Ma qurux badna, dabcan. Aynu ku ilaalino xogtan vault.

Aynu ka bedelno cabbirada groups.yaml una beddelno creds.yaml, oo aynu ku xafidno AES256 oo wata erey sir ah oo 20-god ah:

$ cd inventory
$ cat creds.yaml
---
cisco:
    username: admin1
    password: cisco1

juniper:
    username: admin2
    password: juniper2

$ pwgen 20 -N 1 > vault.passwd
ansible-vault encrypt creds.yaml --vault-password-file vault.passwd  
Encryption successful
$ cat creds.yaml 
$ANSIBLE_VAULT;1.1;AES256
39656463353437333337356361633737383464383231366233386636333965306662323534626131
3964396534396333363939373539393662623164373539620a346565373439646436356438653965
39643266333639356564663961303535353364383163633232366138643132313530346661316533
6236306435613132610a656163653065633866626639613537326233653765353661613337393839
62376662303061353963383330323164633162386336643832376263343634356230613562643533
30363436343465306638653932366166306562393061323636636163373164613630643965636361
34343936323066393763323633336366366566393236613737326530346234393735306261363239
35663430623934323632616161636330353134393435396632663530373932383532316161353963
31393434653165613432326636616636383665316465623036376631313162646435

Way fududahay. Way hadhsan tahay in la baro Nornir-script si loo soo saaro oo loo dabaqo xogtan.
Si tan loo sameeyo, qoraalkayaga ka dib xariiqda bilowga nr = InitNornir (config_file=… ku dar koodka soo socda:

...
nr = InitNornir(config_file="config.yaml", dry_run=True) # set dry_run=False, cross your fingers and run again

# enrich Inventory with the encrypted vault data
from ansible_vault import Vault
vault_password_file="inventory/vault.passwd"
vault_file="inventory/creds.yaml"
with open(vault_password_file, "r") as fp:
    password = fp.readline().strip()   
    vault = Vault(password)
    vaultdata = vault.load(open(vault_file).read())

for a in nr.inventory.hosts.keys():
    item = nr.inventory.hosts[a]
    item.username = vaultdata[item.groups[0]]['username']
    item.password = vaultdata[item.groups[0]]['password']
    #print("hostname={}, username={}, password={}n".format(item.hostname, item.username, item.password))

# run tasks
...

Dabcan, vault.passwd waa inuusan ku ag yaaliin creds.yaml sida tusaale ahaan. Laakin waa ok in la ciyaaro

Waa intaas hadda. Waxaa jira dhowr maqaal oo dheeraad ah oo ku saabsan Cisco + Zabbix soo socda, laakiin tani maahan wax ku saabsan otomaatiga. Iyo mustaqbalka dhow waxaan qorsheynayaa inaan wax ku qoro RESTCONF gudaha Cisco.

Source: www.habr.com

Add a comment