Replication Set on Kubernetes using Terraform
In this example we will be creating two replication sets which will launch two Kubernetes pods for us.
First pod will be acting as a MySQL database which will store all the data coming from our seconds pod which will act as a wordpress application. This task can be performed using single Terraform code.
Let's start the minikube server and check if no pods are running,
>> minikube start
>> kubectl get all
Let's create the code now,
provider "kubernetes" {
config_context_cluster = "minikube"
}
Then, run
>> terraform init
Let's now write the remaining code....
###################### MYSQL DATABASE ###########################
resource "kubernetes_deployment" "mysql" {
metadata {
name = "sqldb"
}
spec {
replicas = 1
selector {
match_expressions {
key = "env"
operator = "In"
values = [ "dev" ]
}
}
template {
metadata {
name = "mypod1"
labels = {
env = "dev"
dc = "IN"
app = "database"
}
}
spec {
container {
name = "sqlcon"
image = "mysql:5.6"
env {
name = "MYSQL_ROOT_PASSWORD"
value = "*******"
}
env {
name = "MYSQL_DATABASE"
value = "wpdatabase"
}
env {
name = "MYSQL_USER"
value = "gaurav"
}
env {
name = "MYSQL_PASSWORD"
value = "********"
}
}
}
}
}
}
#################################################################
###################### WORDPRESS APPLICATION ####################
resource "kubernetes_deployment" "wordpress" {
metadata {
name = "wpapp"
}
spec {
replicas = 1
selector {
match_expressions {
key = "env"
operator = "In"
values = [ "dev" ]
}
}
template {
metadata {
name = "mypod1"
labels = {
env = "dev"
dc = "IN"
app = "web"
}
}
spec {
container {
name = "wpcon"
image = "wordpress:4.8-apache"
}
}
}
}
}
The code is complete and we can launch our complete architecture using a command with the help of terraform.
>> terraform apple --auto-approve
Now, let's check if our pods are running or not
>> kubectl get pods
But how do we know if the replica set is created or not ?
There is a kubectl command to check that as well
>> kubectl get rs
As we can see that our architecture is created be just one command, but we need to expose our wordpress pod to access our application from our browser.
>> kubectl expose pods <pod_name> --port=80 --type=NodePort
Run the following command to know to what port our application is being exposed to .
>> kubectl get all
As we can see that our wordpress pod is exposed to port-no: 31166.
Let's see how our application looks like,
It's working completely fine.
It was a great use case of integrating Kubernetes with Terraform.
Also the complete architecture can be destroyed just by a single command.
>> terraform destroy --auto-approve
This task is a part of my "Hybrid Multi Cloud Training" under the mentorship of Mr. Vimal Daga sir.
Thank you all for reading the article.