实验题目
有三台centos7 使用ansible批量安装httpd ,并且不同主机显示的网页根据主机名动态变化,比如:主机node1,网页显示welcome node1
ip:172.29.9.5 (ansible server)
ip: 172.29.9.6/17 (被管理的服务器)
实验步骤:
root@centos8 ~]#vim /etc/ssh/ssh_config
#修改下面一行
StrictHostKeyChecking no
- 配置ssh基于key的免密登录脚本
vi ssh_key.sh
#!/bin/bash
user=`whoami`
if [ $user != 'root' ];then
echo 'you id is not root!'
exit 2
fi
IPLIST="
172.29.9.6
172.29.9.17" #发送公钥到authorized_keyr的服务器ip列表
rpm -q sshpass &>/dev/null || yum -y install sshpass # 安装sshpass
[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa -P '' #生成密钥对
export SSHPASS='123' #把root密码设置为环境变量,可以用sshpass -e 指定密码了
#下面用ssh-copy-id 把公钥拷贝到目标机器的 authorized_key文件中
for ip in $IPLIST;do
sshpass -e ssh-copy-id -o StrictHostKeyChecking=no root@$ip
done
2.安装ansible,使用epel源中的包直接安装
yum -y install ansible
3.准备目录结构
mkdir -p /data/ansible/{files,templates}
准备httpd.yml
[root@localhost ansible]# cat httpd.yml
---
#install httpd
- hosts: webservers
remote_user: root
# gather_facts: no
tasks:
- name: Install Httpd
yum: name=httpd state=present
- name: Install Configure File
copy: src=files/httpd.conf dest=/etc/httpd/conf/
- name: Web Page File
template: src=index.html.j2 dest=/var/www/html/index.html
- name: Start Service
service: name=httpd state=started enabled=yes
准备httpd.conf 和 index.html.j2(网页模板文件)
[root@localhost templates]# cat index.html.j2
welcome {{ansible_hostname}}
检查目录结构
[root@localhost ansible]# tree /data/
/data/
└── ansible
├── files
│ └── httpd.conf
├── httpd.yml
└── templates
└── index.html.j2
4.测试并执行ansible playbook
[root@localhost ansible]# ansible-playbook --syntax-check httpd.yml
playbook: httpd.yml
注:或者使用你-C 选项检测可能发生的改变 ansible-playbook -Chttpd.yml
执行:ansible-playbook httpd.yml
5.浏览网页验证结果