安装两台nginx服务器并且配置workers数目与CPU核心数目一致,且分别监听8080和9090 tcp端口,然后启动这两台web服务器。
第一步:先复制一个配置文件ngnix.conf到控制主机目录/root/playbooks下并且重命名为:nginx.conf.j2
更改ngnix.conf.j2文件,做如下两处修改:
1、worker_processes {{ ansible_processor_vcpus }};
2、listen {{ http_port }};
第二部:在控制主机的/etc/ansible/hosts文件末尾添加以下三行:
[webservers]
受控主机1的IP地址 ansible_ssh_user=root http_port=8080
受控主机2的IP地址 ansible_ssh_user=root http_port=9090
第三步:在控制主机上编写一个installnginx.yaml文件:
- hosts: webservers
remote_user: root
tasks:
# 安装nginx
- name: install nginx
yum: name=nginx state=present
# 根据模板文件生成配置文件并且复制到受控主机的/etc/nginx/ngnix.conf,并且通知restart nginx任务
- name: install conf file
template: src=/root/playbooks/nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: restart nginx
tags: instconf
# 启动nginx服务
- name: start nginx service
service: name=nginx state=started
# 如果受控主机上的配置文件发生变化,则重启nginx服务程序。
handlers:
- name: restart nginx
service: name=nginx state=restarted
第四步:执行以下命令
ansible-playbook installingix.yaml
检查执行结果:
分别在两台受控主机上执行:ss -tnlp | grep nginx 查询nginx运行情况,受控主机分别监听tcp 8080和9090端口。
更改控制主机的/etc/ansible/hosts文件,把如上添加的3行更改成以下:
[webservers][webservers]
101.132.74.113 ansible_ssh_user=root http_port=80
101.34.33.209 ansible_ssh_user=root http_port=80
运行指定标签的任务:ansible-playbook --tags=instconf installnigix.yaml
分别在两台受控主机上执行:ss -tnlp | grep nginx 查询nginx运行情况: