场景:某公司内部有1台路由器,1台核心交换机,2台接入交换机,希望通过ansible来进行管理。
做法:
1. 基础配置
linux主机下创建ansible文件夹,文件夹内创建ansible.cfg(名字不能改)和hosts(名字可改),
ansible.cfg 内容如下:
[defaults]
host_key_checking = False #跳过SSH key的检查
inventory = ./hosts #使用自定义的设备目录
timeout = 5 #连接超时
hosts 内容如下:
[R] #路由器
10.0.0.241
[CS] #核心交换机
10.0.0.242
[AS] #接入交换机
10.0.0.243
10.0.0.244
[all:vars]
ansible_user = user #登录用户名
ansible_password = password #登录密码
ansible_connection = network_cli #连接类型
ansible_network_os = ios #设备类型,ios是思科
ansible_port = 22 #连接端口
2. 测试连通性
在ansible目录下运行命令:
$ ansible AS -m ping #只ping接入交换机
10.0.0.244 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
10.0.0.243 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}
$ ansible all -m ping #ping所有网络设备
(结果略,包含"ping": "pong"则表示设备可达)
3. 运行查看命令
在ansible目录下运行命令:
$ ansible CS -m ios_command -a "commands='show ip int br'"
10.0.0.242 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"stdout": [
"Interface IP-Address OK? Method Status Protocol\nGigabitEthernet0/0 unassigned YES unset up up \nGigabitEthernet0/1 unassigned YES unset up up \nGigabitEthernet0/2 unassigned YES unset up up \nGigabitEthernet0/3 10.0.0.242 YES manual up up \nGigabitEthernet1/0 unassigned YES unset up up \nGigabitEthernet1/1 unassigned YES unset up up \nGigabitEthernet1/2 unassigned YES unset up up \nGigabitEthernet1/3 unassigned YES unset up up \nVlan1 unassigned YES manual up up"
],
"stdout_lines": [
[
"Interface IP-Address OK? Method Status Protocol",
"GigabitEthernet0/0 unassigned YES unset up up ",
"GigabitEthernet0/1 unassigned YES unset up up ",
"GigabitEthernet0/2 unassigned YES unset up up ",
"GigabitEthernet0/3 10.0.0.242 YES manual up up ",
"GigabitEthernet1/0 unassigned YES unset up up ",
"GigabitEthernet1/1 unassigned YES unset up up ",
"GigabitEthernet1/2 unassigned YES unset up up ",
"GigabitEthernet1/3 unassigned YES unset up up ",
"Vlan1 unassigned YES manual up up"
]
]
}
下一节,运行剧本来对设备的进行自动配置,点击跳转:网络管理自动化 - Ansible 入门(2)