Monday, 11 May 2026

Add ssh key on AWS EC2 Instance

 

Step 1: Apne system par SSH key generate karo (agar pehle se nahi hai)

Linux/macOS/Git Bash:

ssh-keygen -t ed25519 -C "my-laptop"
--

Ya RSA:

ssh-keygen -t rsa -b 4096

Step 2: Existing .pem se EC2 me login karo

ssh -i mykey.pem ec2-user@YOUR_EC2_IP

Step 3: Public key ko instance me add karo

Apne local system par ye command chalao:

cat ~/.ssh/id_ed25519.pub

Jo output aaye usko copy karo.


Step 4: EC2 instance me authorized_keys file me add karo

Instance ke andar:

mkdir -p ~/.ssh #This line for first time and first key add kar rhe ho to run karna hai
nano ~/.ssh/authorized_keys

Last line me copied public key paste karo.

Save:

  • CTRL + O
  • Enter
  • CTRL + X

Step 5: Permissions sahi karo, and run these on server(login server)

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

Step 6: New key se test karo, on local

Ab dusre terminal me:

ssh -i ~/.ssh/id_ed25519 ec2-user@YOUR_EC2_IP

Step 6: Agar aap deploy user ke liye key setup kar rahe ho, to instance me login karke ye run karo:

sudo chmod 700 /home/deploy/.ssh
sudo chmod 600 /home/deploy/.ssh/authorized_keys
sudo chown -R deploy:deploy /home/deploy/.ssh


Step 8: Finally added keys on EC2 Instance

Step 8.1 ssh -i ~/.ssh/id_rsa.pub ec2-user@SERVER_IP
---------------------------------------------------------

Alternative (single command)

Direct append bhi kar sakte ho:

cat ~/.ssh/id_ed25519.pub | ssh -i mykey.pem ubuntu@YOUR_EC2_IP "cat >> ~/.ssh/authorized_keys"


Thursday, 19 March 2026

Add DNS on AWS For (Subdomain)

 1. Login AWS

2. Goes in to LightSail: https://lightsail.aws.amazon.com/ls/webapp/home

3. click from left side menu: Domains & DNS

4. Then select DNS Zone >> select DNS Record

5. Then +Add record

6. And Enter the "Record Name (Record name)" and Save

Wednesday, 18 March 2026

Create Image on AWS for kamal deployment (Repositories)

 1. Goes to Amazon ECR >> Private registry >> Repositories

2. Create new 
Repositories 

    A. Enter the `Namespace/repo-name`

    B. Image Tag setting Choose is `Mutable`

    C. Encryption configuration >> `AES-256`

3. Then Create

4. https://us-east-2.console.aws.amazon.com/ecr/private-registry/repositories?region=us-east-2


5. Then use this `Namespace` image on deploy.yml for kamal


Sunday, 20 April 2025

all ec2 instance pg as remote access(EC2)

Is Blog se local se server per data create kar sakte hai.

1. On each EC2 instance, edit the PostgreSQL configuration file

1.1 sudo nano /etc/postgresql/<version>/main/postgresql.conf

# or for Amazon Linux

sudo nano /var/lib/pgsql/<version>/data/postgresql.conf

--

Update this line:

listen_addresses = '*' OR 
listen_addresses = '0.0.0.0'

---------------------------------------------------------------

2. Edit pg_hba.conf to Allow Remote Connections

On each instance, edit the pg_hba.conf file:

sudo nano /etc/postgresql/<version>/main/pg_hba.conf # or sudo nano /var/lib/pgsql/<version>/data/pg_hba.conf

Add the following line at the end (replace CIDR with the IP or IP range you want to allow):

host all all 0.0.0.0/0 md5

-----------------------------------------------

3. Open Port 5432 in EC2 Security Groups(This is most important)

Go to AWS EC2 Console → Security Groups, and for each EC2 instance:

  1. Find the associated Security Group.

  2. Click Inbound rulesEdit inbound rulesAdd rule:

    • Type: PostgreSQL

    • Protocol: TCP

    • Port Range: 5432

    • Source: Custom → <Your IP>/32 (or 0.0.0.0/0 for all IPs, use with caution)

----------------------------------------------------

4. Restart PostgreSQL

After making changes:

sudo systemctl restart postgresql # or sudo service postgresql restart
---------------------------------

5. Connect Remotely

Now you can connect from your local machine using a PostgreSQL client:

psql -h IP -U user_name -d database_name

ec2-ip: Server Ip address

username: Server pg username

6. Update Database.yml file

default: &default adapter: postgresql encoding: unicode pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> username: <%= ENV["DATABASE_USERNAME"] %> password: <%= ENV["DATABASE_PASSWORD"] %> database: <%= ENV["DATABASE_NAME"] %> host: <%= ENV["DATABASE_HOST"] %> development: <<: *default staging: <<: *default test: <<: *default production: <<: *default


