ansible-playbook模板的简单应用
需求:
多台机器根据硬件指标来设置nginx的worker_processes,并为nginx设置不同的端口.
实现步骤
- 在不知道cpu变量名称的情况下,使用ansible的setup模块来获取cpu的变量名称
[root@localhost playbook]# ansible all -m setup | grep cpu
"ansible_processor_vcpus": 2,
"ansible_processor_vcpus": 2,
- 为每台机器设置不同的端口号:
[node]
192.168.0.107 hostname=node1 port=80
192.168.0.108 hostname=node2 port=81
- 创建templates目录并设置nginx配置文件模板,模板名称后缀为
.j2:
mkdir templates
cp /etc/nginx/nginx.conf ./templates/nginx.conf.j2
- 修改nginx模板:
[root@localhost playbook]# cat templates/nginx.conf.j2
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes {{ ansible_processor_vcpus*2 }}; #此处使用cpu数量的2倍
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
server {
# 为每台机器指定nginx端口
listen {{ port }} default_server;
listen [::]:{{ port }} default_server;
- 创建nginx服务的yaml文件:
[root@localhost playbook]# cat nginx.yaml
---
- hosts: all
remote_user: root
vars:
- pkg1: nginx
- port: 88
tasks:
- name: install {{ pkg1 }}
yum: name=nginx
- name: close httpd
service: name=httpd state=stopped
- name: copy {{ pkg1 }} config file
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify:
- restartsrv
- name: start {{ pkg1 }} server
service: name=nginx state=started enabled=yes
handlers:
- name: restartsrv
service: name=nginx state=restarted
- nginx.yaml文件语法检查:
[root@localhost playbook]# ansible-playbook nginx.yaml -C
- 运行
[root@localhost playbook]# ansible-playbook nginx.yaml
8.验证
[root@localhost playbook]# ansible node -m shell -a 'ss -ntpl | grep nginx'
192.168.0.108 | CHANGED | rc=0 >>
LISTEN 0 128 *:81 *:* users:(("nginx",pid=2963,fd=6),("nginx",pid=2962,fd=6),("nginx",pid=2961,fd=6),("nginx",pid=2960,fd=6),("nginx",pid=2959,fd=6))
LISTEN 0 128 :::81 :::* users:(("nginx",pid=2963,fd=7),("nginx",pid=2962,fd=7),("nginx",pid=2961,fd=7),("nginx",pid=2960,fd=7),("nginx",pid=2959,fd=7))
192.168.0.107 | CHANGED | rc=0 >>
LISTEN 0 128 *:80 *:* users:(("nginx",pid=7775,fd=6),("nginx",pid=7774,fd=6),("nginx",pid=7773,fd=6),("nginx",pid=7772,fd=6),("nginx",pid=7771,fd=6))
LISTEN 0 128 :::80 :::* users:(("nginx",pid=7775,fd=7),("nginx",pid=7774,fd=7),("nginx",pid=7773,fd=7),("nginx",pid=7772,fd=7),("nginx",pid=7771,fd=7))
``










网友评论