2026-03-19 Deploy and Setting EC2 instances

From Izara Wiki
Revision as of 06:17, 1 May 2026 by Seagame (talk | contribs) (→‎Upload AMI to aws account)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Deploy EC2 Instance

  • EC2 instance types are purpose-built configurations of virtual servers, designed with different resource combinations to help your applications perform at their best.

Setting Ec2 on AWS

Create Key pairs

CreateKeyPairs.png

  • Enter key pair name you want
  • select key pair type to RSA
  • select Private key file format to .pem
  • When you created new key pair it will auto download file it will be used later

Create VPC

Sign in to aws account that want to create instance -> VPC -> Virtual private cloud -> your VPC

  • Create VPC if not exist

CreateVPCIfNotExist.png

  • Required: IPv4 CIDR // ex : 172.16.0.0/16
  • VCP exist

CreateVPCifExist.png

  • Note : can shared VPC for create another instance in same account

Screenshot from 2026-03-18 14-28-11.png

Create Subnet

CreateSubNet.png

  • Select VPC

Screenshot from 2026-03-18 14-55-26.png

  • enter subnet name and select Availability Zone then enter IPv4 subnet CIDR block when you finish first subnet click add new subnet and then repeat 3 subnet process
  • Availability Zone
    • Stage : Ohio >> (us-east-2a),(us-east-2b),(us-east-2c)
  • IPv4 subnet CIDR block
    • us-east-2a : 172.16.10.0/24
    • us-east-2b : 172.16.20.0/24
    • us-east-2c : 172.16.30.0/24

Create Internet Gateway

  • When you finish create internet gateway then back to internet gateways page
  • Attach with your VPC: select your internet gateway -> action -> Attach to VPC and then select your VPC

Create Route Table

CreateRouteTable.png

  • Select you VPC and then create route table
  • Select your route table -> action -> edit subnet associate and then select your subnet

SubnetAssociations.png

  • Connect internet gateway for protect config  : Select your route table >> edit route

EditRoute.png

  • Add route
  • Destination : 0.0.0.0/0
  • Target : Internet Gateway>> select your Igw from created

Create VPC Endpoint

Screenshot from 2026-03-18 15-32-04.png

  • Select Service:
    • com.amazonaws.us-east-2.s3
    • com.amazonaws.us-east-2.dynamodb

Select Type: Gateway >> VPC >> route table

    • com.amazonaws.us-east-2.sns
    • com.amazonaws.us-east-2.sqs
    • com.amazonaws.us-east-2.lambda

Select Type : Interface >> VPC >> route table >> subnet >> Security groups

  • Subnet settings

AddSubNet.png

  • Security groups

AddSequrityGroup.png

  • Note : Endpoint Type : Interface , can create those endpoint after created Security groups from deploy Resource EC2 finished

Resource Ec2 settings

  • in ResourceEC2/ ec2.yml
Parameters:

  ExistingVpcId:
    Type: AWS::EC2::VPC::Id
    Description: Use existing VPC
    Default: vpc-0ce9f21b10cb179f9

  SshKeyPairNeo4j:
    Description: SSH Keypair to login to the instance
    Type: AWS::EC2::KeyPair::KeyName
    Default: ${self:custom.iz_DefaultKeyPairName} # name to config same imageId


Resources:

  Neo4jSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Neo4j Security Group shared
      GroupName: share-neo4j-shared
      SecurityGroupIngress:
        # - CidrIp: 0.0.0.0/0 # set to all traffic for send msg to sns
        #   IpProtocol: "-1"
        - IpProtocol: tcp
          FromPort: 22 # SSH
          ToPort: 22
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 7687 # private neo4j port
          ToPort: 7687
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 7474 #  public neo4j port: neo4j
          ToPort: 7474
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 7473 # #  public neo4j port: Bolt
          ToPort: 7473
          CidrIp: 0.0.0.0/0
      SecurityGroupEgress:
        - CidrIp: 0.0.0.0/0 # set all traffic
          IpProtocol: "-1"
      # VpcId: !Ref VPC
      VpcId: !Ref ExistingVpcId


  # create neo4j instance
  Neo4jShared:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ${self:custom.iz_ImageId}
      # InstanceInitiatedShutdownBehavior: stop # default
      InstanceType: t2.medium
      SecurityGroupIds:
        - !Ref Neo4jSecurityGroup
      KeyName: !Ref 'SshKeyPairNeo4j' # NOTE: require existing keypair, please make sure have private key in local.
      SubnetId: ${self:custom.iz_subnetIds1a}

  ## Elastic IP: neo4j instance public IP address will not chabge everytime we stop/start instance(NOT security)
  EIP:
    Type: AWS::EC2::EIP
    Properties:
      InstanceId: !Ref Neo4jShared

