AWS Web and MariaDB on EC2 in one terraform template

This is an example of a terraform template to create the network infrastructure and nodes for a public facing Web server accessing an EC2 MySQL database in a private subnet.

The main point of this exercise was to prove the template would work before converting the template to use modules.

The cost of this infrastructure is measured in single dollars

The “.txt” files listed may need to be converted using either an editor or “dos2unix” if the newline format is incorrect.

e.g. using vi enter

“s/VM//g”

keys

Add the entry

key_name = “devopsdba2

to your secrets file “SECRET_variables.auto.tfvars”

GIT

All the following operations have been completed on a Centos VM.

If the following git repository hasn’t been download already then execute the following:

$ cd ~/git  
$ git clone https://github.com/paulhhallam/AWS-Web-and-EC2-MySQL-db-in-one-terraform-template.git
$cd AWS-Web-and-EC2-MySQL-db-in-one-terraform-templat

Terraform

The files in this terraform configuration are :

Dev2Main.tf    Main instriuctions
output.tf List of outputs
secret.tf Secret variables
vars.tf Defines lots of variables
README.md
database.txt Instructions to install and set up the mysql database
webphpapp.txt Instructions to install and set up the web server

Issues

Any issues can be investigated by checking the log files on the instances at /var/log e.g.

  • /var/log/cloud-init.log
  • /var/log/yum.log

Note

For simplicity I have hardcoded certain values but these can obviously be changed to secrets, environment variables or entered on the terraform command lines.

The MariaDB user and password is hardcoded in Dev2Main.tf

If you use these scripts please remember to change these values.

Terraform

The terraform commands to run the scripts are:

terraform init   -var-file=".auto.tfvars"
terraform apply  -var-file=".auto.tfvars"
terraform delete -var-file=".auto.tfvars"

where the contents of the file .auto.tfvars is similar to the following: MySecretKeys.auto.tfvars

  • access_key = “
  • secret_key = “
  • key_name = “EC2 key pair resource name>

Test

Please note that due to the OS updates and installations involved the availability of the web server and database may actually take over 10 minutes after the terraform script has completed.

Once created the infrastructure can be tested by accessing the web pages:

http:///
This will present the Apache HTTP Server Test Page

http:///mydb2.php
This will present the PHP info page for the phpapp EC2 instance

http:///mydb.php
This will present the result of a query against the Mariadb database on the second EC2 instance.
Please be patient as it can take over 5 minutes for the yum update, patching and database setup to complete before the page is available.

The page just displays the text "Mycol: MyValues" and nothing else.