Преобразовать значение переменной ANSIBLE на основе входных данных - PullRequest
0 голосов
/ 23 сентября 2019

Всего нубов здесь учится Сетевая автоматизация с использованием Ansible с Jinja2.

Мне нужно определить команду диапазона на основе количества переключателей в стеке, например, я спрашиваю ввод в playbook, что-тостроки "Сколько коммутаторов в вашем стеке?"и основываясь на этом ответе, я бы вывел команду диапазона и назначил ее переменной, которую я могу вызвать в моей пьесе.

Я знаю, чего хочу, но просто не могу на всю жизньЯ понимаю, как выполнить это в Ansible, я полностью осознаю, что ниже это неправильно, но, надеюсь, это должно дать вам представление о том, чего я пытаюсь достичь?

vars_prompt;
  - name: numberOfSwitches
    prompt: 'How many switches in the stack?'
    private: no

if {{ number of switches }} == '4' then
numberOfSwitches='gi1/0/1-48,gi2/0/1-48,gi3/0/1-48,gi4/0/1-48'

Я могу тогда назвать этопеременная в моем шаблоне jinja2 для настройки всех портов доступа на коммутаторе

Еще раз извините за мою нубность: -)

EDIT

Playbook

---

- name: Generate and Deploy Configuration
  hosts: switches
  gather_facts: false
  connection: network_cli
  vars_prompt:

    - name: hostname
      prompt: "What is the hostname?"
      private: no
    - name: dataVlanID
      prompt: "What is the Data Vlan ID?"
      private: no
    - name: dataVlanName
      prompt: "What is the Data Vlan name?"
      private: no
    - name: voiceVlanID
      prompt: "What is the Voice Vlan ID?"
      private: no
    - name: voiceVlanName
      prompt: "What is the Voice Vlan Name?"
      private: no
    - name: snmpLocation
      prompt: "For SNMP, where will this switch be installed?"
      private: no
    - name: mgmtVlanIP
      prompt: "What is the management IP of this switch?"
      private: no

  vars:
    ansible_ssh_user: staging
    ansible_ssh_pass: staging
    ansible_network_os: ios
    enableSecret: cisco2
    userName: cisco2
    userPassword: cisco2
    nameServerOne: 10.50.191.3
    nameServerTwo: 10.50.191.131
    startSwitch: 1
    ntpPrefer: 10.50.191.3
    ntpBackup: 10.50.191.131

  tasks:
    - name: Generate Running Configuration 
      template: 
        src="/etc/ansible/jinja2-template/base_with_vars.j2" 
        dest=/etc/ansible/config/{{ inventory_hostname }}_interface.txt
      register: interface

    - name: Push Configuration to Device
      ios_config:
        src: /etc/ansible/config/{{ inventory_hostname }}_interface.txt
      notify: Write Memory
      when: interface.changed

  handlers:
    - name: Write Memory
      ios_command:
        commands: wr

Хосты

[switches]
SW1 ansible_host=10.222.0.131

Шаблон Jija2

no service pad
service tcp-keepalives-in
service tcp-keepalives-out
service timestamps debug datetime msec
service timestamps log datetime msec localtime show-timezone
service password-encryption
no service dhcp
!
hostname {{hostname}}
!
boot-start-marker
boot-end-marker
!
logging buffered 1000000
enable secret {{enableSecret}}
!
username {{userName}} privilege 15 secret {{userPassword}}
aaa new-model
!
!
aaa authentication login AAA_METHOD_CONSOLE local
aaa authentication login AAA_METHOD_VTY group radius local
aaa authorization commands 0 default if-authenticated 
aaa authorization commands 1 default if-authenticated 
aaa authorization commands 15 default if-authenticated 
!
!
!
!
!
!
aaa session-id common
clock timezone AEST 10 0
!
!
!
!
no ip source-route
ip dhcp bootp ignore
!
!
ip dhcp snooping vlan 1-4094
ip dhcp snooping database flash:dhcp-snooping.db
ip dhcp snooping
ip domain-name rccprd.redland.qld.gov.au
ip name-server {{nameServerOne}}
ip name-server {{nameServerTwo}}
login block-for 120 attempts 3 within 30
login on-failure log
login on-success log
vtp domain {{hostname}}
vtp mode transparent
!
!
!
!
vlan 8
 name PRD-RCC-SECURITY
!
vlan 16
 name PRD-RCC-PRINTER
!
!
vlan 56
 name PRD-RCC-WIFI-AD
!
vlan {{dataVlanID}}
 name {{dataVlanName}}
!
vlan {{voiceVlanID}}
 name {{voiceVlanName}}
!
vlan 998
 name PRD_RCC_DEAD-VLAN
!
vlan 999
 name PRD_RCC_NATIVE-VLAN
!
vlan 4000
 name MANAGEMENT_VLAN
!
lldp run
!
!
!
!
interface Vlan4000
 ip address {{mgmtVlanIP}} 255.255.255.0
 no shutdown
!
!
!
!
!
flow record Scrutinizer-Record1
 match datalink mac source address input
 match datalink mac destination address input
 match ipv4 tos
 match ipv4 protocol
 match ipv4 source address
 match ipv4 destination address
 match transport source-port
 match transport destination-port
 collect transport tcp flags
 collect interface input
 collect flow sampler
 collect counter bytes long
 collect counter packets long
 collect timestamp sys-uptime first
 collect timestamp sys-uptime last
!
!
flow exporter Scrutinizer-Export1
 destination 10.50.150.231
 source Vlan4000
 transport udp 2055
 template data timeout 60
 option interface-table
 option exporter-stats
 option sampler-table
!
!
flow monitor Scrutinizer-Monitor1
 exporter Scrutinizer-Export1
 cache timeout active 60
 statistics packet protocol
 record Scrutinizer-Record1
!
!
archive
 path flash:/Config-Archive/
 write-memory
memory reserve critical 4096
memory free low-watermark processor 20
memory free low-watermark IO 20
!
spanning-tree mode mst
spanning-tree extend system-id
!
spanning-tree mst configuration
 name RCC-MST
 instance 1 vlan 1-4094
!
spanning-tree mst 1 priority 61440
!
!
!
!
!
!
!
!
interface Port-channel1
 description LACP to HO HP Core
 switchport trunk allowed vlan 1,2,8,16,48,56,121,621,4000
 switchport trunk native vlan 999
 switchport mode trunk
 ip dhcp snooping trust
!
interface range GigabitEthernet{{startSwitch}}/0/1-48
 description Client Access Port
 switchport access vlan {{dataVlanID}}
 switchport voice vlan {{voiceVlanID}}
 switchport mode access
 switchport port-security maximum 10
 switchport port-security violation restrict
 switchport port-security aging time 1440
 switchport port-security
 ip flow monitor Scrutinizer-Monitor1 input
 storm-control broadcast level 80.00 50.00
 storm-control multicast level 80.00 50.00
 storm-control action trap
 spanning-tree portfast edge
!
!
ip default-gateway 10.2.0.254
!
no ip http server
no ip http secure-server
!
ip ssh time-out 10
ip ssh source-interface Vlan4000
ip ssh version 2
!
ip access-list standard SNMP-SERVERS
 permit 10.50.150.232
 permit 10.50.150.231
 permit 10.50.150.20
 permit 10.50.220.35
 permit 10.50.220.28
 permit 10.50.220.29
 permit 10.50.220.27
 deny   any log
!
kron occurrence KRON-OCC-0200 at 2:00 recurring
 policy-list KRON-POL-SAVE-CONFIG
!
kron occurrence KRON-OCC-0300 at 3:00 recurring
 policy-list KRON-POL-SCP-CONFIG
!
kron policy-list KRON-POL-SAVE-CONFIG
 cli wr 
!
kron policy-list KRON-POL-SCP-CONFIG
 cli copy running-config scp://admin:rgrs753jlh@10.50.40.170/{{hostname}}/
