I recently decided to learn the basics of AWS i.e. launch EC2 instances, ssh to it and set up a couple of services on it.
One thing I came across while doing so was Configuration Management Software. Ansible became my favourite option because 1) it’s agent-less and 2) I had previously gone to a meetup that gave a brief intro to Ansible. Here is what I came up with after some experimentation: a simple playbook that sets up Nginx on a remote server.
1 — Launch an EC2 instance with the AWS console
For the purpose of this exercise, I picked an Ubuntu server, and a flavour that is within their free-tier.
I made sure to use a key I had already created to access the server, and set up the security group so that I could have the port 22 (SSH) and 80 (HTTP) open. To tighten up the security during the configuration, I restricted the access to one IP only (my computer running Mac OS X).
The AWS documentation is pretty good, and with a few clicks, you have it up and running in the cloud.
2 — SSH to the instance to make sure you can access it.
ssh -i path_to_my_key/my_key.pem ubuntu@DNS_name_of_the_EC2_instance
3 — Setting up Ansible on a Mac
Install Ansible with Homebrew (but you could use pip as well).
brew install ansible
You will then want to create an ansible directory in /etc/:
In that ansible directory:
Create a basic config file (ansible.cfg) that allows you to specify some parameters, such as the path to the private key (instead of having to type it while launching the playbook) and the remote user on the remote server.
[defaults]private_key_file=path_to_my_key/my_key.pemremote_user = ubuntu
You also need to create a hosts file with the Public IP of the server:
It should now be possible to ping the remote host if you execute the following command in a terminal.
ansible all -m ping
4 — Creating the Playbook
This was a lot of trial and error. The first step: create a playbook with the .yml extension.
Full content of the file here:
This does the following:
- Installs Nginx
- Upload 2 files to the folder where Nginx serves the static site (in the current user’s Documents folder in that example)
- Modify the default Nginx config file to add an /images endpoint (probably not the best solution there)
- Upload an image to that images folder
I created tasks one by one and gave it a go with the following command:
If all goes well, you should see no errors and could then open the below link in your browser.
You should see your index page there and your image if you do: