As the title suggests, use Ansible to build a proxy server with nginx on multiple remote servers. This time I'm using an AWS EC2 instance as the remote server.
--Build a server on multiple EC2 instances with one command. --When adding an instance, just add the target IP address.
What to do when executing the ansible command.
Installed in the local environment to run. Now you can use the command ʻansible-playbook`.
$ pip install ansible
.
|-- webapp.yml
|-- hosts
|-- nginx.conf
`-- myapp.j2
myapp.j2
server {
listen 80;
server_name 0.0.0.0;
location / {
proxy_pass {{ proxy_pass }};
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache zone1;
proxy_cache_key $proxy_host$uri$args;
proxy_cache_valid 600s;
}
}
Prepare nginx.conf
in the same directory.
webapp.yml
- hosts: web-servers
user: ec2-user
sudo: True
vars:
proxy_pass: '<Origin URL>'
tasks:
#Install nginx.
- name: Install nginx
yum: name=nginx state=latest
#Create a cache directory.
- name: Create Cache
action: file dest=/var/cache/nginx/cache state=directory owner=nginx group=nginx
#Local nginx.Copy conf remotely.
- name: Copy the default nginx config file
action: copy src=./nginx.conf dest=/etc/nginx/nginx.conf
#Local myapp.j2 to myapp.Compile to conf and copy remotely.
- name: Write the original nginx config file
action: template src=./myapp.j2 dest=/etc/nginx/conf.d/myapp.conf
#Start nginx.
notify:
- Start nginx
handlers:
- name: Start nginx
action: service name=nginx state=restarted
[web-servers]
54.64.xxx.xxx
54.64.yyy.yyy
54.64.zzz.zzz
$ ansible-playbook ./webapp.yml --private-key ~/.ssh/mykey.pem -i ./hosts
If the configuration is as simple as starting a web server, Ansible can be written simply, and when adding the target remote server, it is only added to the hosts file, so I was able to do exactly what I wanted to do :) It's a Python library, but it's also attractive that you only write yaml and ini file-like hosts files. I recommend it because I was able to do it in about 3 hours while watching the tutorial etc .: D
Recommended Posts