AWS Lightsail instance with Nginx server (using AWS CLI)

How to create a Lightsail Instance running NGINX webserver (using AWS CLI)

Most of the tasks in AWS performed using AWS management console like running EC2 or lightsail instances, creating cloudfront distributions or editing Route 53 records, can also be done using the AWS CLI from the command line. In this post, we will discuss how to create an AWS Lightsail instance with Ubuntu 22.04 machine image and Nginx server. The task is easy to perform and can be completed with a simple command.

Install and Configure AWS CLI:

You need to have the AWS CLI installed locally and configured to achieve this. Installing the AWS CLI is easy as running a one line command. You can run the MSI installer with the following command:

$ msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi

To confirm that AWS CLI is installed, open Windows Powershell and then type

$ aws –version

You will see an output like the following showing that the AWS CLI is installed:

aws-cli/2.10.3 Python/3.9.11 Windows/10 exe/AMD64 prompt/off

Following that, you can run the configuration to configure the AWS CLI and then you are connected. You can start creating instances and doing other things. To configure the AWS CLI, just run the aws configure command as given below and enter the necessary information when prompted.

$ aws configure

AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE

AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

Default region name [None]: us-west-2

Default output format [None]: json

If you do not provide an output format, the default output format json will be used.

Now, that you have installed and configured the AWS CLI, you can start instance creation on aws lightsail. AWS CLI commands start with the service you are working upon like EC2 commands start with aws ec2 and lightsail commands with aws lightsail.

How to Create AWS Lightsail Instance Using AWS CLI

Below is a sample command to create a lightsail instance using the AWS CLI (without user data):

aws lightsail create-instances \

    --instance-names Instance-1 \

    --availability-zone us-west-2a \

    --blueprint-id wordpress_5_1_1_2 \

    --bundle-id nano_2_0

The command above begins with ‘aws lightsail’ as I discussed already and the ‘create-instances’ command is used to create new instances. You can create more than one instances at one go with the same configuration. In the second line, you give your lightsail instance a name. The availability zone is the zone in which you want to create the instance like us-west-2a or us-east-1a. The blueprint is is the id of the machine image or the OS you will use with your instance like Windows server, Ubuntu, wordpress (One click wordpress) or Amazon Linux 2. The last line in the command above includes the bundle id or simply the size of your instance.

The above command will create a simple lightsail instance with wordpress by Bitnami and Apache server installed on it as well as mysql and php. If you do not want wordpress or want to install it your own way like on an NGINX server, you can replace it with the blueprint id of another machine image like Amazon Linux 2 or Ubuntu and then carry out the rest of the installation.

In the example below, we will create a lightsail instance with Ubuntu 22.04 and will install NGINX server on it (via user-data). However, we need the availability zone, blueprint id and the bundle id for instance creation. If you do not know the zone, you can obtain a list of available regions using the AWS CLI. The description in the output will help you select the region based on your audience. To list regions for AWS Lightsail, run the following command from the command line:

$ aws lightsail get-regions

This command will output a list of the aws regions in the following format:

*******************************************************************************