Note: Security Group section after deploy if has config between lambda endpoint not send message out… should add setting inbound rules:

  • Type:HTTPS>>TPC>>443>>172.16.0.0/16

AddSettingSequrityGroup.png

Install Neo4j in terminal

After EC2 instance was created: ** must have ec2 instance existing **

Install neo4j using .tar

  • ssh EC2 instance: in Terminal
# set permission of key
chmod 400 <your keys pairs> // ex. GraphHandler-ver-05.pem

# connect ec2 instance by SSH command
ssh -i "your-key.pem" ec2-user@<public-ip> -L 7687:<private-ip>:7687

# Install java: 
sudo yum install java-17-amazon-corretto -y  // neo4j version-5 use java version more than version 11

# Download and extract neo4j
wget https://neo4j.com/artifact.php?name=neo4j-community-5.20.0-unix.tar.gz

tar -xzf neo4j.tar.gz

mv neo4j-community-* neo4j

cd neo4j

# Configure Neo4j bash
nano conf/neo4j.conf

Then Add this into file:

server.default_listen_address=0.0.0.0
server.default_advertised_address=<your-ec2-private-ip or public-ip>
server.bolt.listen_address=:7687
server.http.listen_address=:7474

#Setting start on reboot bash 
bin/neo4j stop

sudo nano /etc/systemd/system/neo4j.service

Add this code in file: 
[Unit]
Description=Neo4j Graph Database
After=network.target

[Service]
Type=forking
User=ec2-user
WorkingDirectory=/home/ec2-user/neo4j
ExecStart=/home/ec2-user/neo4j/bin/neo4j start
ExecStop=/home/ec2-user/neo4j/bin/neo4j stop
Restart=on-failure
RemainAfterExit=true
Environment=NEO4J_HOME=/home/ec2-user/neo4j
Environment=JAVA_HOME=/usr/lib/jvm/java-17-amazon-corretto

[Install]
WantedBy=multi-user.target

# set neo4j password
bin/neo4j-admin dbms set-initial-password NewPassword123 // < your password>

# Then
bin/neo4j start

Note: If use AMIs exist from another account neo4j browser/backend database will be use old password from that AMIs

  • If want to change password with new EC2 instance after install neo4j package
