ansible安装及配置使用
环境: centos7.5
yum安装,ansible版本:2.7.5
master_ip: 172.28.128.3
node01_ip: 172.28.128.5
node02_ip: 172.28.128.4
配置无密钥访问
- 生成公钥
ssh-keygen -t rsa
- 公钥下发
ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.28.128.5
或拷贝公钥至目标服务器
cat id_rsa.pub >> /root/.ssh/authorized_keys
添加ansible访问
修改/etc/ansible/hosts文件
#添加
[node]
172.28.128.4
172.28.128.5
测试访问
# ansible node -m ping
172.28.128.5 | SUCCESS => {
"changed": false,
"ping": "pong"
}
172.28.128.4 | SUCCESS => {
"changed": false,
"ping": "pong"
}
编写httpd playbook
- hosts: node
remote_user: root
tasks:
# 在node节点安装httpd服务
- name: install httpd packages
yum: name=httpd state=latest
# 修改配置文件
- name: copy httpd.conf to httpd
copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf
# 加上tags 使用--tags=conf即可
tags: conf
# 加上notify,当修改时触发handlers,
notify:
- restart httpd
# 启动服务
- name: start httpd service
service: enabled=true name=httpd state=started
# 添加handlers
handlers:
# 名称需要与notify的名称一致
- name: restart httpd
service: name=httpd state=restarted
使用命令 ansible-playbook httpd.yaml
即可运行
运行结果
PLAY [all] *********************************************************************************************************************************************************
TASK [Gathering Facts] *********************************************************************************************************************************************
ok: [172.28.128.5]
ok: [172.28.128.4]
TASK [install httpd packages] **************************************************************************************************************************************
changed: [172.28.128.5]
changed: [172.28.128.4]
TASK [copy httpd.conf to httpd] ************************************************************************************************************************************
changed: [172.28.128.5]
changed: [172.28.128.4]
TASK [start httpd service] *****************************************************************************************************************************************
changed: [172.28.128.5]
changed: [172.28.128.4]
RUNNING HANDLER [restart httpd] ************************************************************************************************************************************
changed: [172.28.128.4]
changed: [172.28.128.5]
PLAY RECAP *********************************************************************************************************************************************************
172.28.128.4 : ok=5 changed=4 unreachable=0 failed=0
172.28.128.5 : ok=5 changed=4 unreachable=0 failed=0
分别查看两台服务器,发现httpd服务已启动。