{

    “regions”: [

        {

            “continentCode”: “NA”,

            “description”: “This region is recommended to serve users in the eastern United States”,

            “displayName”: “Virginia”,

            “name”: “us-east-1”,

            “availabilityZones”: [],

            “relationalDatabaseAvailabilityZones”: []

        },

        {

            “continentCode”: “NA”,

            “description”: “This region is recommended to serve users in the eastern United States”,

            “displayName”: “Ohio”,

            “name”: “us-east-2”,

            “availabilityZones”: [],

            “relationalDatabaseAvailabilityZones”: []

        },

        {

            “continentCode”: “NA”,

            “description”: “This region is recommended to serve users in the northwestern United States, Alaska, and western Canada”,            “displayName”: “Oregon”,

            “name”: “us-west-2”,

            “availabilityZones”: [],

            “relationalDatabaseAvailabilityZones”: []

        },

        {

            “continentCode”: “EU”,

            “description”: “This region is recommended to serve users in Ireland, the United Kingdom, and Iceland”,

            “displayName”: “Ireland”,

            “name”: “eu-west-1”,

— More  —

***************************************************************************************

 You can see that the above output includes the region and the country or area where your instance will be located. Just pick the name of the region like us-east-1. However, you will need to add the availability zone and not just region in the final command. For example, in US-East region, the availability zones include us-east-1a, us-east-1b, us-east-1c, us-east-1d, us-east-1e, and us-east-1f. There is no need to be confused about the availability zone. The availability zones are indicated by region names followed by a letter identifier like a,b,c,d,e or f. You can also use the EC2 command ‘describe-availability-zones’ to know about them.

$ aws ec2 describe-availability-zones --region us-east-1

The next step is to find the blueprint id. You can obtain a list of blueprint ids just like you did in the case of availability zones. Run the following command:

$ aws lightsail get-blueprints

The output will show the blueprint id and the machine image name as in the examples below which include the descriptions for Amazon Linux2 and Ubuntu 22.04.

{

            “blueprintId”: “amazon_linux_2”,

            “name”: “Amazon Linux 2”,

            “group”: “amazon_linux_2”,

            “type”: “os”,

            “description”: “Amazon Linux 2 image (HVM / 64-bit). The Amazon Linux 2 image is a supported and maintained Linux image provided by Amazon Web Services (AWS) for use on Amazon Lightsail. It is designed to provide a stable, secure, and high performance execution environment for applications running on Lightsail. It also includes packages that enable easy integration with AWS, including launch configuration tools and many popular AWS libraries and tools. AWS provides ongoing security and maintenance updates to all instances running the Amazon Linux 2 image. The Amazon Linux 2 image is provided at no additional charge to Lightsail users.”,– More              “isActive”: true,

            “minPower”: 0,

            “version”: “2.0.20230418.0”,

            “versionCode”: “1”,

            “productUrl”: “https://aws.amazon.com/amazon-linux-2/”,

            “licenseUrl”: “https://d7umqicpi7263.cloudfront.net/eula/product/f37c8255-1ff9-48bd-b5da-b5046f4fee68/17864b80-f5b6-4f0a-aa26-7346ef135ebc.txt”,

            “platform”: “LINUX_UNIX”

        },

        {

            “blueprintId”: “ubuntu_22_04”,

            “name”: “Ubuntu”,

            “group”: “ubuntu_22”,

            “type”: “os”,

            “description”: “Ubuntu 22.04 – Jammy. Ubuntu Server delivers services reliably, predictably and economically. It is the perfect base on which to build your instances. Ubuntu is free, and you have the option to get support and Landscape from Canonical.”,-            “isActive”: true,

            “minPower”: 0,

            “version”: “22.04 LTS”,

            “versionCode”: “1”,

            “productUrl”: “https://aws.amazon.com/marketplace/pp/prodview-f2if34z3a4e3i”,

            “licenseUrl”: “https://aws.amazon.com/marketplace/pp/prodview-f2if34z3a4e3i#pdp-usage”,

            “platform”: “LINUX_UNIX”

        },

Now, you need to select the right size for your instance. The instance size of bundle id nano_2_0 is the smallest instance size in lightsail costing only $3.5 a month.  Lightsail also offers another small instance size costing only $5 a month and has 1gb ram size known as ‘micro’ and bundle id micro_2_0. To know the bundle id of the instance size you want and to learn other details like price and RAM size, run the following command:

$ aws lightsail get-bundles

You will see an output like the following including the instance size, price and other details.

***************************************************************

{

    “bundles”: [

        {

            “price”: 3.5,

            “cpuCount”: 1,

            “diskSizeInGb”: 20,

            “bundleId”: “nano_2_0”,

            “instanceType”: “nano”,

            “isActive”: true,

            “name”: “Nano”,

            “power”: 300,

            “ramSizeInGb”: 0.5,

            “transferPerMonthInGb”: 1024,

            “supportedPlatforms”: [

                “LINUX_UNIX”

            ]

        },

        {

            “price”: 5.0,

            “cpuCount”: 1,

            “diskSizeInGb”: 40,

            “bundleId”: “micro_2_0”,

            “instanceType”: “micro”,

            “isActive”: true,

            “name”: “Micro”,

            “power”: 500,

            “ramSizeInGb”: 1.0,

            “transferPerMonthInGb”: 2048,

            “supportedPlatforms”: [

                “LINUX_UNIX”

            ]

***********************************************************************************

Now, that we have all the necessary details, we can run the command to create instances. However, before doing that, we will need to create a user data file that will include commands to install and start the NGINX server.

So, let’s first create the user-data file in txt format to include with the command.

$ vim user-data.txt

Hit ‘I’ to enter the ‘Insert’ mode and then paste the following into the file:

#!/bin/bash

sudo apt update -y

sudo apt install -y nginx

sudo systemctl start nginx

sudo systemctl enable nginx

After pasting the above content into the file, hit escape and then type :wq to exit.

Now, let’s run the final command to create the lightsail instance with desired configuration.

$ aws lightsail create-instances --instance-names My-Instance --availability-zone us-east-1a --blueprint-id ubuntu_22_04 --bundle-id nano_2_0 --user-data file:///user-data.txt

Upon successful completion, you will get an output like the following:

*****************************************************************************

{

    “operations”: [

        {

            “id”: “fb0e4b94-8b44-4bfe-a6e5-d3e7978aa79f”,

            “resourceName”: “My-Instance1”,

            “resourceType”: “Instance”,

            “createdAt”: “2023-04-26T12:54:32.745000+05:30”,

            “location”: {

                “availabilityZone”: “us-east-1a”,

                “regionName”: “us-east-1”

            },

            “isTerminal”: false,

            “operationType”: “CreateInstance”,

            “status”: “Started”,

            “statusChangedAt”: “2023-04-26T12:54:32.745000+05:30”

        }

    ]

}

********************************************************************************************

Now, you will need to wait just 1-2 minutes and then copy the public ip of your lightsail instance and paste it into a browser. You will find yourself on the NGINX welcome page. Your instance is ready for use and you can upload a static html site or install a CMS like WordPress on it.

 In case, you want to check out the complete details of your instance including the ip (the instance you just created and any existing instances in lightsail), you will need to run the following command:

$ aws lightsail get-instances

The resulting output will look like the following:

*******************************************************************************

{

    “instances”: [

        {

            “name”: “My-Instance”,

            “arn”: “arn:aws:lightsail:us-east-1:302984893886:Instance/8551837d-96a7-4b40-929a-dba90ad95301”,

            “supportCode”: “856434544309/i-05eb193e23c446ad7”,

            “createdAt”: “2023-04-26T12:50:58.858000+05:30”,

            “location”: {

                “availabilityZone”: “us-east-1a”,

                “regionName”: “us-east-1”

            },

            “resourceType”: “Instance”,

            “tags”: [],

            “blueprintId”: “ubuntu_22_04”,

            “blueprintName”: “Ubuntu”,

            “bundleId”: “nano_2_0”,

            “isStaticIp”: false,

            “privateIpAddress”: “172.26.11.183”,

            “publicIpAddress”: “44.200.9.170”,

            “ipv6Addresses”: [

                “2600:1f10:406d:7500:bc1:600e:504a:cebd”

            ],

            “ipAddressType”: “dualstack”,

            “hardware”: {

                “cpuCount”: 1,

                “disks”: [

                    {

                        “createdAt”: “2023-04-26T12:50:58.858000+05:30”,

                        “sizeInGb”: 20,

                        “isSystemDisk”: true,

                        “iops”: 100,

                        “path”: “/dev/sda1”,

                        “attachedTo”: “My-Instance”,

                        “attachmentState”: “attached”

                    }

                ],

                “ramSizeInGb”: 0.5

            },

            “networking”: {

                “monthlyTransfer”: {

                    “gbPerMonthAllocated”: 1024

                },

                “ports”: [

                    {

                        “fromPort”: 80,

                        “toPort”: 80,

                        “protocol”: “tcp”,

                        “accessFrom”: “Anywhere (0.0.0.0/0 and ::/0)”,

                        “accessType”: “public”,

                        “commonName”: “”,

                        “accessDirection”: “inbound”,

                        “cidrs”: [

                            “0.0.0.0/0”

                        ],

                        “ipv6Cidrs”: [

                            “::/0”

                        ],

                        “cidrListAliases”: []

                    },

                    {

                        “fromPort”: 22,

                        “toPort”: 22,

                        “protocol”: “tcp”,

                        “accessFrom”: “Anywhere (0.0.0.0/0 and ::/0)”,

                        “accessType”: “public”,

                        “commonName”: “”,

                        “accessDirection”: “inbound”,

                        “cidrs”: [

                            “0.0.0.0/0”

                        ],

                        “ipv6Cidrs”: [

                            “::/0”

                        ],

                        “cidrListAliases”: []

                    }

                ]

            },

            “state”: {

                “code”: 16,

                “name”: “running”

            },

            “username”: “ubuntu”,

            “sshKeyName”: “LightsailDefaultKeyPair”,

            “metadataOptions”: {

                “state”: “applied”,

                “httpTokens”: “optional”,

                “httpEndpoint”: “enabled”,

                “httpPutResponseHopLimit”: 1,

                “httpProtocolIpv6”: “disabled”

            }

        },

*********************************************************************************************

Unlike EC2, where you need to specify if you have to create a dual stack instance (IPV4 + IPV6), in the case of lightsail, the default instance type is double stack and includes both IPV4 and IPV6 public ips.

How to delete AWS Lightsail Instance using AWS CLI:

If you do not need a lightsail instance and want to delete it, you will need only its name to run the command for deletion. As in the above example, we named our instance My-Instance. To delete this instance, we will run the following command:

$ aws lightsail delete-instance --instance-name My-Instance

Output:

{

    “operations”: [

        {

            “id”: “2895e33d-731f-4d90-83bf-b4266bd54ebe”,

            “resourceName”: “My-Instance”,

            “resourceType”: “Instance”,

            “createdAt”: “2023-04-26T13:08:59.064000+05:30”,

            “location”: {

                “availabilityZone”: “us-east-1a”,

                “regionName”: “us-east-1”

            },

            “isTerminal”: true,

            “operationDetails”: “”,

            “operationType”: “DeleteInstance”,

            “status”: “Succeeded”,

            “statusChangedAt”: “2023-04-26T13:08:59.064000+05:30”

        }

    ]

}

As you can see in the above output, the operation type ‘DeleteInstance’ has succeeded and the instance in question has been deleted.