Terraform Digital Ocean Script

Setup Terraform in Windows (AMD64)
Download Terraform for Windows (AMD64) from
Unzip the file to a directory
Add the Terraform binary to your system's PATH:
Right-click This PCSettingsAdvanced system settingsEnvironment Variables.
Under User variables for Unity_0116, find the Path variable, and click Edit.
Click New, and add the path to the directory where you unzipped Terraform.
Press OK to save the changes.
terraform —version (Terraform version command)
Screenshot 2024-09-18 181914.png

Create API Tokens in Digital Ocean
Go to and log in to your account.
Generate a New Token
Name the Token
Expiration :- 30/60/90 days and No Expir
Set Permissions :- full access
Screenshot 2024-09-18 171244.png


Create API Tokens in GitHub
Access Personal Access Tokens:
Click on your profile icon in the top-right corner.
Select Settings from the dropdown menu.
In the left sidebar, click on Developer settings.
Click on Personal access tokens.
Create a New Token
Click on Generate new token.
Enter a Token name to describe its purpose.
Choose an Expiration date or set it to No expiration if you prefer.
Set Permissions:
Under Repository access, select All repositories.
Scroll down to Repository permissions, and open the Contents row.
Select Read and Write from the menu.
Generate and Copy the Token

Screenshot 2024-09-18 173049.png

Create API Tokens for Cloudflare
Create a new API token:
Click "Create Token
Select the "Edit zone DNS" template or create a custom token with permissions for "Zone DNS"
Zone DNS" read and edit
Define the token's permissions:
Permissions: Select "Zone DNS" and set to "Read" and "Edit."
Zone Resources: Set to "Include All Zones" or specify the zones as needed.
Click "Continue to summary" and then "Create Token."

Screenshot 2024-09-18 173739.png

How to Retrieve the Cloudflare Zone ID

Log in to the .
Select your account and choose the domain for which you need the Zone ID.
On the Overview page (this is the default landing page when you select a domain), scroll down to find the API section.
In this section, you will find both the Zone ID and the Account ID.
Copy the Zone ID to use in your Terraform configuration or API calls.

Screenshot 2024-09-18 191053.png

Create SSH Key
ssh-keygen -t rsa
And Save Terraform File
file name :- id_rsa.pub
Terraform File
create a new Terraform file
create the .tf file

provider.tf (Terraform Provider Configuration for Digital Ocean and Cloudflare)
terraform {
required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 3.0" # Adjust the version as needed
}
digitalocean = {
source = "digitalocean/digitalocean"
version = "~> 2.0" # Adjust the version as needed
}
}
}

# Configure the DigitalOcean Provider
provider "digitalocean" {
token = var.do_token
}

# Configure the Cloudflare Provider
provider "cloudflare" {
api_token = var.cloudflare_token
}


terraform.tfvars (Enter API Tokens in Digital Ocean and Cloudflare )
# DigitalOcean API Token
do_token = "dop_v1_cd61e7b627830e2212033ceb47b6400e1f1ed981c896b88a3ca6fe5f541da5c4"

# Cloudflare API Token
cloudflare_token = "z2ah0j36vxc-nJ11_4qEbDCDLNJtGK8HE8rJ4wQj"


variables.tf
# Define the DigitalOcean API token variable
variable "do_token" {
description = "The API token for DigitalOcean"
type = string
}

# Define the Cloudflare API token variable
variable "cloudflare_token" {
description = "The API token for Cloudflare"
type = string
}





main.tf (Create Digital Ocean and Cloudflare Code )
# Define your SSH key for DigitalOcean
resource "digitalocean_ssh_key" "id_rsa" {
name = "id_rsa"
public_key = file("${path.module}/id_rsa.pub") # Ensure this is the correct path to the public key file
}

# Create the Droplet on DigitalOcean
resource "digitalocean_droplet" "nestjs_droplet" {
name = "sumit" # Droplet name
image = "ubuntu-22-04-x64" # Ubuntu 22.04 LTS image
region = "nyc3" # DigitalOcean region (NYC3 in this case)
size = "s-1vcpu-2gb" # Droplet size (1 vCPU, 2GB RAM)
backups = false # Disable backups (can be set to true if needed)
ipv6 = true # Enable IPv6 support
monitoring = true # Enable monitoring for the droplet
ssh_keys = [digitalocean_ssh_key.id_rsa.fingerprint] # Reference the SSH key

# Use cloud-init or a shell script for initial setup
user_data = file("${path.module}/betterbugs.sh") # Ensure this script is in the correct location
}

# Output the public IP of the droplet
output "droplet_ip" {
value = digitalocean_droplet.nestjs_droplet.ipv4_address
}

