AWS Cloud9 environment is ready. You now build frontend code which discovers the app services details from the Cloud Map and make call to the services.
-
In the Cloud9 environment, click on the New File option under the File menu.
-
It will create an Untitled1 file. Copy-paste the following code.
import boto3 serviceclient = boto3.client('servicediscovery') response = serviceclient.discover_instances(NamespaceName='dojoappnamespace', ServiceName='appservices', QueryParameters={ 'name': 'writeservice' }) functionname = response["Instances"][0]["Attributes"]["function"] lambdaclient = boto3.client('lambda') resp = lambdaclient.invoke(FunctionName=functionname, Payload='"This is a test data"') print(resp["Payload"].read())
`
-
In the code above, you discover the Lambda function to write data by searching for the custom attribute name=writeservice in the appservices service. You get the Lamb function name back which is responsible to write data to the table. You then invoke the Lambda function, passing a sample payload. Save the above code as writeclient.py file.
-
Run the code using the command python writeclient.py command. It will create a record in the DynamoDB table. Make note of the value under the id column in the DynamoDB table. You need this to query data in the next part of the code.
Table Record
-
Similarly create another file readclient.py with the code shown below. The code is reading data from the table. In this code, replace payload value with the value of the id you see in the previous step.
import boto3 serviceclient = boto3.client('servicediscovery') response = serviceclient.discover_instances(NamespaceName='dojoappnamespace', ServiceName='appservices', QueryParameters={ 'name': 'readservice' }) functionname = response["Instances"][0]["Attributes"]["function"] lambdaclient = boto3.client('lambda') resp = lambdaclient.invoke(FunctionName=functionname, InvocationType='RequestResponse', Payload='"8"') print(resp["Payload"].read())
`
-
Run the code using the command python readclient.py command. It will print record from the table.
-
You can see the frontend application is using Cloud Map to discover the services and making call to the actual services (Lambda Function).
-
This completes the workshop. Follow the next step to clean-up the resources so that you don’t incur any cost post the workshop.