定义playbook的主机组
说明:
1、playbook的主机组和ansible的主机组不一样,
2、playbook的主机组文件必须要和playbook文件在同一个目录下否则会报如下错误:
[root@test1 profile]# ansible-playbook -i hosts deploy_flanneld.yaml --list-hosts
[WARNING]: Unable to parse /k8s/profile/hosts as an inventory source
3、执行playbook必须要在plyaybook文件所在目录下执行,否则报错;跟带不带绝对路径没有关系,必须保证在同一个目录
4、执行playbook的任何相关操作都要在plyaybook文件所在目录下执行,否则报错;跟带不带绝对路径没有关系,必须保证在同一个目录
cat >/k8s/profile/hosts <<EOF
[webservers]
192.168.0.91
192.168.0.92
EOF
playbook文件
cat > /k8s/profile/deploy_nginx.yaml <<EOF
---
- hosts: webservers
become: yes
become_method: sudo
vars:
worker_processes: 4
worker_connections: 768
max_open_files: 65506
tasks:
- name: install nginx
command: yum install nginx -y
- name: copy nginx config file
template: src=/home/lmx/test_ansible/nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: restart nginx
- name: copy index.html
template:
src: /home/lmx/test_ansible/index.html.j2
dest: /usr/share/nginx/www/index.html
mode: 0644
notify: restart nginx
- name: see file
command: ls /root
notify: restart nginx
handlers:
- name: restart nginx
service: name=nginx state=restarted
EOF
模板文件
mkdir -p /home/lmx/test_ansible/
cat > /home/lmx/test_ansible/nginx.conf.j2 << EOF
worker_processes {{ worker_processes }};
worker_rlimit_nofile {{ max_open_files }};
events {
worker_connections {{ worker_connections }};
}
http {
server {
listen 80;
root /usr/share/nginx/www;
index index.html index.htm default.html index.php;
server_name loclhost;
location / {
try_files $uri $uri/ =404;
}
}
}
EOF
cat > /home/lmx/test_ansible/index.html.j2 <<EOF
<html>
<head>
<title>welcome to american</title>
</head>
<body>
<h1>nginx, confitured by ansible</h1>
<p>if you can see this, ansible successfully installed nginx.</p>
<p>{{ ansible_hostname }}</p>
</body>
</html>
EOF
开始部署:
说明:必须切换到playbook所在文件目录下执行,否则报错
[root@test1 ~]# cd /k8s/profile/
[root@test1 profile]# ansible-playbook deploy_nginx.yaml