2026-03-19 Deploy and Setting EC2 instances

From Izara Wiki
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

// wait for image

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

// wait for image Note : can shared VPC for create another instance in same account // wait for image

Create Subnet

// wait for image

  • Select VPC

// wait for image

  • 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

// wait for image

  • 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

// wait for image

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

// wait for image

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

// wait for image

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

Create VPC Endpoint

// wait for image

  • 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

// wait for image

  • Security groups

// wait for image

  • 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

// wait for image

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

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

// wait for image

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

// wait for image

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

Step2 : Select target // wait for image

  • 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

// wait for image

  • 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