Application.yml file

development:

  DATABASE_NAME: "database_name" # This is server database name

  DATABASE_HOST: "IP"

  DATABASE_USERNAME: "Server pg username"

  DATABASE_PASSWORD: "Server pg password"

Thursday, 10 April 2025

Sidekiq restart with new updation(like: update time, add new job(worker))

 1. ps aux | grep sidekiq

Get output: ubuntu    1111111  0.0  0.0   7008  2432 pts/0    S+   10:28   0:00 grep --color=auto sidekiq

2. kill -9 1111111

3. bundle exec sidekiq -d -L log/sidekiq.log

4. sudo service redis-server restart

5. sudo systemctl restart sidekiq

Wednesday, 26 February 2025

Send attachment with mail in rails and active storage

 Routes: 

post "/send_email_with_attachment", to: "articles#send_email_with_attachment"

-----------------------------------

Controller:

class ArticlesController < ApplicationController

  def send_email_with_attachment

    email = "arvind@gmail.com"

    attachment = params[:attachment]

    # Save the file temporarily

    file_path = Rails.root.join('tmp', attachment.original_filename)

    File.open(file_path, 'wb') do |file|

      file.write(attachment.read)

    end

    MyMailer.send_email_with_attachment(email, file_path).deliver_now

    # Delete the temporary file after sending the email

    File.delete(file_path) if File.exist?(file_path)

    redirect_to root_path, notice: 'Email sent successfully'

  end

end


--------------------------

Mailer

class MyMailer < ApplicationMailer

  def send_email_with_attachment(email, attachment_path)

    @greeting = "Hi"

    attachments[File.basename(attachment_path)] = File.read(attachment_path)

    mail(to: email, subject: 'Email with Attachment')

  end

end

-------------------------------

View
Form view:

<%= form_tag "/send_email_with_attachment", class: "inline-form", multipart: true do %>
  <%= file_field_tag :attachment %>
  <%= submit_tag 'Send Email' %>
<% end %>

Mailer view:

<h1>My#send_email_with_attachment</h1>

<p>
  <%= @greeting %>, find me in app/views/my_mailer/send_email_with_attachment.html.erb
</p>

----------------------------

Development.rb

config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_options = {from: 'localhost:3000'}
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address:              'smtp.gmail.com',
    port:                 587,
    domain:               'localhost',
    user_name:            ENV["SMTP_EMAIL"],
    password:             ENV["SMTP_PASSWORD"],
    authentication:       'plain',
    enable_starttls_auto: true
  }

=======================================
With Active storage and with html override

class AnnouncementMailer < ApplicationMailer

  def announcement_created(user, announcement)
    @user = user
    @announcement = announcement
    @association = announcement.custom_association

    # subject = "📢 New Announcement from #{@association.name}"
    subject = "📢 #{announcement.subject}"

    @announcement.announcement_attachments.each do |attachment|
      # next unless attachment.attached? #user this for has_one_attached :announcement_attachment

      # Optional size limit (10MB)
      # next if attachment.byte_size > 10.megabytes

      attachments[attachment.filename.to_s] = {
        mime_type: attachment.content_type,
        content: attachment.download
      }
    rescue StandardError => e
      Rails.logger.info "**********Announcement attachment skipped: #{e.message}"
    end

    template_path = Rails.root.join(
      "app", "views", "announcement_mailer", "announcement_created.html.erb"
    )
    erb_template = File.read(template_path)
    html_body = ERB.new(erb_template).result(binding)
    plain_text = ActionView::Base.full_sanitizer.sanitize(html_body)
    Notification.create(user_id: @user.id, notifiable: announcement, title: subject, message: plain_text, delivery_methods: ["email", "portal"], created_by: announcement.user_id, updated_by: announcement.user_id)
    mail(
      to: @user.email,
      subject: subject,
    ) do |format|
      format.html { render html: html_body.html_safe }
    end
  end
end




Public bucket on AWS s3

 Please visite: https://alex-okorkov.medium.com/how-to-set-up-aws-s3-bucket-on-rails-with-activestorage-d384075ce773

--------------------


Code:

{

    "Version": "2012-10-17",

    "Statement": [

        {

            "Effect": "Allow",

            "Principal": "*",

            "Action": "s3:ListBucket",

            "Resource": "arn:aws:s3:::bucket-name"

        },

        {

            "Effect": "Allow",

            "Principal": "*",

            "Action": [

                "s3:PutObject",

                "s3:GetObject",

                "s3:DeleteObject"

            ],

            "Resource": "arn:aws:s3:::bucket-name/*"

        }

    ]

}