Ansible使用总结
什么是Ansible
Ansible是一种集成IT系统的配置管理,应用部署,执行特定任务的开源平台。主要基于Paramiko和PyYAML两个模块。
安装Ansible
这里是在CentOS7上安装使用的,首先要开启epel源:
# yum install -y epel-release
配置公私钥证书登录
# ssh-kegen -t rsa -C "lightless@foxmail.com"
# ssh-copy-id -i /root/.ssh/id_rsa.pub root@1.1.1.1
# ssh-copy-id -i /root/.ssh/id_rsa.pub root@2.2.2.2
定义主机组
默认的配置文件在/etc/ansible/hosts
有点像ini的格式:
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
# - Comments begin with the '#' character
# - Blank lines are ignored
# - Groups of hosts are delimited by [header] elements
# - You can enter hostnames or ip addresses
# - A hostname/ip can be a member of multiple groups
# Ex 1: Ungrouped hosts, specify before any group headers.
## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10
# Ex 2: A collection of hosts belonging to the 'webservers' group
## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110
# If you have multiple hosts following a pattern you can specify
# them like this:
## www[001:006].example.com
# Ex 3: A collection of database servers in the 'dbservers' group
## [dbservers]
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57
# Here's another example of host ranges, this time there are no
# leading 0s:
## db-[99:101]-node.example.com
默认的配置文件中提供了一些例子,这里说一些特殊的
别名
jumpserver ansible_ssh_port=22 ansible_ssh_host=1.1.1.1
这个是为主机定义一个别名,名称叫jumpserver
,后面定义了host和port,除此之外还有一些保留的变量名:
- ansible_ssh_host
- ansible_ssh_port
- ansible_ssh_user
- ansible_ssh_pass
- ansible_connection, 连接类型,可以是local、ssh、或者是paramiko
- ansible_ssh_privite_key_file
- ansible_*_interpreter, 指定采用非python的其他脚本语言,例如ruby、perl等
主机变量
主机可以指定变量,以便提供给playbooks使用
host1 http_port=80 maxRequestsPerChild=100
host2 http_port=8080 maxRequestsPerChild=200
定义组变量
组变量就是变量的作用域会覆盖组所有成员
[atlanta]
host1
host2
[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com
此外还有嵌套组,但是只在ansible-playbook中生效。
分离主机与数据
- /etc/ansible/group_vars/+组名 存放指定组名定义的变量
- /etc/ansible/host_vars/+主机名 存放指定主机名定义的变量
Ansible模块与API
通过ansible <host/group name> -m <module name> -a "param"
进行调用模块。
ansible vultr -m command -a "uptime"
等价于
ansible vultr -a "uptime"
查看模块帮助信息
ansible-doc ping
playbooks中执行命令方法
- name: reboot the server
command: /sbin/reboot -t now