ansible最佳实战部署nginx
1、先看下整体目录架构 [root@bogon ~]# cd /etc/ansible/ [root@bogon ansible]# tree . ├── ansible.cfg ├── group_vars │ └── all ├── hosts ├── roles │ └── webservs │ ├── handlers │ │ └── main.yml │ ├── README.md │ ├── tasks │ │ ├── install_nginx.yaml │ │ └── main.yaml │ └── templates │ ├── index.html.j2 │ └── nginx.conf.j2 ├── site.retry └── site.yaml 6 directories, 11 files 2、初始化一个role [root@bogon ~]# ansible-galaxy init /etc/ansible/roles/websrvs 查看已经创建的role [root@bogon ~]# ls /etc/ansible/roles/ webservs 把初始化后, role里面没用的目录删除,没有的目录就创建,按照第一步的目录架构来 3、配置ansible.cfg [root@bogon ansible]# cat ansible.cfg [defaults] inventory = /etc/ansible/hosts sudo_user=root remote_port=22 host_key_checking=False remote_user=root log_path=/var/log/ansible.log module_name=command private_key_file=/root/.ssh/id_rsa 4、配置变量all文件,注意:名字只能写成all,写其他的就报错 [root@bogon group_vars]# cat all --- # vars file for /etc/ansible/roles/webservs worker_processes: 4 worker_connections: 768 max_open_files: 65506 5、配置site.yaml作为执行入口文件,里面定义都对哪些roles操作 [root@bogon ansible]# cat site.yaml --- # this playbook deploy the whole application stack in this site - name: configuration and deploy webservers and application code hosts: webservers roles: - webservs 6、配置handlers文件 ,就是触发器,比如满足条件后启动nginx [root@bogon webservs]# cat handlers/main.yml --- # handlers file for /etc/ansible/roles/webservs - name: restart nginx service: name=nginx state=restarted 7、配置tasks, 这是具体执行操作的yaml文件 [root@bogon webservs]# cat tasks/main.yaml --- - include: install_nginx.yaml [root@bogon webservs]# cat tasks/install_nginx.yaml --- # tasks file for /etc/ansible/roles/webservs - name: install nginx command: yum install nginx -y - name: copy nginx config file template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf notify: restart nginx - name: copy index.html template: src: index.html.j2 dest: /usr/share/nginx/www/index.html mode: 0644 notify: restart nginx - name: see file command: ls /root notify: restart nginx 8、配置templates。 就是准备需要的模板文件,没有就不用准备 [root@bogon webservs]# cat templates/nginx.conf.j2 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 / =404; } } } [root@bogon webservs]# cat templates/index.html.j2 <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> 9、执行部署 [root@bogon ansible]# ls ansible.cfg group_vars hosts roles site.retry site.yaml [root@bogon ansible]# ansible-playbook site.yaml