!
logging origin-id hostname
logging facility local6
logging source-interface Vlan4000
logging host 10.50.220.63
logging host 10.50.150.20
!
snmp-server group RCC-SNMP-GROUP v3 priv read SNMPv3-RO-VIEW access SNMP-SERVERS
snmp-server view SNMPv3-RO-VIEW internet included
snmp-server trap-source Vlan4000
snmp-server location {{snmpLocation}}
snmp-server contact IT Service Desk (07) 3829 8432
snmp-server chassis-id {{hostname}}
snmp-server enable traps snmp authentication linkdown linkup coldstart warmstart
snmp-server enable traps config
snmp-server enable traps cpu threshold
snmp-server enable traps vlancreate
snmp-server enable traps vlandelete
snmp-server enable traps envmon fan shutdown supply temperature status
!
!
radius server RADIUS-POOL
 address ipv4 10.50.220.62 auth-port 1645 acct-port 1646
 key 7 0214325C06045D17790F28352F54260A19060B6F122D0B760631322F2719027E7C5C711A0E4C52480F706A5D5C615F54372D6C0306362C14481801280C6B401F2B
!
banner exec ^CC
#######################################################################
# This computer system is for authorised use only.                    #
# Users have no explicit or implicit expectation of privacy.          #
# Any or all uses of this system and all data on this system may      #
# be intercepted, monitored, recorded, copied, audited, inspected,    #
# and disclosed to authorised sites and law enforcement personnel,    #
# as well as authorised officials of other agencies.                  #
# By using this system, you consent to such disclosure at the         #
# discretion of authorised site personnel.                            #
# Unauthorised or improper use of this system may result in           #
# administrative disciplinary action, civil and criminal penalties.   #
# By continuing to use this system you indicate your awareness of     #
# and consent to these terms and conditions of use. STOP IMMEDIATELY  #
# if you do not agree to the conditions stated in this warning.       #
#######################################################################
^C
banner login ^CC 
#######################################################################
# This computer system is for authorised use only.                    #
# Users have no explicit or implicit expectation of privacy.          #
# Any or all uses of this system and all data on this system may      #
# be intercepted, monitored, recorded, copied, audited, inspected,    #
# and disclosed to authorised sites and law enforcement personnel,    #
# as well as authorised officials of other agencies.                  #
# By using this system, you consent to such disclosure at the         #
# discretion of authorised site personnel.                            #
# Unauthorised or improper use of this system may result in           #
# administrative disciplinary action, civil and criminal penalties.   #
# By continuing to use this system you indicate your awareness of     #
# and consent to these terms and conditions of use. STOP IMMEDIATELY  #
# if you do not agree to the conditions stated in this warning.       #
#######################################################################
^C
configuration mode exclusive
!
line con 0
 logging synchronous
 login authentication AAA_METHOD_CONSOLE
line vty 0 4
 exec-timeout 30 0
 privilege level 15
 logging synchronous
 login authentication AAA_METHOD_VTY
 length 0
 transport input ssh
line vty 5 15
 exec-timeout 30 0
 privilege level 15
 logging synchronous
 login authentication AAA_METHOD_VTY
 transport input ssh
!
exception memory ignore overflow processor
exception memory ignore overflow io
ntp source Vlan4000
ntp server {{ntpPrefer}} prefer
ntp server {{ntpBackup}}
!
end

1 Ответ

0 голосов
/ 23 сентября 2019

Игра ниже

- hosts: localhost
  vars_prompt:
    - name: numberOfSwitches
      prompt: 'How many switches in the stack?'
      private: no
  tasks:
    - set_fact:
        my_switches: "{{ my_switches|default([]) +
                       [ 'gi' ~ item ~ '/0/1-48' ] }}"
      loop: "{{ range(1, numberOfSwitches|int + 1, 1)|list }}"
    - template:
        src: my_switches.j2
        dest: /tmp/my_switches.conf

с этим шаблоном

$ cat my_switches.j2
{{ my_switches|join(", ") }}

дает

$ cat /tmp/my_switches.conf
gi1/0/1-48, gi2/0/1-48, gi3/0/1-48, gi4/0/1-48
...