ansible-playbook简单使用template

实验题目

有三台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
  1. 配置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.浏览网页验证结果
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值