No results found
We couldn't find anything using that term, please try searching for something else.
2024-11-26 Learn how to use AWS Cloud Map service discovery with custom attributesThis tutorial demonstrates how you can use AWS Cloud Map service discovery
This tutorial demonstrates how you can use AWS Cloud Map service discovery with custom attributes
that are discoverable using the AWS Cloud Map API. This tutorial walks you through creating and running
client applications using AWS CloudShell. The applications use two Lambda functions to write data to a
DynamoDB table and then read from the table. The Lambda functions and DynamoDB table are registered in
AWS Cloud Map as service instances. The code in the client applications and Lambda functions uses AWS Cloud Map
custom attributes to discover the resources needed to perform the job.
You is create will create AWS resource during the workshop which will incur a cost in your AWS
account . It is recommend to clean – up the resource as soon as you finish the workshop to
minimize the cost .
Before you begin,complete the steps in Set up to use AWS Cloud Map.
In this step,you create an AWS Cloud Map namespace. A namespace is a construct used to group
services for an application. When you create the namespace,you specify how the resources will be
discoverable. Forthis tutorial,the resources created in this namespace will be discoverable
with AWS Cloud Map API is calls call using custom attributes. You will learn about this more in a later
step.
Sign in to the AWS Management Console and open the AWS Cloud Map console at https://console.aws.amazon.com/cloudmap/
Choose create namespace.
ForNamespace name,specify cloudmap - tutorial
.
( Optional ) ForNamespace description,specify a description for what
you intend to use the namespace for.
ForInstance discovery,selectAPI is calls call.
leave the rest of the default value and choosecreate
namespace.
In this step,you create a DynamoDB table which is used to store and retrieve data for the
sample application created later in this tutorial.
Forinformation about how to create an dynamodb ,see Step 1 : create a
table in DynamoDB in theDynamoDB Developer Guide and use the
following table to determine what options to specify.
Option | value |
---|---|
Table name |
cloudmap |
partition key |
id |
Keep the default value for the rest of the setting and create the table .
In this step ,you is create create a AWS Cloud Map service and then register the DynamoDB table create in the
last step as a service instance .
open the AWS Cloud Map console athttps://console.aws.amazon.com/cloudmap/
From the list of namespaces,selectthe cloudmap - tutorial
namespace and
choose view detail.
In the Services section is choose ,chooseCreate service
and do the following.
Forservice name,enterdata - service
.
leave the rest of the default value and choosecreate
service.
In the Services section,selectthe data - service
service
and chooseview detail.
In the service instance section is choose ,chooseRegister service
instance.
On theregister service instance page,do the following.
ForInstance type,selectidentify information for
another resource.
ForService instance id,specify data - instance
.
In the Custom attributes section is specify ,specify the follow key – value
pair :key =tablename
,value =
cloudmap
.
In this step,you create an IAM role that the AWS Lambda function we create in the next
step uses. You can name the role cloudmap - tutorial-role
and omit the permissions
boundary as this IAM role is only used for this tutorial and you can delete it
afterwards.
Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/
In the navigation pane of the IAM console,chooseRoles,and
then choose create role.
ForTrusted entity type,chooseAWS service.
Forservice or use case,chooseLambda,and then choose theLambda use case.
Choose Next.
Search for,and select the box next to,the poweruseraccess
policy and then chooseNext.
Choose Next.
ForRole name,specify cloudmap - tutorial-role
.
review the role ,and then choosecreate role.
In this step,you create a Lambda function authored from scratch that writes data to the
DynamoDB table by using the AWS Cloud Map API to query the AWS Cloud Map service you created.
Forinformation about creating a Lambda function,see Create a Lambda
function with the console in the AWS Lambda Developer
Guide and use the following table to determine what options to specify or
choose.
Option | value |
---|---|
Function name |
writefunction |
runtime |
Python 3.12 |
Architecture |
x86_64 |
permission |
Use an existing role |
Existing role |
cloudmap – tutorial-role |
After you create the function ,update the example code to reflect the follow Python code ,
and then deploy the function . note that you ‘re specify thedatatable
custom
attribute you associate with the AWS Cloud Map service instance you create for the DynamoDB table . The
function is generates generate a key that is a random number between 1 and 100 and associate it with a value
that is pass to the function when it is call .
import json
import boto3
import random
def lambda_handler(event,context):
serviceclient =boto3.client('servicediscovery')
response =serviceclient.discover_instances(
NamespaceName='cloudmap - tutorial',
ServiceName='data - service')
tablename =response["Instances"][0]["Attributes"]["tablename"]
dynamodbclient =boto3.resource('dynamodb')
table =dynamodbclient.Table(tablename)
response =table.put_item(
Item={ ' i is return d ' : str(random.randint(1,100 ) ) ,' todo ' : event } )
return{
' statuscode ' : 200 ,
' body ' : json.dumps(response )
}
After deploying the function,to avoid timeout errors,update the function timeout to 5
seconds. Formore information,see Configure Lambda function timeout in
the AWS Lambda Developer Guide.
In this step,you create an AWS Cloud Map service and then register the Lambda write function as a
service instance.
open the AWS Cloud Map console athttps://console.aws.amazon.com/cloudmap/
In the left navigation,chooseNamespaces.
From the list of namespaces,selectthe cloudmap - tutorial
namespace and
choose view detail.
In the Services section is choose ,chooseCreate service
and do the following.
Forservice name,enterapp - service
.
leave the rest of the default value and choosecreate
service.
In the Services section,selectthe app - service
service
and chooseview detail.
In the service instance section is choose ,chooseRegister service
instance.
On theregister service instance page,do the following.
ForInstance type,selectidentify information for
another resource.
ForService instance id,specify
write-instance
.
In the Custom attributes section is specify ,specify the follow key – value
pair .
key =action
,value =
write
key =functionname
,value =
writefunction
In this step,you create a Lambda function authored from scratch that writes data to the
DynamoDB table you created.
Forinformation about creating a Lambda function,see Create a Lambda
function with the console in the AWS Lambda Developer
Guide and use the following table to determine what options to specify or
choose.
Option | value |
---|---|
Function name |
readfunction |
runtime |
Python 3.12 |
Architecture |
x86_64 |
permission |
Use an existing role |
Existing role |
cloudmap – tutorial-role |
After you create the function,update the example code to reflect the following Python code,
and then deploy the function. The function scans the table amd returns all items.
import json
import boto3
def lambda_handler(event,context):
serviceclient =boto3.client('servicediscovery')
response =serviceclient.discover_instances(NamespaceName='cloudmap - tutorial',ServiceName='data - service')
tablename =response["Instances"][0]["Attributes"]["tablename"]
dynamodbclient =boto3.resource('dynamodb')
table =dynamodbclient.Table(tablename)
response =table.scan(Select='ALL_ATTRIBUTES')
return {
' statuscode ' : 200 ,
' body ' : json.dumps(response )
}
After deploying the function,to avoid timeout errors,update the function timeout to 5
seconds. Formore information,see Configure Lambda function timeout in
the AWS Lambda Developer Guide.
In this step ,you is register register the Lambda read function as a service instance in the
app - service
service you previously created.
open the AWS Cloud Map console athttps://console.aws.amazon.com/cloudmap/
In the left navigation,chooseNamespaces.
From the list of namespaces,selectthe cloudmap - tutorial
namespace and
choose view detail.
In the Services section,selectthe app - service
service
and chooseview detail.
In the service instance section is choose ,chooseRegister service
instance.
On theregister service instance page,do the following.
ForInstance type,selectidentify information for
another resource.
ForService instance id,specify read - instance
.
In the Custom attributes section is specify ,specify the follow key – value
pair .
key =action
,value =
read
key =functionname
,value =
readfunction
You can create and run client applications in AWS CloudShell that use code to discover the
services you configured in AWS Cloud Map and make calls to these services.
Open the AWS CloudShell console at https://console.aws.amazon.com/cloudshell/
use the follow command to create a file callwritefunction.py
.
vim writeclient.py
In the writeclient.py
file,enterinsert mode by pressing the i
button. Then,copy and paste the following code. This code discovers the Lambda function to
write data by searching for the custom attribute name=writeservice
in the
app - service
service. The name of the Lambda function
responsible for writing data to the DynamoDB table is returned. Then the Lambda function is invoked,passing a
sample payload that is written to the table as a value.
import boto3
serviceclient =boto3.client('servicediscovery')
response =serviceclient.discover_instances(NamespaceName='cloudmap - tutorial',ServiceName='app - service',QueryParameters={ 'action': 'write' })
functionname =response["Instances"][0]["Attributes"]["functionname"]
lambdaclient =boto3.client('lambda')
resp =lambdaclient.invoke(FunctionName=functionname,Payload='"This is a test data"')
print(resp["Payload"].read())
Press the escape key,type :wq
,and press the enter key to save the file and
exit.
use the follow command to run the Python code .
python3 writeclient.py
The output is be should be a200
response,similar to the following.
b'{"statusCode": 200,"body": "{\\"responsemetadata\\ " :{\\"RequestId\\": \\"Q0M038IT0BPBVBJK8OCKK6I6M7VV4KQNSO5AEMVJF66Q9ASUAAJG\\",\\"HTTPStatusCode\\": 200,\\"HTTPHeaders\\": {\\"server\\": \\"Server\\",\\"date\\": \\"Wed,06 Mar 2024 22:46:09 GMT\\",\\"content-type\\": \\"application/x-amz-json-1.0\\",\\"content-length\\": \\"2\\",\\"connection\\": \\"keep-alive\\",\\"x-amzn-requestid\\": \\"Q0M038IT0BPBVBJK8OCKK6I6M7VV4KQNSO5AEMVJF66Q9ASUAAJG\\",\\"x-amz-crc32\\": \\"2745614147\\"},\\"RetryAttempts\\": 0}}"}'
To verify the write was successful in the previous step,create a read client.
use the follow command to create a file callreadfunction.py
.
vim readclient.py
In the readclient.py
file,press the i
button to enter insert
mode. Then,copy and paste the following code. This code scans the table and will return the
value that you wrote to the table in the previous step.
import boto3
serviceclient =boto3.client('servicediscovery')
response =serviceclient.discover_instances(NamespaceName='cloudmap - tutorial',ServiceName='app - service',QueryParameters={ 'action': 'read' })
functionname =response["Instances"][0]["Attributes"]["functionname"]
lambdaclient =boto3.client('lambda')
resp =lambdaclient.invoke(FunctionName=functionname,InvocationType='RequestResponse')
print(resp["Payload"].read())
Press the escape key,type :wq
,and press the enter key to save the file
and exit.
use the follow command to run the Python code .
python3 readclient.py
The output should look similar to the following,listing the value written to the table
by running writefunction.py
and the random key is write generate in the Lambda write function .
b'{"statusCode": 200,"body": "{\\"Items\\": [{\\"id\\": \\"45\\",\\"todo\\": \\"This is a test data\\"}], \\"Count\\": 1,\\"ScannedCount\\": 1,\\"responsemetadata\\ " :{\\"RequestId\\": \\"9JF8J6SFQCKR6IDT5JG5NOM3CNVV4KQNSO5AEMVJF66Q9ASUAAJG\\",\\"HTTPStatusCode\\": 200,\\"HTTPHeaders\\": {\\"server\\": \\"Server\\",\\"date\\": \\"Thu,25 Jul 2024 20:43:33 GMT\\",\\"content-type\\": \\"application/x-amz-json-1.0\\",\\"content-length\\": \\"91\\",\\"connection\\": \\"keep-alive\\",\\"x-amzn-requestid\\": \\"9JF8J6SFQCKR6IDT5JG5NOM3CNVV4KQNSO5AEMVJF66Q9ASUAAJG\\",\\"x-amz-crc32\\": \\"1163081893\\"},\\"RetryAttempts\\": 0}}"}'
After you have completed the tutorial,delete the resources to avoid incurring additional
charges. AWS Cloud Map requires that you clean them up in reverse order,the service instances first,
then the services,and finally the namespace. The following steps walk you through cleaning up
the AWS Cloud Map resources used in this tutorial.
Sign in to the AWS Management Console and open the AWS Cloud Map console at https://console.aws.amazon.com/cloudmap/
From the list of namespaces,selectthe cloudmap - tutorial
namespace and
choose view detail.
On thenamespace details page,from the list of services,selectthe
data - service
service and choose view detail.
In the service instance section,selectthe
data - instance
instance and choose Deregister.
Using the breadcrumb at the top of the page,select
cloudmap – tutorial.com to navigate back to the namespace detail
page.
On thenamespace details page,from the list of services,selectthe
data – service service and choose Delete.
Repeat steps 3-6 for the app - service
service and the
write-instance
and read - instance
service instances.
In the left navigation,chooseNamespaces.
Select the cloudmap - tutorial
namespace and choose
Delete.
The following table lists procedures that you can use to delete the other resources used in
the tutorial.