Giniúint agus líonadh uathoibríoch eilimintí cumraíochta gléas líonra ag baint úsáide as Nornir

Giniúint agus líonadh uathoibríoch eilimintí cumraíochta gléas líonra ag baint úsáide as Nornir

Hey Habr!

Le déanaí tháinig alt anseo Mikrotik agus Linux. Gnáthamh agus uathoibriú áit ar réitíodh fadhb chomhchosúil le modhanna iontaise. Agus cé go bhfuil an tasc go hiomlán tipiciúil, níl aon rud den chineál céanna faoi Habré. Ba mhaith liom mo rothar a thairiscint don phobal measúil TF.

Ní hé seo an chéad rothar le haghaidh tasc den sórt sin. Cuireadh an chéad rogha i bhfeidhm roinnt blianta ó shin ar ais i ansible leagan 1.x.x. Is annamh a úsáideadh an rothar agus mar sin bhí sé i gcónaí meirgeach. Sa chiall nach dtagann an tasc féin chun cinn chomh minic agus a nuashonraítear leaganacha ansible. Agus gach uair is gá duit a thiomáint, titeann an slabhra as nó titeann an roth as. Mar sin féin, oibríonn an chéad chuid, a ghineann configs, i gcónaí go han-soiléir, fortunately girseach 2 Tá an t-inneall seanbhunaithe. Ach an dara cuid, rolladh amach na configs, de ghnáth thug iontas. Agus ós rud é go gcaithfidh mé an cumraíocht a rolladh amach go cianda go leath céad gléas, cuid acu atá suite na mílte ciliméadar ar shiúl, bhí baint úsáide as an uirlis seo beagán leadránach.

Ní mór dom a admháil anseo gurb é an t-easpa cur amach atá agam ar an éiginnteacht is mó is dócha ansiblená ina easnaimh. Agus is pointe tábhachtach é seo, dála an scéil. ansible is réimse iomlán ar leith é, a réimse eolais féin a bhfuil a DSL féin (Teanga Sainiúil Fearainn), nach mór a choinneáil ag leibhéal muiníneach. Bhuel, an nóiméad sin ansible Tá sé ag forbairt go tapa go leor, agus gan aird ar leith ar chomhoiriúnacht ar gcúl, ní chuireann sé muinín.

Mar sin, ní fada ó shin a cuireadh an dara leagan den rothar i bhfeidhm. An uair seo ar python, nó in áit ar chreat scríofa i python agus le haghaidh python ar a dtugtar Nornir

Mar sin - Nornir is microframework scríofa i python agus le haghaidh python agus atá deartha le haghaidh uathoibrithe. Mar an gcéanna leis an gcás le ansible, chun fadhbanna a réiteach anseo, tá gá le hullmhú inniúil sonraí, i.e. fardal na n-óstach agus a bparaiméadar, ach ní scríobhtar scripteanna i DSL ar leith, ach sa chéanna níl siad an-sean, ach an-mhaith p[i|i]ton.

Breathnaímid ar a bhfuil sé ag baint úsáide as an sampla beo seo a leanas.

Tá gréasán brainse agam le dosaen oifigí ar fud na tíre. Tá ródaire WAN ag gach oifig a chuireann deireadh le roinnt bealaí cumarsáide ó oibreoirí éagsúla. Is é BGP an prótacal ródaithe. Tagann ródairí WAN in dhá chineál: Cisco ISG nó Juniper SRX.

Anois an tasc: ní mór duit subnet tiomnaithe le haghaidh Faireachais Físeáin a chumrú ar phort ar leith ar gach ródaire WAN den líonra brainse - fógairt an subnet seo i BGP - cumraigh luasteorainn an chalafoirt tiomnaithe.

Ar dtús, ní mór dúinn cúpla teimpléad a ullmhú, ar a mbonn a ghinfear cumraíochtaí ar leithligh do Cisco agus Juniper. Is gá freisin sonraí a ullmhú le haghaidh gach pointe agus paraiméadair naisc, i.e. an fardal céanna a bhailiú

Teimpléad réidh le haghaidh 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

Teimpléad le haghaidh 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

Ní thagann teimpléid, ar ndóigh, as aer tanaí. Go bunúsach is difríochtaí iad seo idir na cumraíochtaí oibre a bhí agus a bhí tar éis an tasc a réiteach ar dhá ródaire ar leith de mhúnlaí éagsúla.

