Skip to content

Commit

Permalink
update(tutorial): updated Terraform and Dockerfiles
Browse files Browse the repository at this point in the history
  • Loading branch information
jlecomte committed Mar 15, 2024
1 parent 58cdfd2 commit c50210f
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 107 deletions.
29 changes: 15 additions & 14 deletions mnq/sns-instances-notification-system/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# SNS Instances Notification System

This repository contains the source code for the this tutorial: [Creating a notification system with Scaleway SNS and Instances.](https://github.com/scaleway/docs-content/blob/int-add-mnq-tuto/tutorials/sns-instances-notification-system/index.mdx)
This repository contains the source code for the this tutorial: [Creating a notification system with Scaleway SNS and Instances.](https://www.scaleway.com/en/docs/tutorials/sns-instances-notification-system)

## Requirements

Expand All @@ -16,25 +16,26 @@ This example shows you how to set up a Notification System with Terraform across

## Setup

Once you have cloned this repository you can run:
Once you have cloned this repository, export your public SSH key to a `TF_VAR_public_ssh_key` environement variable:

```
export TF_VAR_public_ssh_key=$(cat ~/.ssh/id_ed25519.pub)
```

Then you can run these commands:

```console
terraform init
terraform plan
terraform apply
```
You will be prompted to enter your public ssh. You will find them in the `~/.ssh/` folder:

```console
cat ~/.ssh/*.pub
```

## Testing

Connect to the subscriber Instance with this URL ```http://<your_subscriber_ip_address>:8081``` (you can find the address on the Console Instances page)
Click on `Confirm subscription`. If you have an error because the URL hasn't been received, you can reload the page. You will see a AWS xml page.
Go back to the home page, and click on `Notifications`. The notifications received will be displayed here.
Then connect to the publisher Instance with that URL ```http://<your_subscriber_ip_address>:8081```
Go to the home page of your publisher server: ```http://<your_publisher_ip_address>:8081```
Click on a CPU behavior, and check the notification page of your subscriber server. A notification about the behavior should have appeared.
Once you're done testing, you can apply `terraform destroy` to clean and remove the project.
- Connect to the subscriber Instance with this URL ```http://<your_subscriber_ip_address>:8081``` (you can find the address on the Console Instances page)
- Click on `Confirm subscription`. If you get an error because the URL hasn't been received, you can reload the page, it should take less than 30s to appear. You will see a AWS xml page.
- Go back to the home page, and click on `Notifications`. The notifications received will be displayed here.
- Then connect to the publisher Instance with that URL ```http://<your_subscriber_ip_address>:8081```
- Go to the home page of your publisher server: ```http://<your_publisher_ip_address>:8081```
- Click on a CPU behavior, and check the notification page of your subscriber server. A notification about the behavior should have appeared.
- Once you're done testing, you can apply `terraform destroy` to clean and remove the project.
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
FROM debian:bookworm-20240211
LABEL authors="[email protected]"

RUN apt-get update && \
apt-get install -y golang ca-certificates && \
Expand All @@ -13,10 +12,9 @@ COPY ./internal ./internal
COPY ./www ./www

RUN go mod init publisher-server && \
go mod tidy
go mod tidy && \
go build ./cmd/publisher

EXPOSE 8081

WORKDIR /app/cmd/publisher

CMD ["go", "run", "main.go"]
CMD ["./publisher"]
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ func main() {
sns_client.InitAwsSnsClient()

router := gin.Default()
router.LoadHTMLGlob("../../www/templates/*")
router.Static("/", "../../www")
router.LoadHTMLGlob("./www/templates/*")
router.Static("/", "./www")
router.POST("/low-CPU-usage", handlers.LowCPUUsageHandler)
router.POST("/high-CPU-usage", handlers.HighCPUUsageHandler)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
FROM debian:bookworm-20240211
LABEL authors="[email protected]"

RUN apt-get update && \
apt-get install -y golang ca-certificates && \
Expand All @@ -13,10 +12,9 @@ COPY ./internal ./internal
COPY ./www ./www

RUN go mod init subscriber-server && \
go mod tidy
go mod tidy && \
go build -o ./subscriber ./cmd/subscriber

EXPOSE 8081

WORKDIR /app/cmd/subscriber

CMD ["go", "run", "main.go"]
CMD ["./subscriber"]
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package main

import (
"fmt"
"github.com/gin-gonic/gin"
"subscriber-server/internal/handlers"

"github.com/gin-gonic/gin"
)

func main() {
router := gin.Default()

router.LoadHTMLGlob("../../www/templates/*")
router.LoadHTMLGlob("./www/templates/*")

router.GET("/", handlers.GetIndexHandler)
router.GET("/confirm-subscription", handlers.ConfirmSubscriptionHandler)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package handlers

import (
"github.com/gin-gonic/gin"
"net/http"

"github.com/gin-gonic/gin"
)

func NoRouteHandler(context *gin.Context) {
Expand All @@ -13,5 +14,5 @@ func NoRouteHandler(context *gin.Context) {
}

func GetIndexHandler(context *gin.Context) {
context.File("../../www/index.html")
}
context.File("./www/index.html")
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,41 +69,6 @@
transform: translateY(1px);
}
</style>

<!-- <script>-->
<!-- // document.addEventListener('DOMContentLoaded', function() {-->
<!-- // const fetchNotifications = () => {-->
<!-- // fetch('/notifications', {-->
<!-- // method: 'GET',-->
<!-- // headers: {-->
<!-- // 'X-Requested-With': 'XMLHttpRequest'-->
<!-- // 'Accept': 'application/json'-->
<!-- // }-->
<!-- // })-->
<!-- // .then(response => {-->
<!-- // console.log('Received response', response); // Log response object-->
<!-- // return response.json(); // Parse JSON from response-->
<!-- // })-->
<!-- // .then(data => {-->
<!-- // if (data.newNotifications) {-->
<!-- // alert("New notification received!");-->
<!-- // // Update the DOM with new notifications here-->
<!-- // const notificationsList = document.getElementById('notificationsList');-->
<!-- // notificationsList.innerHTML = ''; // Clear existing notifications-->
<!-- // data.notifications.forEach(notification => {-->
<!-- // const listItem = document.createElement('li');-->
<!-- // listItem.textContent = notification;-->
<!-- // notificationsList.appendChild(listItem);-->
<!-- // });-->
<!-- // }-->
<!-- // })-->
<!-- // .catch(error => console.error('Error fetching notifications:', error));-->
<!-- // };-->
<!-- //-->
<!-- // // Fetch notifications every 5 seconds-->
<!-- // setInterval(fetchNotifications, 5000);-->
<!-- // });-->
<!-- </script>-->
</head>
<body>

Expand All @@ -122,11 +87,9 @@ <h1>Subscriber Server - Notifications</h1>
}

function reload(){
console.log("Refreshed"); // Optional: for debugging
fetch('/notifications-refresh', { method: 'GET' })
.then(response => response.json())
.then(res => {
console.log(res);
document.getElementById("notificationsList").innerHTML = jsonNotificationToHtmlNotification(res.notifications);
})
.catch(error => console.error('Error:', error));
Expand Down
78 changes: 39 additions & 39 deletions mnq/sns-instances-notification-system/terraform/main.tf
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
terraform {
# CONNECTS TO SCALEWAY CLOUD PROVIDER
# Connects to Scaleway cloud provider
required_providers {
scaleway = {
source = "scaleway/scaleway"
Expand All @@ -11,31 +11,31 @@ terraform {
provider "scaleway" {
}

# CREATE PROJECT SNS-TUTORIAL
# Creates Project sns_tutorial
resource "scaleway_account_project" "sns_tutorial" {
name = "sns-tutorial"
}

# TAKES YOUR PUBLIC SSH-KEY TO ACCESS INSTANCES
# Takes your public SSH-key to access Instances
resource "scaleway_iam_ssh_key" "main" {
name = "sns-tutorial-public-ssh-key"
name = "sns-tutorial-public-ssh-key"
project_id = scaleway_account_project.sns_tutorial.id
public_key = var.public_ssh_key
}

# ===================== SNS =====================

# ACTIVATE SNS
# Activates SNS
resource "scaleway_mnq_sns" "main" {
project_id = scaleway_account_project.sns_tutorial.id
region = "fr-par"
region = "fr-par"
}

# CREATE CREDENTIALS
# Creates credentials
resource "scaleway_mnq_sns_credentials" "main" {
project_id = scaleway_account_project.sns_tutorial.id
permissions {
can_manage = true // to set up the topic subject, the subscription to the topic
can_manage = true // to set up the topic subject, the subscription to the topic
can_receive = true // to subscribe a topic
can_publish = true // to publish messages to the topic
}
Expand All @@ -46,50 +46,50 @@ resource "scaleway_mnq_sns_credentials" "main" {
]
}

# CREATE TOPIC
# Creates topic
resource "scaleway_mnq_sns_topic" "topic" {
project_id = scaleway_account_project.sns_tutorial.id
name = "sns-tutorial-topic"
name = "sns-tutorial-topic"
access_key = scaleway_mnq_sns_credentials.main.access_key
secret_key = scaleway_mnq_sns_credentials.main.secret_key
}

# ========== INSTANCES SECURITY GROUP ===========

resource "scaleway_instance_security_group" "sns_www" {
project_id = scaleway_account_project.sns_tutorial.id
project_id = scaleway_account_project.sns_tutorial.id
inbound_default_policy = "drop"
outbound_default_policy = "accept"

# FOR SSH CONNEXIONS
# For SSH connections
inbound_rule {
action = "accept"
port = "22"
port = "22"
}

# FOR HTTP CONNEXIONS
# For HTTP connections
inbound_rule {
action = "accept"
port = "8081"
port = "8081"
}
}

# ============= SUBSCRIBER SERVER ===============

resource "scaleway_instance_ip" "subscriber_public_ip" {
project_id = scaleway_account_project.sns_tutorial.id
zone = "fr-par-1"
zone = "fr-par-1"
}

resource "scaleway_instance_server" "subscriber_sns_tuto_instance" {
project_id = scaleway_account_project.sns_tutorial.id
name = "suscriber-server"
type = "PLAY2-PICO"
image = "debian_bookworm"
ip_id = scaleway_instance_ip.subscriber_public_ip.id
security_group_id= scaleway_instance_security_group.sns_www.id

# USER DATA TO RUN THE SERVER AT START-UP
project_id = scaleway_account_project.sns_tutorial.id
name = "suscriber-server"
type = "PLAY2-PICO"
image = "debian_bookworm"
ip_id = scaleway_instance_ip.subscriber_public_ip.id
security_group_id = scaleway_instance_security_group.sns_www.id

# User_data to run the server at start-up
user_data = {
cloud-init = <<-EOF
#cloud-config
Expand All @@ -107,7 +107,7 @@ resource "scaleway_instance_server" "subscriber_sns_tuto_instance" {
}
}

# TO WAIT FOR THE SUBSCRIBER PORT 8081 TO BE OPENED TO CONTINUE
# Waits for the subscriber port 8081 to be opened before moving on
resource "terraform_data" "bootstrap" {
triggers_replace = [
scaleway_instance_server.subscriber_sns_tuto_instance.id,
Expand All @@ -128,32 +128,32 @@ resource "terraform_data" "bootstrap" {
}
}

# CREATE SNS TOPIC SUBSCRIPTION
resource scaleway_mnq_sns_topic_subscription main {
# Creates SNS topic subscription
resource "scaleway_mnq_sns_topic_subscription" "main" {
project_id = scaleway_account_project.sns_tutorial.id
access_key = scaleway_mnq_sns_credentials.main.access_key
secret_key = scaleway_mnq_sns_credentials.main.secret_key
topic_id = scaleway_mnq_sns_topic.topic.id
protocol = "http"
endpoint = "http://${scaleway_instance_ip.subscriber_public_ip.address}:8081/notifications"
topic_id = scaleway_mnq_sns_topic.topic.id
protocol = "http"
endpoint = "http://${scaleway_instance_ip.subscriber_public_ip.address}:8081/notifications"
}

# ================= PUBLISHER SERVER =================

resource "scaleway_instance_ip" "publisher_public_ip" {
project_id = scaleway_account_project.sns_tutorial.id
zone = "fr-par-1"
zone = "fr-par-1"
}

resource "scaleway_instance_server" "publisher_sns_tuto_instance" {
project_id = scaleway_account_project.sns_tutorial.id
name = "publisher-server"
type = "PLAY2-PICO"
image = "debian_bookworm"
ip_id = scaleway_instance_ip.publisher_public_ip.id
security_group_id= scaleway_instance_security_group.sns_www.id

# USER DATA TO RUN THE SERVER AT START-UP
project_id = scaleway_account_project.sns_tutorial.id
name = "publisher-server"
type = "PLAY2-PICO"
image = "debian_bookworm"
ip_id = scaleway_instance_ip.publisher_public_ip.id
security_group_id = scaleway_instance_security_group.sns_www.id

# User_data to run the server at start-up
user_data = {
cloud-init = <<-EOF
#cloud-config
Expand Down

0 comments on commit c50210f

Please sign in to comment.