Getting Started With AWS Services Using LocalStack
Published: 2023-07-17 10:11:29


## Introducing  Localstack 

In simple words localstack "Is a cloud service emulator used for testing and developing cloud applications"

The reason for something like LocalStack to exist is pretty simple to mock AWS APIs and their responses for local development. In the heated debate of determining the best way to train resource for larger Enterprise localstack has a pretty convincing argument. 

Imagine a large enterprise that onboards a few thousand developers a year. Some percentage of them will need to learn how AWS works. How do you build effective guardrails that let them develop against the platform without introducing a whole bunch of friction? Or without running the risk of cost overruns and data leakage?


## Before Getting Started 

I will be using Windows through out this tutorial. The steps though for any operating system will be the same. ( Sorry Linux / macOS community )

My windows information :

OsName    :                      Microsoft Windows 10 Pro         OsVersion  :                     10.0.19044      
OsHardware :                     10.0.1904  
AbstractionLayer  :              1.2251


Also for for this tutorial we would be using WSL 2 backend for Docker. So enable your WSL 2 service if it  isn't enabled. You could check whether WSL 2 is enabled or not by typing the following command into your terminal 

```text 
wsl –-list --verbose
```

Confirm the version of the distro version is set to 2. 

By default the WSL is disabled If you want to enable WSL services you can follow this guide at [Install WSL On Windows](https://woshub.com/install-wsl-windows-subsystem-linux/#:~:text=By%20default%2C%20WSL%20is%20disabled,OK%2C%20and%20restart%20your%20computer.&text=Then%20you%20need%20to%20restart%20your%20computer)

If you like to change your WSL distro you could follow the step highlighted at [Install WSL | Microsoft Learn](https://learn.microsoft.com/en-us/windows/wsl/install)

Moreover you need 

- `python` (Python 3.7 up to 3.11 supported)
- `pip` (Python package manager)

It will aid the installation of localstack. 


## Step 1 :  Installing Docker 

Docker's primary focus is to automate the deployment of applications inside software containers and the automation of operating system level virtualization. It's more lightweight than standard Containers and boots up in seconds.

You can learn more about Details of Docker and Docker containers at [Overview | Docker Documentation](https://docs.docker.com/get-started/)

As fall as installation is concerned I would recommend getting Docker Desktop app for windows at [Install Docker Desktop on Windows | Docker Documentation](https://docs.docker.com/desktop/install/windows-install/)

Alternatively you could manually install docker if you feel like it following the steps at [Install Docker Engine | Docker Documentation](https://docs.docker.com/engine/install/)


Once docker is successfully installed you can verify the installation by opening the Docker Desktop installation or by typing the following command in your terminal.

```text 
docker ps 
```

Here is the docker version I am using 


| Client:                    	|                          	| Server:  	|                                          	|
|----------------------------	|--------------------------	|--------------------------------------	|------------------------------------------	|
| Cloud integration:            |  v1.0.25               	| Engine:                              	| Docker Desktop 4.9.0 (80466)                                         	|
| Version:                   	| 20.10.16                 	| Version:                             	| 20.10.16                                 	|
| API version:               	| 1.41                     	| API version:                         	| 1.41 (minimum version 1.12)              	|
| Go version:                	| go1.17.10                	| Go version:                          	| go1.17.10                                	|
| Git commit:                	| aa7e414                  	| Git commit:                          	| f756502                                  	|
| Built:                     	| Thu May 12 09:17:07 2022 	| Built:                               	| Thu May 12 09:15:42 2022                 	|
| OS/Arch:                   	| windows/amd64            	| OS/Arch:                             	| linux/amd64                              	|
| Context:                   	| default                  	| Experimental:                        	| false                                    	|
| Experimental:              	| true                     	| containerd:                          	|                                          	|
|                            	|                          	| Version:                             	| 1.6.4                                    	|
|                            	|                          	| GitCommit:                           	| 212e8b6fa2f44b9c21b2798135fc6fb7c53efc16 	|
|                            	|                          	| runc:                                	|                                          	|
|                            	|                          	| Version:                             	| 1.1.1                                    	|
|                            	|                          	| GitCommit:                           	| v1.1.1-0-g52de29d                        	|
|                            	|                          	| docker-init:                         	|                                          	|
|                            	|                          	| Version:                             	| 0.19.0                                   	|
|                            	|                          	| GitCommit:                           	| de40ad0                                  	|




## Step 2 : Installing LocalStack


You can install the LocalStack CLI in your Python environment with:

```text
$ python3 -m pip install --upgrade localstack
```


In this tutorial we are using the localstack cli but there are many other alternatives for starting and managing localstack. You can find them at [Installation | Docs (localstack.cloud)](https://docs.localstack.cloud/getting-started/installation/)and choose whichever suits you the best. 


If everything went well ( and I hope it did ). You can verify LocalStack installation by typing the following command in the 

```text
localstack --version
```


To be able to run localstack ensure that docker deamon (in this case docker desktop) is running in the background and type the following in the terminal 

``` text 
localstack start 
```

If you observe the localstack logo displayed on the CLI. Congrats localstack is running successfully. Don't close your cli. You will see a container by the name of localstack running in your list of containers. 

Note : If you don't see a entry of localstack inside the containers list in docker. One possible reason might be the you don't have the localstack container image. 

```text
docker pull localstack/localstack-pro:latest
```



## Step 3 :  Configure AWS CLI

For Configuration of your AWS CLI you'll need to install it first. duh ! 

You can follow the steps highlighted at [Install or update the latest version of the AWS CLI - AWS Command Line Interface (amazon.com)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) to get it done. 

To verify your installation use the following terminal command 

```text
aws --version
```

After a successful install of the AWS CLI you would need to configure it. 

Do so by first typing the following in the terminal 

```text
docker exec -it <container id> /bin/bash
```

Note: You can find the container id in the docker desktop container page

You are now set to configure your AWS CLI. 

``` text
aws configure --profile your_name
```

Enter the following credentials
``` text
AWS Access Key Id : 79
AWS Secret Access key : 79
Default region name [None]: us-east-1
Default output format : json
```

The first two are irrelevant because localstack does not verify credentials. For the region name you can add any compatible region mentioned at [Regions and Zones - Amazon Elastic Compute Cloud](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)


And you are done !

The next step is an optional step. You are now ready to build any kind of AWS application. Hurray !

But I thought it'll be great if I could leave you with a sample program. The sample program is a simple program that creates a SQS Queue and tries to send a message to it. The program uses the JAVA SDK FOR AWS. 


## Step 4 : Building Your First Program 

Create a Java program in your desired IDE. Since I am using Intellij you can refer to creating a new program at [Create A New Program | Intellij](https://www.jetbrains.com/help/idea/new-project-wizard.html#project-with-tips)

Create a new java class and copy paste the code below 

``` java
package service;  
  
import com.amazonaws.client.builder.AwsClientBuilder;  
import com.amazonaws.services.sqs.AmazonSQS;  
import com.amazonaws.services.sqs.AmazonSQSClient;  
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;  
import com.amazonaws.services.sqs.model.AmazonSQSException;  
import com.amazonaws.services.sqs.model.CreateQueueRequest;  
import com.amazonaws.services.sqs.model.QueueAttributeName;  
import com.amazonaws.services.sqs.model.SendMessageRequest;  
  
  
public class SQS {  
  
    public static void main(String args[]){  
  
        AmazonSQS sqsClient = createClient();  
  
        String queueName ="Fire";  
  
       createQueue(sqsClient,queueName);  
  
  
        String message = "This is a body text for the message";  
        String queueUrl = sqsClient.getQueueUrl(queueName).getQueueUrl();  
        sendMessage(sqsClient,queueUrl,message);  
  
  
    }  
  
    private static void sendMessage(AmazonSQS sqsClient, String queueUrl,String message) {  
  
        SendMessageRequest request = new SendMessageRequest()  
                .withQueueUrl(queueUrl)  
                .withMessageBody(message)  
                .withDelaySeconds(5);  
  
        try{  
            sqsClient.sendMessage(request);  
        }  
        catch(Exception e){  
            e.printStackTrace();  
        }  
    }  
  
    private static void createQueue(AmazonSQS SQSClient, String queueName) {  
        CreateQueueRequest request = new CreateQueueRequest(queueName)  
                .addAttributesEntry("DelaySeconds","60")  
                .addAttributesEntry("MessageRetentionPeroid","86400");  
  
        try {  
            SQSClient.createQueue(request);  
        }  
        catch(Exception e){  
            e.printStackTrace();  
        }  
  
    }  
  
    private static AmazonSQS createClient(){  
        return AmazonSQSClientBuilder.standard()  
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(  
                        "http://localhost:4566","us-east-1"))  
                .build();  
    }  
  
  
}

```


pom.xml dependencies are as follows 

``` xml
  
<dependency>  
  <groupId>com.amazonaws</groupId>  
  <artifactId>aws-java-sdk-dynamodb</artifactId>  
  <version>1.11.318</version>  
</dependency>
  

 note : Please also change the package from war to jar
```

## End

So that is all for now. I hope this article was helpful for you and everything went smoothly. If it did good on you. If it didn't don't worry programmer is more about debugging error than creating something indefinitely. 

If you couldn't resolve some errors or are facing some werid issues you could go on to [aws s3 using localstack](https://medium.com/@mugheesqasim/aws-s3-using-localstack-and-java-4e23796c23d2) written by the person who inspired me to write this article. Mughees highlights some common issues and how to resolve them. It is definitely worth a read.