#bash: 
sudo systemctl stop neo4j
rm -rf data/dbms/*
rm -rf data/databases/system
rm -rf data/transactions/system
bin/neo4j-admin dbms set-initial-password neo4jComAcc
sudo systemctl start neo4j

Connect Neo4j Browser

 neo4j:// public -ip:7687
 Username: neo4j
 Password : xxxxxx

Stop and start EC2 instances automatically

Schedules Instance using AWS EventBridge

  • Step1: Specify schedule detail
  • Go to Amazon EventBridge >> Schedules → Create Schedules

Step1CreateSpecifyTagEvenBridge.png

  • Schedule pattern:
  • Occurrence → Recurring schedule
  • Time zone: → asia/Bangkok
  • Schedule type → Cron-based schedule

CronExpression.png

  • Note: monday to saturday stop instance on 18:00 / 6:00PM
  • Flexible time window : off → next page
  • Step2 : Select target

EventBridgeTargetDetial.png

  • Amazon EC2 → StopInstances then push Instance Id into JSON format → next page
  • Step3 : Settings
  • Schedule state : enable
  • Action after schedule completion : NONE
  • Retry policy and dead-letter queue (DLQ) : NONE
  • Set Permissions: → Go to IAM console to create role permission then select an existing role after created finished
  • IAM → Roles → Create roles
    • Custom trust policy:
{
   "Version": "2012-10-17",
   "Statement": [
       {
           "Effect": "Allow",
           "Principal": {
               "Service": "scheduler.amazonaws.com"
           },
           "Action": "sts:AssumeRole"
       }
   ]
}
  • Add Permission : if permission for stop Instance not exist , have to create before or skip this step then add those permission later
{
   "Version": "2012-10-17",
   "Statement": [
       {
           "Sid": "VisualEditor0",
           "Effect": "Allow",
           "Action": "ec2:StopInstances",
           "Resource": "arn:aws:ec2:us-east-2:418867772665:instance/i-0569d4b408c5a75db"
       }
   ]
}

Note: "Resource": "arn:aws:ec2:us-east-2:<Account-Id>:instance/<instanceIds>"

  • Name, review, and create : create roles name

Step4 : Review and create schedule

  • Check detail the create schedule

// wait for image

Idea: Stop and start Instance using Systems Manager

  • Go to AWS → Systems Manager
  • In the left menu click → Quick Setup
  • Get started with Quick Setup → Get started
  • Choose Configuration Type
  • 👉 Resource Scheduler (Powered by AWS Solutions) → Create
  • Specify instance tag :
    • Key : Value >> should set key & value like those instance want to set Auto Scheduler
    • go to EC2 Console → Instances
    • Select your specific instance
    • Click Tags → Manage tags → Add tag
  • Target
    • Choose : current account and current region
    • Local deployment roles : Use new IAM local deployment roles

Download and Upload AMIs on EC2

Download AMI from aws account

  • Create vmimport Role
{
 "Version": "2012-10-17",
 "Statement": [
   {
     "Effect": "Allow",
     "Principal": {
       "Service": "vmie.amazonaws.com"
     },
     "Action": "sts:AssumeRole",
     "Condition": {}
   }
 ]
}
  • Permissions in vmImportPolicy
{
 "Version": "2012-10-17",
 "Statement": [
   {
     "Effect": "Allow",
     "Action": [
       "s3:GetBucketLocation",
       "s3:GetObject",
       "s3:ListBucket"
     ],
     "Resource": [
       "arn:aws:s3:::object-schema", 
       "arn:aws:s3:::object-schema/*"
     ]
   },
   {
     "Effect": "Allow",
     "Action": [
       "s3:PutObject"
     ],
     "Resource": "arn:aws:s3:::object-schema/*"
   },
   {
     "Effect": "Allow",
     "Action": [
       "ec2:ModifySnapshotAttribute",
       "ec2:CopySnapshot",
       "ec2:RegisterImage",
       "ec2:Describe*"
     ],
     "Resource": "*"
   }
 ]
}
  • Create Role Permission
    • can create from EC2 instance >>Action > security > Modify IAM role
{
   "Version": "2012-10-17",
   "Statement": [
       {
           "Effect": "Allow",
           "Action": [
               "ec2:ExportImage",
               "ec2:DescribeImages",
               "ec2:DescribeExportImageTasks"
           ],
           "Resource": "*"
       },
       {
           "Effect": "Allow",
           "Action": [
               "s3:GetObject",
               "s3:ListBucket",
               "s3:PutObject",
               "s3:GetBucketLocation"
           ],
           "Resource": "*"
       }
   ]
}

Set AWS config

AWS Access Key ID [****************SVVH]: xxxxxxxxx
AWS Secret Access Key [****************XESH]:  yyyyyyyyy
Default region name [us-east-2]: us-east-2
Default output format [json]: json
  • Start export task
aws ec2 export-image \
  --region us-east-2  \
  --image-id <ami-01547ffae334d2ca4> \ 
  --disk-image-format VMDK \
  --s3-export-location S3Bucket=object-schema,S3Prefix=exports/
  • How to check progress
aws ec2 describe-export-image-tasks \
  --export-image-task-ids <export-ami-69b4fce2df0ce647t> \
  --region us-east-2
  • Download AMIs
aws s3 cp s3://schema-accounting/exports/<export-ami-69b4fce2df0ce647t.vmdk> .

Upload AMI to aws account

    • If ami download exist in s3 / aws account can run:
cat > containers.json << 'EOF'
[{
  "Description": "neo4j-ami-accounting",
 "Format": "vmdk",
 "UserBucket": {
   "S3Bucket": "schema-accounting",
   "S3Key": "exports/export-ami-69b4fce2df0ce647t.vmdk"
 }
}]
EOF
    • If file export-ami-xxx in local terminal | that download from another account, then want to upload into s3 / other aws account run before:
aws s3 cp ~/JangProgramer/export-ami-819afd57ae1eb750t.vmdk \
         s3://schema-accounting/exports/
aws ec2 import-image \
 --description "Neo4j AMI Import" \
 --disk-containers file://containers.json \
 --region us-east-2
* check status
aws ec2 describe-export-image-tasks // check status
aws ec2 describe-import-image-tasks //