inventory文件
[cassandra:children]
shcp-01
shcp-06
bjyt-03
[cassandra:vars]
snmp_path=/etc/snmp/snmpd.conf
[shcp-01]
w-tri_db0[1:5].og.shcp.qihoo.net
[shcp-06]
w-tri_db[06:10].og.shcp.qihoo.net ansible_ssh_passwd=123456
[bjyt-03]
w-tri_db[03:07].og.bjtp.qihoo.net ansible_ssh_port=60022
命令行执行
ansible -i cassandra-hosts all -m shell -a "touch /root/test.yxy" -s --ask-pass --ask-sudo-pass
-s 是使用sudo
--ask-pass 是询问登录密码
--ask-sudo-pass 是询问sudo到指定用户的密码
设置变量
[yangxiaoyi1@w38v inventory]$ ls
cassandra-hosts group_vars host_vars
#
[yangxiaoyi1@w38v group_vars]$ ls
shcp-01 shcp-06
#
[yangxiaoyi1@w38v shcp-01]$ ls
login_vars
# 查看组变量
[yangxiaoyi1@w38v shcp-01]$ cat login_vars
---
sshport: 22
httpport: 80
#执行查看效果
ansible -i cassandra-hosts shcp-01 -m shell -a "echo {{sshport}}" --ask-pass
patterns
关于主机名有几种正则表达式
1. 多个组名和主机名可以用:分隔
ansible -i cassandra-hosts shcp-01:shcp06 -m ping
#在shcp-01不再shcp-06
ansible -i cassandra-hosts shcp-01:\!shcp06 -m ping
#既在shcp-01 又在shcp-06
ansible -i cassandra-hosts shcp-01:\&shcp06 -m ping
2. 通配符*的使用
ansible -i cassandra-hosts w-tri_db*.og.shcp.qihoo.net -m ping
3. 应用正则表达式 以~开头
ansible -i cassandra-hosts ~^b -m ping
4. 逻辑!的应用
ansible -i cassandra-hosts w-tri_db*.og.bjtp.qihoo.net:\!w-tri_db03.og.bjtp.qihoo.net -m ping
模块
- shell 在目标主机执行shell命令
- ansible all -m shell -a "echo hello"
- copy 模块
#复制文件
ansible all -m copy -a "src=/tmp/1.log dest=/tmp"
#复制文件夹中的内容
ansible tmp -m copy -a "src=/tmp/tmp/ dest=/tmp"
#复制整个文件夹
ansible tmp -m copy -a "src=/tmp/tmp dest=/tmp"
- file模块
#修改文件权限
ansible tmp -m file -a "dest=/tmp/1.txt owner=yangxiaoyi group=yangxiaoyi mode=600"
#删除目录和文件
ansible tmp -m file -a "dest=/tmp/tmp/1.txt state=absent"
ansible tmp -m file -a "dest=/tmp/tmp/ state=absent"
#创建目录
ansible tmp -m file -a "dest=/tmp/tmp/ state=directory"
#创建文件
ansible tmp -m file -a "dest=/tmp/tmp/file state=touch"
- yum模块
# 安装包
ansible tmp -m yum -a "name=httpd state=latest"
删除包
ansible tmp -m yum -a "name=httpd state=absent"
- User模块
ansible all -m user -a "name=foo password=<crypted password here>"
#删除用户
ansible tmp -m user -a "name=foo state=absent"
- git模块
ansible tmp -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD"
- service模块
#重启服务
ansible tmp -m service -a "name=sshd state=restarted"
value of state must be one of: reloaded, restarted, started, stopped, got: restart
- 获取facts
ansible tmp -m setup
ansible配置文件
用户可以修改一下配置文件来修改设置,他们的被读取的顺序如下:
- ANSIBLE_CONFIG (一个环境变量)
- ansible.cfg (位于当前目录中)
- .ansible.cfg (位于家目录中)
- /etc/ansible/ansible.cfg
PlayBook使用
#我们想忽略某一错误,通过执行成功与否来做决定,我们可以像这样:
tasks:
- command: /bin/false
register: result
ignore_errors: True
- command: /bin/something
when: result|failed
- command: /bin/something_else
when: result|success
- command: /bin/still/something_else
when: result|skipped
今后所有操作都使用playbook,增加熟练度
模拟场景一
- 两台线上服务器需要部署nginx、php-fpmd、
一台服务器做Mysql - 创建虚拟主机,修改服务配置文件
- 日志切割,数据库备份,优化配置,系统优化
- 启动服务
具体可按ansible文件夹中roles内容