Embedded Analytics
with Amazon QuickSight
Module Four: Lambda Functions
In this module we will setup our compute infrastructure to power the web portal.
Introduction
In this module, we will setup our compute infrastructure to power the web portal. We are using AWS Lambda, however, you can use your existing compute infrastructure where your web portal or application is already running.
What You Will Learn
- Create Lambda Execution Role
- Create Embed URL Lambda for Dashboard Embedding - To assume role that has permission to run QuickSight APIs and generate Dashboard / Session embed url.
- Create Embed URL Lambda for Session Embedding - To assume role that has permission to run QuickSight APIs and generate Dashboard / Session embed url.
Time to Complete
20 minutes
Services Used
Implementation
-
Create Lambda Execution Role
Steps to create a role that will be used for lambda execution are given below
1. Launch IAM and choose Roles from left panel.
2. Click Create role button.
2. Click Lambda and Next: Permissions button.
3. Click Create Policy button. It will open up a new tab with policy create option.
4. Click JSON tab, paste the following policy and click Review policy button.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "quicksight:DescribeUser", "quicksight:UpdateUser", "quicksight:CreateGroup", "quicksight:CreateUser", "quicksight:DeleteUser", "quicksight:DeleteGroup", "quicksight:DeleteGroupMembership", "quicksight:UpdateDashboardPermissions", "quicksight:CreateGroupMembership", "quicksight:RegisterUser" ], "Resource": "*" } ] }
5. Name the policy as QSInitialSetupTempPolicy and click Create policy button.
We will use this role to run an initial setup lambda function and will then remove this temp policy.6. Switch back to create role tab. Refresh the policy list, search for QSInitialSetupTempPolicy and Check the select box.
7. Search for LambdaBasic, select AWSLambdaBasicExecutionRole and click Next: Tags button.
8. Click Next: Review.
9. Name the role as QSLambdaBasicExecutionRole and click Create role button.
-
Create Embed Url Lambda (For Dashboard Embedding)
Skip this step if you are trying out session embedding.
We will now create a lambda function that generates the dynamic embed url.
1. Launch Lambda and click Create function button.
2. Make the following selections.
Choose Author from scratch
Function Name: QSGetEmbedUrl
Runtime: Python 3.8
Execution role: Use an existing role Select QSLambdaBasicExecutionRole from drop down. Click Create function3. Copy following python code into lambda function and click Save.
def lambda_handler(event, context): #Implementation import urllib, json, sys, os, base64, boto3, botocore #Read in environment variables awsAccountId = os.environ["AwsAccountId"] roleArn = os.environ["RoleArn"] #Read in the values passed to Lambda function openIdToken = event['queryStringParameters']['openIdToken'] dashboardId = event['queryStringParameters']['dashboardId'] dashboardRegion = event['queryStringParameters']['dashboardRegion'] resetDisabled = True undoRedoDisabled = True userName = json.loads(base64.b64decode(openIdToken.split('.')[1]+ "========"))['cognito:username'] #Assume role that has permissions on QuickSight sts = boto3.client('sts') assumedRole = sts.assume_role_with_web_identity( RoleArn = roleArn, RoleSessionName = userName, WebIdentityToken = openIdToken ) assumedRoleSession = boto3.Session( aws_access_key_id = assumedRole['Credentials']['AccessKeyId'], aws_secret_access_key = assumedRole['Credentials']['SecretAccessKey'], aws_session_token = assumedRole['Credentials']['SessionToken'], ) quickSight = assumedRoleSession.client('quicksight',region_name= dashboardRegion) #Generate Embed url response = quickSight.get_dashboard_embed_url( AwsAccountId = awsAccountId, DashboardId = dashboardId, IdentityType = 'IAM', SessionLifetimeInMinutes = 600, UndoRedoDisabled = undoRedoDisabled, ResetDisabled = resetDisabled ) return { 'statusCode': 200, 'headers': {"Access-Control-Allow-Origin": "*"}, 'body': json.dumps(response) }
4. Scroll down to Environment variables section and click Manage environment variables.
5. Add the following environment variables.
AwsAccountId
RoleArn - QSER Role Arn saved in your notepad.
Click Save button.6. Scroll down to Basic Settings and click Edit button.
7. Increase Timeout value to 2 mins and click Save button
-
Create Embed Url Lambda (For Session Embedding)
Skip to next section if you are trying out dashboard embedding.
We will now create a lambda function that generates the dynamic embed url.1. Launch Lambda and click Create function button.
2. Make the following selections.
Choose Author from scratch
Function Name: QSGetEmbedUrl
Runtime: Python 3.8
Execution role: Use an existing role Select QSLambdaBasicExecutionRole from drop down. Click Create function3. Copy following python code into lambda function and click Save.
import json,sys,os,boto3,base64 def lambda_handler(event, context): #Read in environment variables awsAccountId = os.environ["AwsAccountId"] roleArn = os.environ["RoleArn"] identityRegion = os.environ["QuickSightIdentityRegion"] roleName = roleArn.split('/')[1] #Read in the values passed to Lambda function openIdToken = event['queryStringParameters']['openIdToken'] dashboardRegion = event['queryStringParameters']['dashboardRegion'] userName = json.loads(base64.b64decode(openIdToken.split('.')[1]+ "========"))['cognito:username'] #Assume role that has permissions on QuickSight sts = boto3.client('sts') assumedRole = sts.assume_role_with_web_identity( RoleArn = roleArn, RoleSessionName = userName, WebIdentityToken = openIdToken ) assumedRoleSession = boto3.Session( aws_access_key_id = assumedRole['Credentials']['AccessKeyId'], aws_secret_access_key = assumedRole['Credentials']['SecretAccessKey'], aws_session_token = assumedRole['Credentials']['SessionToken'], ) quickSight = assumedRoleSession.client('quicksight', region_name = dashboardRegion) #Generate Session Embed url response = quickSight.get_session_embed_url( AwsAccountId = awsAccountId, UserArn = "arn:aws:quicksight:"+identityRegion+":"+awsAccountId+":user/default/"+roleName+"/"+userName ) return { 'statusCode': 200, 'headers': {"Access-Control-Allow-Origin": "*"}, 'body': json.dumps(response) }
4. Scroll down to Environment variables section and click Manage environment variables.
5. Add the following environment variables.
AwsAccountId
RoleArn - QSER Role Arn saved in your notepad.
QuickSightIdentityRegion - Region where your QuickSight identities are setup.
Click Save button.6. Scroll down to Basic Settings and click Edit button.
7. Increase Timeout value to 2 mins and click Save button
Conclusion
You successfully completed module four! Next, lets create an API gateway and static web page in module five.