Ónár dteimpléid feicimid nach bhfuil ach dhá pharaiméadar ag teastáil uainn le haghaidh aitil agus 3 pharaiméadar do Cisco chun an fhadhb a réiteach. seo iad:

  • ifainm
  • iarmhír
  • asn

Anois ní mór dúinn na paraiméadair seo a shocrú do gach feiste, i.e. an rud céanna a dhéanamh fardal.

Chun fardal Leanfaimid go docht leis an doiciméadú Nornir a thionscnamh

is é sin, cruthaímid an creatlach comhaid céanna:

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

Is é an comhad config.yaml an comhad cumraíochta caighdeánach 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"

Cuirfimid na príomh-pharaiméadair in iúl sa chomhad óstaigh.yaml, grúpa (is logins/pasfhocail iad seo i mo chás) isteach grúpaí.yamlagus i réamhshocraithe.yaml Ní chuirfimid rud ar bith in iúl, ach ní mór duit trí lúide a chur isteach ann - ag léiriú go bhfuil yaml tá an comhad folamh áfach.

Seo an chuma atá ar hosts.yaml:

---
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

Agus seo grúpaí.yaml:

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

juniper:
    platform: junos
    username: admin2
    password: juniper2

Seo mar a tharla fardal dár dtasc. Le linn thúsaithe, déantar paraiméadair ó chomhaid fardail a mhapáil chuig an tsamhail réad Eilimint Fhardail.

Anseo thíos tá léaráid den tsamhail 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"
                }
            }
        }
    }
}

Is féidir leis an tsamhail seo breathnú beagán mearbhall, go háirithe ar dtús. D'fhonn é a dhéanamh amach, an modh idirghníomhach i iipitín.

 $ 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'

Agus ar deireadh, déanaimis bogadh ar aghaidh go dtí an script féin. Níl rud ar bith agam le bheith bródúil as anseo. Níor ghlac mé ach sampla réidh ó teagaisc agus d'úsáid sé beagnach gan athrú. Seo an chuma atá ar an script oibre chríochnaithe:

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)

Tabhair aird ar an bparaiméadar dry_run=Fíor i líne tosaigh réadú nr.
Anseo mar an gcéanna i ansible tá rith tástála curtha i bhfeidhm ina ndéantar nasc leis an ródaire, ullmhaítear cumraíocht leasaithe nua, a bhailíochtaíonn an gléas ansin (ach níl sé seo cinnte; braitheann sé ar thacaíocht an ghléis agus ar chur i bhfeidhm an tiománaí i NAPALM) , ach ní chuirtear an chumraíocht nua i bhfeidhm go díreach. Le húsáid chomhrac, ní mór duit an paraiméadar a bhaint tirim_rith nó a luach a athrú go Bréagach.

Nuair a chuirtear an script i gcrích, aschuir Nornir logaí mionsonraithe chuig an consól.

Faoi bhun an spoiler tá aschur rith comhraic ar dhá ródaire tástála:

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 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Folaithe pasfhocail in ansible_vault

Ag tús an ailt chuaigh mé beagán thar fóir ansible, ach níl sé chomh dona sin. Is maith liom iad go mór cruinneachán cosúil le, atá deartha chun faisnéis íogair a cheilt as radharc. Agus is dócha gur thug go leor faoi deara go bhfuil logáil isteach / pasfhocail againn do gach ródaire comhraic súilíneach i bhfoirm oscailte i gcomhad gorups.yaml. Níl sé go hálainn, ar ndóigh. A ligean ar a chosaint sonraí seo le cruinneachán.

Aistrímid na paraiméadair ó groups.yaml go creds.yaml, agus criptigh le AES256 é le pasfhocal 20-dhigit:

$ 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

Tá sé chomh simplí sin. Tá sé fós a mhúineadh ár Nornir-script chun na sonraí seo a aisghabháil agus a chur i bhfeidhm.
Chun seo a dhéanamh, inár script tar éis an líne initialization nr = InitNornir(config_file=… cuir an cód seo a leanas leis:

...
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
...

Ar ndóigh, níor chóir vault.passwd a bheith suite in aice le creds.yaml mar atá i mo shampla. Ach tá sé ceart go leor chun imirt.

Sin go léir faoi láthair. Tá cúpla alt eile faoi Cisco + Zabbix ag teacht, ach níl sé seo beagán faoi uathoibriú. Agus go luath amach anseo tá sé beartaithe agam scríobh faoi RESTCONF i Cisco.

Foinse: will.com

Add a comment