Setting up a web server with terraform part 2
In the previous section, we created our AWS keypair now we would attach it to our instance.
Once we have a key pair the next thing is to create a security group. According to aws definition of security group , A security group acts as a virtual firewall that controls the traffic for one or more instances. When you launch an instance, you can specify one or more security groups; otherwise, we use the default security group.
To do that we can add this block of codes to terraform, what this does is that it allows all tcp traffic from only our IP address and can allow all outgoing connection from the instance to any ip address. To get your public IP address just type this in the terminal curl ipconfig.co
Create a new file called sg.tf
To set up the Nginx Webserver create a file called myuserdata.tpl and paste this shell script
This is just a simple shell script that does two things update your repo list and install nginx webserver
#!/bin/bash
sudo apt-get update -y
sudo apt-get install nginx -y
In the ec2.tf add this block of code below so we can fetch our user data template and let AWS run it at launch time.
This is calling a data resource called template_file and we assigned the resource name myuserdata
The location of the file is “path.cwd” which is current working directory/filename with the extension tpl. Terraform would load this file up and parse it as an ec2 user data. You can also use cloud-init but for the sake of simplicity let us use user data.
After this, we can launch our ec2 instance with an Nginx web server running on it.
Lastly, we would need to get the public ip address of our instance using the output variable here is a definition from terraform about output variables
When building potentially complex infrastructure, Terraform stores hundreds or thousands of attribute values for all your resources. But as a user of Terraform, you may only be interested in a few values of importance, such as a load balancer IP, VPN address, etc.
Outputs are a way to tell Terraform what data is important. This data is outputted when apply is called, and can be queried using the terraform output command.
create a file called outputs.tf and paste this here
run
terraform init
terraform plan
terraform apply
We have our web server up and running here.
Don’t forget to do a terraform destroy so you can destroy the infrastructure you just created if you don’t need them anymore.
terraform destroy
You can get the whole source codes here terraform-aws-ec2-nginx