# Create an A record in Cloudflare pointing to the Droplet's public IP
resource "cloudflare_record" "example_a_record" {
zone_id = "3dd054264c1a06c8794306590a4205e2" # Cloudflare Zone ID
name = "api.sumitdevops.xyz" # DNS record name (subdomain)
value = digitalocean_droplet.nestjs_droplet.ipv4_address # Droplet's public IP address
type = "A" # A record
ttl = "1" # Time-to-live (TTL) value in seconds
proxied = true # Enable Cloudflare proxy (set to false if not needed)
}

# Output the DNS record details
output "cloudflare_dns_record" {
value = cloudflare_record.example_a_record
}

betterbugs.sh (Run Command in Better Bugs API, Git Clone, Redis, and Nginx Server Block Setup)
#!/bin/bash

# Define variables
REDIS_PASSWORD="Sumit@123"
GITHUB_USERNAME="sumit-linearloop"
GITHUB_TOKEN="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"
REPO_URL="https://$GITHUB_TOKEN@github.com/$GITHUB_USERNAME/digitalocean-api.git"
TARGET_DIR="/var/www/nestjs-app"

# Update and install dependencies
echo "Updating system and installing dependencies..."
apt-get update && apt-get upgrade -y
apt-get install nginx -y
apt-get install git -y
apt-get install curl -y
apt-get install redis-server -y

# Install nvm (Node Version Manager)
# Log everything to /root/startup-script.log
exec > >(tee -a /root/startup-script.log) 2>&1

# Install nvm (Node Version Manager)
echo "Installing NVM..."
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

# Load nvm in the current shell
source ~/.bashrc || source ~/.profile

# Verify nvm installation
echo "Verifying NVM installation..."
nvm -v || { echo "NVM not installed"; exit 1; }

# Install Node.js version 18 using nvm and set it as default
echo "Installing Node.js 18..."
nvm install 18
nvm use 18 || { echo "Node.js installation failed"; exit 1; }

# Install global npm packages
echo "Installing global npm packages (yarn, pm2)..."
npm install --global yarn pm2 || { echo "Global npm package installation failed"; exit 1; }

echo "Script completed successfully."


# Clone the GitHub repo
echo "Cloning repository from: $REPO_URL"
mkdir -p $TARGET_DIR && cd $TARGET_DIR
git clone --verbose $REPO_URL . || { echo "Git clone failed. Check your token or repository access."; exit 1; }

# Install dependencies and build the project
echo "Installing project dependencies with Yarn..."
yarn install || { echo "Yarn install failed"; exit 1; }
echo "Building the project with Yarn..."
yarn build || { echo "Yarn build failed"; exit 1; }

# Enable the PM2 service
echo "Configuring PM2 service for NestJS app..."
pm2 stop "nestjs-app" || echo "PM2 service not running"
pm2 delete "nestjs-app" || echo "No PM2 process to delete"
pm2 start /var/www/nestjs-app/dist/main.js --name "nestjs-app" -i 1 || { echo "PM2 start failed"; exit 1; }
pm2 save || { echo "PM2 save failed"; exit 1; }

# Set up NGINX for domain api.sumitdevops.xyz
echo "Configuring NGINX for domain api.sumitdevops.xyz..."
cat << 'EOF' > /etc/nginx/sites-available/api.sumitdevops.xyz
server {
listen 80;
server_name api.sumitdevops.xyz;

location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
EOF

# Enable the NGINX configuration
ln -s /etc/nginx/sites-available/api.sumitdevops.xyz /etc/nginx/sites-enabled/

# Restart NGINX to apply the new configuration
echo "Restarting NGINX..."
systemctl restart nginx || { echo "Nginx restart failed"; exit 1; }

# Check if NGINX is running correctly
systemctl status nginx || { echo "Nginx is not running"; exit 1; }

# --- Redis setup ---
echo "Configuring Redis..."

# Configure Redis to require a password
sed -i "s/# requirepass foobared/requirepass $REDIS_PASSWORD/" /etc/redis/redis.conf

# Restart Redis to apply the new configuration
systemctl restart redis-server || { echo "Redis restart failed"; exit 1; }

# Check Redis status
systemctl status redis-server || { echo "Redis is not running"; exit 1; }

# Verify Redis password setup by attempting a connection
redis-cli -a "$REDIS_PASSWORD" ping || { echo "Redis authentication failed"; exit 1; }

echo "Initialization script completed successfully"


Terraform Command
terraform init
This command initializes your Terraform working directory. It downloads the necessary provider plugins (like Digital Ocean, AWS, etc.) and sets up the environment to work with your configuration.
terraform plan
This command creates an execution plan, showing what actions Terraform will take to reach the desired state as defined in your configuration files.
terraform apply -auto-approve
This command applies the changes required to reach the desired state of the configuration. It provisions and manages your infrastructure according to your Terraform code.
terraform destroy -auto-approve ​This command destroys all infrastructure managed by your Terraform code. It deletes all resources, effectively tearing down everything that was previously created.

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.