Service Discovery using Amazon Cloud Map

   Go back to the Task List

  « 7: Setup Development Environment    9. Clean up »

8: Create Frontend Client

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.

  1. In the Cloud9 environment, click on the New File option under the File menu.

    Cloud9

  2. It will create an Untitled1 file. Copy-paste the following code.

    Cloud9

    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())
    

    `

  3. 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.

  4. 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.

    Cloud9

    Table Record

    Cloud9

  5. 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())
    

    `

  6. Run the code using the command python readclient.py command. It will print record from the table.

    Cloud9

  7. You can see the frontend application is using Cloud Map to discover the services and making call to the actual services (Lambda Function).

  8. This completes the workshop. Follow the next step to clean-up the resources so that you don’t incur any cost post the workshop.