ansible - 根据输入转换 ansible 变量值
问题描述
Total noob 在这里学习使用 Ansible 和 Jinja2 的网络自动化。
我需要根据堆栈中的开关数量确定范围命令,例如,我要求在剧本中输入,类似于“堆栈中有多少开关?” 并基于该答案,我将派生 range 命令并将其分配给我可以在我的剧本中调用的变量。
我知道我想要它做什么,但我一生都无法弄清楚如何在 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 模板中调用这个变量来配置交换机上的所有访问端口
再次为我的菜鸟道歉:-)
编辑
剧本
---
- 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
解决方案
下面的戏
- 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
推荐阅读
- powershell - 未在 Windows Server 上创建故障转储
- linux - 如何使用 PSQL 更改数据库中表的列名?
- java - 使用 Spring 将 Java 从 5 升级到 8
- java - 如何创建一个圆角按钮并在运行时以编程方式设置任何颜色
- html - 通过 css 或普遍应用 img-fluid 用于数据库提供的图像
- c# - 为什么在同一个类中使用构造函数参数时可以访问私有属性
- python-3.x - 获取时间序列数据框中每个日期的最后一个条目
- java - 为 URLDecoder.decode() 抛出 UnsupportedEncodingException 的示例字符串
- javascript - 如何为同一路由调用不同的控制器功能?
- ubuntu-16.04 - aerospike 中的配置以在内存已满之前通知