├── tests ├── __init__.py └── unit │ ├── __init__.py │ ├── test_ada_appflow_extension_stack.py │ └── test_update_flow_metadata.py ├── ada_appflow_extension ├── __init__.py └── ada_appflow_extension_stack.py ├── lambdas ├── notify_user │ ├── __init__.py │ ├── requirements.txt │ └── lambda_function.py ├── create_ada_dataproduct │ ├── __init__.py │ ├── requirements.txt │ └── lambda_function.py ├── trigger_ada_data_update │ ├── __init__.py │ ├── requirements.txt │ └── lambda_function.py ├── update_flow_metadata │ ├── __init__.py │ ├── requirements.txt │ └── lambda_function.py └── existing_flow_handler_cr │ ├── __init__.py │ ├── requirements.txt │ └── lambda_function.py ├── .bandit ├── NOTICE ├── requirements.txt ├── requirements-dev.txt ├── images ├── ada-appflow-extension-sm-def-flow.png └── ada-appflow-extension-arch-diagram.png ├── .gitignore ├── CODE_OF_CONDUCT.md ├── source.bat ├── app.py ├── cdk.json ├── CONTRIBUTING.md ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ada_appflow_extension/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambdas/notify_user/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambdas/create_ada_dataproduct/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambdas/trigger_ada_data_update/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambdas/update_flow_metadata/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambdas/existing_flow_handler_cr/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.bandit: -------------------------------------------------------------------------------- 1 | # FILE: .bandit 2 | [bandit] 3 | skips = B101 -------------------------------------------------------------------------------- /lambdas/notify_user/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.28.36 -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | -------------------------------------------------------------------------------- /lambdas/update_flow_metadata/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.28.36 2 | moto==4.2.2 -------------------------------------------------------------------------------- /lambdas/create_ada_dataproduct/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.28.36 2 | requests==2.31.0 -------------------------------------------------------------------------------- /lambdas/trigger_ada_data_update/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.28.36 2 | requests==2.31.0 -------------------------------------------------------------------------------- /lambdas/existing_flow_handler_cr/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.28.39 2 | requests==2.31.0 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aws-cdk-lib==2.100.0 2 | constructs>=10.0.0,<11.0.0 3 | cdk-nag==2.27.183 -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | pytest==7.4.1 2 | moto==4.2.2 3 | black==23.7.0 4 | isort==5.12.0 5 | bandit==1.7.5 6 | -------------------------------------------------------------------------------- /images/ada-appflow-extension-sm-def-flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/ada-appflow-extension/main/images/ada-appflow-extension-sm-def-flow.png -------------------------------------------------------------------------------- /images/ada-appflow-extension-arch-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/ada-appflow-extension/main/images/ada-appflow-extension-arch-diagram.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | package-lock.json 3 | __pycache__ 4 | .pytest_cache 5 | .venv 6 | *.egg-info 7 | 8 | # CDK asset staging directory 9 | .cdk.staging 10 | cdk.out 11 | cdk.context.json 12 | 13 | # macOS 14 | **/.DS_Store 15 | 16 | # Intellij 17 | .idea -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /source.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | rem The sole purpose of this script is to make the command 4 | rem 5 | rem source .venv/bin/activate 6 | rem 7 | rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows. 8 | rem On Windows, this command just runs this batch file (the argument is ignored). 9 | rem 10 | rem Now we don't need to document a Windows command for activating a virtualenv. 11 | 12 | echo Executing .venv\Scripts\activate.bat for you 13 | .venv\Scripts\activate.bat 14 | -------------------------------------------------------------------------------- /tests/unit/test_ada_appflow_extension_stack.py: -------------------------------------------------------------------------------- 1 | import aws_cdk as core 2 | import aws_cdk.assertions as assertions 3 | 4 | from ada_appflow_extension.ada_appflow_extension_stack import AdaAppflowExtensionStack 5 | 6 | 7 | # example tests. To run these tests, uncomment this file along with the example 8 | # resource in ada_appflow_extension/ada_appflow_extension_stack.py 9 | def test_sqs_queue_created(): 10 | app = core.App() 11 | stack = AdaAppflowExtensionStack(app, "ada-appflow-extension") 12 | template = assertions.Template.from_stack(stack) 13 | 14 | 15 | # template.has_resource_properties("AWS::SQS::Queue", { 16 | # "VisibilityTimeout": 300 17 | # }) 18 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from os import getenv 3 | 4 | import aws_cdk as cdk 5 | from ada_appflow_extension.ada_appflow_extension_stack import AdaAppflowExtensionStack 6 | from cdk_nag import AwsSolutionsChecks, NagSuppressions, NagPackSuppression 7 | 8 | app = cdk.App() 9 | ada_appflow_extension_stack = AdaAppflowExtensionStack( 10 | app, 11 | app.node.try_get_context("stack-name"), 12 | env=cdk.Environment( 13 | region=getenv("AWS_REGION", getenv("CDK_DEFAULT_REGION")), 14 | account=getenv("AWS_ACCOUNT_ID", getenv("CDK_DEFAULT_ACCOUNT")), 15 | ), 16 | description="AppFlow extension stack for ADA (uksb-xxxx) ", 17 | ) 18 | 19 | tags = { 20 | "SolutionName": "ADAAppFlowExtension", 21 | "SolutionVersion": "v1.0.0", 22 | "SolutionIaC": "CDK v2", 23 | } 24 | 25 | for k, v in tags.items(): 26 | cdk.Tags.of(ada_appflow_extension_stack).add(k, v) 27 | 28 | # cdk-nag checks 29 | nag_suppressions = [ 30 | {"id":"AwsSolutions-SMG4", "reason":"ADA api key stored in secrets manager, does not require automatic rotation."}, 31 | {"id":"AwsSolutions-DDB3", "reason":"DynamoDB table is used as metadata store, does not need PITR."}, 32 | {"id":"AwsSolutions-IAM4", "reason":"AWSLambdaBasicExecutionRole is restrictive role."}, 33 | {"id":"AwsSolutions-IAM5", "reason":"S3 permissions are specific to bucket policy only and are required for the solution."} 34 | ] 35 | for supression in nag_suppressions: 36 | NagSuppressions.add_stack_suppressions(ada_appflow_extension_stack, [ 37 | NagPackSuppression( 38 | id=supression["id"], 39 | reason=supression["reason"] 40 | ) 41 | ]) 42 | cdk.Aspects.of(app).add(AwsSolutionsChecks(verbose=True)) 43 | 44 | app.synth() 45 | -------------------------------------------------------------------------------- /cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "python3 app.py", 3 | "watch": { 4 | "include": [ 5 | "**" 6 | ], 7 | "exclude": [ 8 | "README.md", 9 | "cdk*.json", 10 | "requirements*.txt", 11 | "source.bat", 12 | "**/__init__.py", 13 | "python/__pycache__", 14 | "tests" 15 | ] 16 | }, 17 | "context": { 18 | "@aws-cdk/aws-lambda:recognizeLayerVersion": true, 19 | "@aws-cdk/core:checkSecretUsage": true, 20 | "@aws-cdk/core:target-partitions": [ 21 | "aws", 22 | "aws-cn" 23 | ], 24 | "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true, 25 | "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true, 26 | "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true, 27 | "@aws-cdk/aws-iam:minimizePolicies": true, 28 | "@aws-cdk/core:validateSnapshotRemovalPolicy": true, 29 | "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true, 30 | "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true, 31 | "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true, 32 | "@aws-cdk/aws-apigateway:disableCloudWatchRole": true, 33 | "@aws-cdk/core:enablePartitionLiterals": true, 34 | "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true, 35 | "@aws-cdk/aws-iam:standardizedServicePrincipals": true, 36 | "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true, 37 | "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true, 38 | "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true, 39 | "@aws-cdk/aws-route53-patters:useCertificate": true, 40 | "@aws-cdk/customresources:installLatestAwsSdkDefault": false, 41 | "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true, 42 | "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true, 43 | "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true, 44 | "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true, 45 | "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true, 46 | "@aws-cdk/aws-redshift:columnId": true, 47 | "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true, 48 | "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true, 49 | "@aws-cdk/aws-apigateway:requestValidatorUniqueId": true, 50 | "@aws-cdk/aws-kms:aliasNameRef": true, 51 | "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true, 52 | "@aws-cdk/core:includePrefixInUniqueNameGeneration": true, 53 | "@aws-cdk/aws-efs:denyAnonymousAccess": true, 54 | "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true, 55 | "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true, 56 | "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true, 57 | "stack-name": "ada-appflow-extension" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /lambdas/trigger_ada_data_update/lambda_function.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | from os import getenv 4 | 5 | import requests 6 | import boto3 7 | from botocore.exceptions import ClientError 8 | 9 | ADA_API_BASE_URL = getenv("ADA_API_BASE_URL").rstrip("/") 10 | ADA_API_KEY_SECRET_NAME = getenv("ADA_API_KEY_SECRET_NAME") 11 | ADA_DOMAIN_NAME = getenv("ADA_DOMAIN_NAME") 12 | ADA_API_TIMEOUT = 10 13 | 14 | logger = logging.getLogger() 15 | logger.setLevel(logging.INFO) 16 | 17 | secretsmanager_client = boto3.client("secretsmanager") 18 | 19 | def get_secret() -> str: 20 | """ 21 | Retrieves ADA API call from AWS Secrets Manager. 22 | 23 | :return: Secret string for ADA API key. 24 | """ 25 | try: 26 | get_secret_value_response = secretsmanager_client.get_secret_value( 27 | SecretId=ADA_API_KEY_SECRET_NAME 28 | ) 29 | secret = get_secret_value_response["SecretString"] 30 | except ClientError as e: 31 | logger.error(f"Failed to get secret value.\nError: {e}") 32 | raise e 33 | return secret 34 | 35 | def lambda_handler(event, context): 36 | """ 37 | Lambda function to trigger ADA API call to start data update. 38 | 39 | :param event: Event object. 40 | :param context: Context object. 41 | :return: Response object. 42 | """ 43 | 44 | logger.debug(f"Event: {event}") 45 | api_key = get_secret() 46 | flow_name = event["flow-name"] 47 | data_product_id = event["data_product_id"] 48 | url = f"{ADA_API_BASE_URL}/data-product/domain/{ADA_DOMAIN_NAME}/data-product/{data_product_id}" 49 | headers = { 50 | "Authorization": f"api-key {api_key}", 51 | "Content-Type": "application/json", 52 | "Accept": "*/*", 53 | "Accept-Encoding": "gzip, deflate, br", 54 | } 55 | try: 56 | r = requests.get(url, headers=headers, timeout=ADA_API_TIMEOUT) 57 | r.raise_for_status() 58 | if r.json()["dataStatus"] != "READY": 59 | logger.info( 60 | f"Data product not in READY state, cannot trigger data product update." 61 | ) 62 | return { 63 | "statusCode": 200, 64 | "body": { 65 | "request-type": "trigger-data-update", 66 | "trigger-data-update": "SKIPPED", 67 | "flow-name": flow_name, 68 | "data-product-id": data_product_id 69 | } 70 | } 71 | data_update_r = requests.put(f"{url}/start-data-update", headers=headers, timeout=ADA_API_TIMEOUT) 72 | data_update_r.raise_for_status() 73 | except requests.exceptions.RequestException as e: 74 | logger.error( 75 | f"Failed to trigger data update.\n Error: {e}" 76 | ) 77 | 78 | return { 79 | "statusCode": 200, 80 | "body": { 81 | "request-type": "trigger-data-update", 82 | "trigger-data-update": "DONE", 83 | "flow-name": flow_name, 84 | "data-product-id": data_product_id 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /lambdas/notify_user/lambda_function.py: -------------------------------------------------------------------------------- 1 | import json 2 | from os import getenv 3 | 4 | import boto3 5 | import logging 6 | 7 | ADA_NOTIFICATION_TOPIC_ARN = getenv("NOTIFICATION_TOPIC_ARN") 8 | 9 | logger = logging.getLogger() 10 | logger.setLevel(logging.INFO) 11 | 12 | sns_client = boto3.client("sns") 13 | 14 | def lambda_handler(event, context): 15 | """ 16 | Publish message to SNS topic for email notification. 17 | 18 | :param event: Output event from ADA data product create/update trigger step. 19 | :return: Publish call response. 20 | 21 | """ 22 | logger.debug(f"Event: {event}") 23 | try: 24 | info_text = f"""Data Product Id: {event['body']['data-product-id']} 25 | AppFlow Flow Name: {event['body']['flow-name']}\n 26 | Check ADA console for data product details. 27 | """ 28 | 29 | if event["body"]["request-type"] == "create-data-product": 30 | subject = "[ADA AppFlow Extension]Data product creation failed!" 31 | message = f"Failed to create data product for an AppFlow flow." 32 | 33 | if event["statusCode"] == 200: 34 | message = f"Successfully created data product for an AppFlow flow. Please find the details below:\n{info_text}" 35 | subject = "[ADA AppFlow Extension]Data product creation success!" 36 | 37 | elif event["body"]["request-type"] == "trigger-data-update": 38 | subject = "[ADA AppFlow Extension]Data product data-update failed!" 39 | message = f"Failed to trigger data product data-update for an AppFlow flow run." 40 | 41 | if event["statusCode"] == 200: 42 | if event["body"]["trigger-data-update"] == "SKIPPED": 43 | message = f"Skipped data product data-update for an AppFlow flow run as data-product is not in READY state. Please find the details below:\n{info_text}" 44 | subject = "[ADA AppFlow Extension]Data product data-update skipped!" 45 | else: 46 | message = f"Successfully triggered data product data-update for an AppFlow flow run. Please find the details below:\n{info_text}" 47 | subject = "[ADA AppFlow Extension]Data product data-update success!" 48 | else: 49 | logger.error( 50 | f"Invalid request type: {event['body']['request-type']}" 51 | ) 52 | return { 53 | "statusCode": 400, 54 | "body": "Invalid request type." 55 | } 56 | response = sns_client.publish( 57 | TopicArn = ADA_NOTIFICATION_TOPIC_ARN, 58 | Message = message, 59 | Subject = subject 60 | ) 61 | except KeyError as keyerr: 62 | logger.error( 63 | f"Missing data product info. KeyError: {keyerr}" 64 | ) 65 | return { 66 | "statusCode": 400, 67 | "error": f"[KeyError]Missing key: {str(keyerr)}" 68 | } 69 | except Exception as e: 70 | logger.error( 71 | f"Failed to publish message to SNS topic. Error: {e}" 72 | ) 73 | 74 | return { 75 | "statusCode": 200, 76 | "body": response 77 | } 78 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /lambdas/update_flow_metadata/lambda_function.py: -------------------------------------------------------------------------------- 1 | """This lambda function is invoked as part of step function workflow. 2 | This lambda function receives the flow events from Appflow and checks whether data 3 | product exists for this flow or not and inserts the flow information into MetaData Store. 4 | """ 5 | import logging 6 | import os 7 | 8 | import boto3 9 | from botocore.exceptions import ClientError 10 | 11 | dynamodb = boto3.resource("dynamodb") 12 | logger = logging.getLogger() 13 | logger.setLevel(logging.INFO) 14 | 15 | 16 | def lambda_handler(event, context): 17 | """ 18 | Entry point for lambda function. 19 | 20 | :return: flow and existing data product information in a json. 21 | """ 22 | return update_flow_metadata(event) 23 | 24 | 25 | def update_flow_metadata(event): 26 | """ 27 | Validates whether data product exists and inserts/updates the flow information into MetaData store. 28 | 29 | :return: flow information along with data product exists or not. 30 | """ 31 | logging.info("[Start] - update flow metadata") 32 | detail = event["detail"] 33 | flow_name = detail["flow-name"] 34 | table_name = os.environ["FLOW_METADATA_TABLE_NAME"] 35 | flow_table = dynamodb.Table(table_name) 36 | is_data_product_exists = False 37 | data_product_id = None 38 | 39 | try: 40 | response = flow_table.get_item(Key={"flow-name": flow_name}) 41 | except ClientError as e: 42 | logging.error( 43 | e.response["Error while retrieving flow information from DynamoDB"] 44 | ) 45 | else: 46 | if "Item" in response: 47 | logging.info("Flow information exists in Metadata store !") 48 | 49 | if "data-product-info" in response["Item"]: 50 | logging.info("Data product information exists in Metadata store !") 51 | 52 | if response["Item"]["data-product-info"]["id"] is not None: 53 | is_data_product_exists = True 54 | data_product_id = response["Item"]["data-product-info"]["id"] 55 | bucket_name, key = read_bucket_name_and_key( 56 | detail["flow-name"], detail["destination-object"] 57 | ) 58 | destination_details = {"bucket": bucket_name, "key": key} 59 | else: 60 | logging.info("Flow information does not exist in Metadata store !") 61 | 62 | item = persist_flow_information(detail, flow_table) 63 | destination_details = item["destination-details"] 64 | 65 | logging.info("[End] - update flow metadata") 66 | return { 67 | "data_product_exists": is_data_product_exists, 68 | "data_product_id": data_product_id, 69 | "flow-name": flow_name, 70 | "destination-details": destination_details, 71 | } 72 | 73 | 74 | def persist_flow_information(detail, flow_table): 75 | """ 76 | Prepare the flow object and persists flow object into DynamoDB. 77 | 78 | :return: flow object which has been persisted into DynamoDB 79 | """ 80 | logging.info("[Start] - persist flow information in DynamoDB") 81 | bucket_name, key = read_bucket_name_and_key( 82 | detail["flow-name"], detail["destination-object"] 83 | ) 84 | item = { 85 | "flow-name": detail["flow-name"], 86 | "flow-arn": detail["flow-arn"], 87 | "source": detail["source"], 88 | "destination": detail["destination"], 89 | "source-object": detail["source-object"], 90 | "destination-details": {"bucket": bucket_name, "key": key}, 91 | "trigger-type": detail["trigger-type"], 92 | "status": detail["status"], 93 | } 94 | flow_table.put_item(Item=item) 95 | logging.info("[End] - persist flow information in DynamoDB") 96 | return item 97 | 98 | 99 | def read_bucket_name_and_key(flow_name, destination_object): 100 | """ 101 | Extracts the S3 bucket name and key from the flow info contained in the event 102 | 103 | :return: key from destination S3 bucket.If destination S3 bucket does not have a key, then returns empty string 104 | """ 105 | if "s3://" not in destination_object: 106 | raise Exception("Destination object is not an S3 URI") 107 | path_parts = destination_object.replace("s3://", "").split("/") 108 | bucket = path_parts.pop(0) 109 | key = "/".join(path_parts) 110 | key = flow_name if key == "" else f"{key}/{flow_name}" 111 | return bucket, key 112 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Automated Data Analytics(ADA) Amazon AppFlow Extension 3 | 4 | [Automated Data Analytics(ADA)](https://aws.amazon.com/solutions/implementations/automated-data-analytics-on-aws/) on AWS enables customers to derive meaningful insights from data in a matter of minutes through a simple and intuitive user interface. ADA currently supports multiple source types such as CSV files, [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) bucket, [Amazon DynamoDB](https://aws.amazon.com/dynamodb/), [Amazon Kinesis Data Streams](https://aws.amazon.com/kinesis/data-streams/) and various others. 5 | [Amazon AppFlow](https://aws.amazon.com/appflow/) is an integration service that enables you to securely transfer data between SaaS applications and AWS services without code. 6 | The ADA Extension streamlines the integration process, making it easy to connect ADA with a multitude of external SaaS data sources through Amazon AppFlow. This connection allows for the automatic retrieval and integration of data, eliminating the need for users to manually configure data flows within ADA. 7 | 8 | This extension leverages [Amazon EventBridge](https://aws.amazon.com/eventbridge/), [AWS Lambda](https://aws.amazon.com/lambda/) and [AWS Step Functions](https://aws.amazon.com/step-functions/) to orchestrate ADA data-product creation for a source AppFlow flow by consuming flow execution events. 9 | When an AppFlow flow execution with destination S3 ends succesfully, the event will trigger step function state machine. The state machine will create the respective ADA data-product. If the data-product already exists, the extension will trigger data update start for the respective data-product. 10 | The metadata of the execution and the events will be stored in a DynamoDB table for tracing and debugging purposes. 11 | Once the data-product creation/data update is completed, a notification email will be sent. You can set the notification email when deploying the extension. 12 | 13 | The following illustrates the state machine definition for better comprehension: 14 | ![State Machine Definition](images/ada-appflow-extension-sm-def-flow.png) 15 | 16 | The extension only supports AppFlow flow where the destination is a S3 bucket. In ADA, a data-product with S3 as source will be created. If the flow destination is some other data source, the event notification will be skipped and no ADA data-product will be created. 17 | 18 | The extension also supports exisiting (at the time of extension deployment) AppFlow flows where the destination is a S3 bucket. When deploying the solution, a Lambda function will list and filter all the target flows and trigger the state machine to create respective ADA data-products. 19 | 20 | ## Solution Architecture 21 | 22 | ![Architecture](images/ada-appflow-extension-arch-diagram.png "Architecture") 23 | 24 | The primary components of the extension's architecture are: 25 | - Amazon EventBridge events for `AppFlow End Flow Run Report` with `destination: S3` and `status: Execution Successful`. 26 | - AWS Lambda functions for interacting with ADA APIs. 27 | - AWS Step Functions for orchestrating the Lambda functions and Amazon DynamoDB for storing metadata. 28 | - [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) for storing ADA API Key secret. 29 | - [Amazon Simple Notification Service](https://aws.amazon.com/sns/) for sending email notification about the extension execution. 30 | 31 | > NOTE: Please follow security best practices to handle PII data, if present in the flow destination bucket. 32 | 33 | ## Pre-requisites 34 | 35 | - [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/v2/guide/home.html) version 2.100.0 or higher. 36 | - Docker version 1.41 or higher. 37 | - [ADA APIs Access](https://docs.aws.amazon.com/solutions/latest/automated-data-analytics-on-aws/access-the-ada-apis.html) 38 | 39 | ## Deployment 40 | 41 | Deploy the stack 42 | ``` 43 | cdk deploy \ 44 | --parameters AdaApiBaseUrl= \ 45 | --parameters AdaApiKey= \ 46 | --parameters AdaAccountId= \ 47 | --parameters AdaAppflowExtDomainName= \ 48 | --parameters AdaAppflowExtUserGroupName= \ 49 | --parameters AdaAppflowExtNotificationEmail= 50 | ``` 51 | This will deploy all the required services and execute a Lambda function to create ADA data-products for existing AppFlow flows. 52 | 53 | ## Security 54 | 55 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 56 | 57 | ## License 58 | 59 | This library is licensed under the Apache 2.0 License. See the LICENSE file. 60 | -------------------------------------------------------------------------------- /tests/unit/test_update_flow_metadata.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import boto3 4 | import moto 5 | import pytest 6 | 7 | from lambdas.update_flow_metadata import lambda_function 8 | 9 | TABLE_NAME = "flow_info_mock" 10 | 11 | 12 | @pytest.fixture 13 | def lambda_environment(): 14 | os.environ["FLOW_METADATA_TABLE_NAME"] = TABLE_NAME 15 | 16 | 17 | @pytest.fixture 18 | def sample_flow_run_complete_event(): 19 | return { 20 | "version": "0", 21 | "id": "febf499e-03d1-4878-8ef8-6cc73fa7fdty", 22 | "detail-type": "AppFlow End Flow Run Report", 23 | "source": "aws.appflow", 24 | "account": "1234567890xx", 25 | "time": "2023-08-29T12:55:32Z", 26 | "region": "eu-west-1", 27 | "resources": ["bd3275d267f032646f926d73a98d12c2"], 28 | "detail": { 29 | "flow-name": "test", 30 | "created-by": "arn:aws:sts::123456789:assumed-role/ABC/ABC-ROLE", 31 | "flow-arn": "arn:aws:appflow:eu-west-1:1234567890xx:flow/test", 32 | "source": "S3", 33 | "destination": "S3", 34 | "source-object": "s3://appflow-input-test-bucket/input", 35 | "destination-object": "s3://appflow-output-test-bucket/input", 36 | "trigger-type": "ONDEMAND", 37 | "num-of-records-processed": "63000", 38 | "execution-id": "2c07e424-21e4-4ee3-b70f-4fb55b2ecf79", 39 | "num-of-records-filtered": "0", 40 | "start-time": "2023-08-29T12:55:23.835Z[UTC]", 41 | "num-of-documents-processed": "0", 42 | "end-time": "2023-08-29T12:55:32.049Z[UTC]", 43 | "num-of-record-failures": "0", 44 | "data-processed": "10226699", 45 | "status": "Execution Successful", 46 | }, 47 | } 48 | 49 | 50 | @pytest.fixture 51 | def metadata_table(): 52 | with moto.mock_dynamodb(): 53 | dynamodb = boto3.resource("dynamodb") 54 | table = dynamodb.create_table( 55 | TableName=TABLE_NAME, 56 | AttributeDefinitions=[{"AttributeName": "flow-name", "AttributeType": "S"}], 57 | KeySchema=[{"AttributeName": "flow-name", "KeyType": "HASH"}], 58 | ProvisionedThroughput={"ReadCapacityUnits": 10, "WriteCapacityUnits": 10}, 59 | ) 60 | table.wait_until_exists() 61 | yield TABLE_NAME 62 | 63 | 64 | @pytest.fixture 65 | def metadata_table_with_data_product_exists(metadata_table): 66 | table = boto3.resource("dynamodb").Table(metadata_table) 67 | sample_item_with_data_product = { 68 | "flow-name": "test", 69 | "flow-arn": "arn:aws:appflow:eu-west-1:1234567890xx:flow/test", 70 | "source": "S3", 71 | "destination": "S3", 72 | "source-object": "s3://appflow-input-test-bucket/input", 73 | "destination-details": { 74 | "bucket": "appflow-output-test-bucket", 75 | "key": "input-key", 76 | }, 77 | "trigger-type": "ONDEMAND", 78 | "start-time": "2023-08-29T12:55:23.835Z[UTC]", 79 | "end-time": "2023-08-29T12:55:32.049Z[UTC]", 80 | "status": "Execution Successful", 81 | "data-product-info": { 82 | "id": "12345", 83 | "created-time": "", 84 | "updated-time": "", 85 | "domain-id": "ABCD", 86 | }, 87 | } 88 | table.put_item(Item=sample_item_with_data_product) 89 | 90 | 91 | # Test 1 - testing a valid S3 URI with bucket name and key 92 | def test_read_bucket_name_and_key_with_key(): 93 | flow_name = "Test" 94 | destination_object = "s3://appflow-output-test-bucket/dummy-key" 95 | bucket_name, key = lambda_function.read_bucket_name_and_key( 96 | flow_name, destination_object 97 | ) 98 | assert bucket_name == "appflow-output-test-bucket" 99 | assert key == "dummy-key/Test" 100 | 101 | 102 | # Test 2 - testing a valid S3 URI with bucket name and no key present 103 | def test_read_bucket_name_and_key_without_key(): 104 | flow_name = "Test" 105 | destination_object = "s3://appflow-output-test-bucket" 106 | bucket_name, key = lambda_function.read_bucket_name_and_key( 107 | flow_name, destination_object 108 | ) 109 | assert bucket_name == "appflow-output-test-bucket" 110 | assert key == flow_name 111 | 112 | 113 | # Test 3 - testing a valid S3 URI with bucket name and key being multiple folders 114 | def test_read_bucket_name_and_key_with_multi_folder_key(): 115 | flow_name = "Test" 116 | destination_object = ( 117 | "s3://appflow-output-test-bucket/dummy-folder-1/dummy-folder-2/dummy-folder-3" 118 | ) 119 | bucket_name, key = lambda_function.read_bucket_name_and_key( 120 | flow_name, destination_object 121 | ) 122 | assert bucket_name == "appflow-output-test-bucket" 123 | assert key == "dummy-folder-1/dummy-folder-2/dummy-folder-3/Test" 124 | 125 | 126 | # Test 4 - testing an invalid URI not being an S3 URI 127 | def test_read_bucket_name_and_key_with_invalid_s3_uri(): 128 | flow_name = "Test" 129 | destination_object = "invalid-s3-uri" 130 | with pytest.raises(Exception): 131 | lambda_function.read_bucket_name_and_key(flow_name, destination_object) 132 | 133 | 134 | # Test 5 - testing the lambda function with a sample event, where flow does not exist 135 | def test_update_flow_metadata_with_no_flow_exists( 136 | lambda_environment, sample_flow_run_complete_event, metadata_table 137 | ): 138 | response = lambda_function.update_flow_metadata(sample_flow_run_complete_event) 139 | assert response["data_product_exists"] is False 140 | assert response["data_product_id"] is None 141 | 142 | 143 | # Test 6 - testing the lambda function with a sample event, where flow already exists with associated data product 144 | def test_update_flow_metadata_with_flow_and_data_product_exists( 145 | lambda_environment, 146 | sample_flow_run_complete_event, 147 | metadata_table_with_data_product_exists, 148 | ): 149 | response = lambda_function.update_flow_metadata(sample_flow_run_complete_event) 150 | assert response["data_product_exists"] is True 151 | assert response["data_product_id"] == "12345" 152 | -------------------------------------------------------------------------------- /lambdas/existing_flow_handler_cr/lambda_function.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | from os import getenv 4 | 5 | import boto3 6 | import requests 7 | from botocore.exceptions import ClientError 8 | from requests.adapters import HTTPAdapter, Retry 9 | 10 | ADA_API_BASE_URL = getenv("ADA_API_BASE_URL").rstrip("/") 11 | ADA_API_KEY_SECRET_NAME = getenv("ADA_API_KEY_SECRET_NAME") 12 | ADA_DOMAIN_NAME = getenv("ADA_DOMAIN_NAME") 13 | ADA_USER_GROUP_NAME = getenv("ADA_USER_GROUP_NAME") 14 | STATE_MACHINE_ARN = getenv("STATE_MACHINE_ARN") 15 | ADA_API_TIMEOUT = 60 16 | 17 | logger = logging.getLogger() 18 | logger.setLevel(logging.INFO) 19 | 20 | appflow_client = boto3.client("appflow") 21 | secretsmanager_client = boto3.client("secretsmanager") 22 | sfn_client = boto3.client("stepfunctions") 23 | 24 | # requests session 25 | session = requests.Session() 26 | retries = Retry(total=5, backoff_factor=1, status_forcelist=[400, 500, 502, 503, 504]) 27 | session.mount("https://", HTTPAdapter(max_retries=retries)) 28 | 29 | 30 | def get_secret() -> str: 31 | """ 32 | Retrieves ADA API call from AWS Secrets Manager. 33 | 34 | :return: Secret string for ADA API key. 35 | """ 36 | try: 37 | get_secret_value_response = secretsmanager_client.get_secret_value( 38 | SecretId=ADA_API_KEY_SECRET_NAME 39 | ) 40 | secret = get_secret_value_response["SecretString"] 41 | except ClientError as e: 42 | logger.error(f"Failed to get secret value.\nError: {e}") 43 | raise e 44 | return secret 45 | 46 | 47 | def create_ada_domain(api_key: str) -> str: 48 | """ 49 | Calls ADA API for creating ADA Domain. 50 | 51 | :param api_key: Secret string for ADA API key. 52 | :return: ADA Domain object string. 53 | 54 | """ 55 | url = f"{ADA_API_BASE_URL}/data-product/domain/{ADA_DOMAIN_NAME}" 56 | headers = { 57 | "Authorization": f"api-key {api_key}", 58 | "Content-Type": "application/json", 59 | "Accept": "*/*", 60 | "Accept-Encoding": "gzip, deflate, br", 61 | } 62 | data = json.dumps( 63 | { 64 | "name": "ADA AppFlow Extension Domain", 65 | "description": "ADA domain for AppFlow extension", 66 | } 67 | ) 68 | try: 69 | check_domain = session.get(url, headers=headers, timeout=ADA_API_TIMEOUT) 70 | if check_domain.status_code == 404: 71 | create_domain = session.put(url, headers=headers, data=data, timeout=ADA_API_TIMEOUT) 72 | create_domain.raise_for_status() 73 | return create_domain.text 74 | elif check_domain.status_code == 200: 75 | logger.info(f"{ADA_DOMAIN_NAME} domain already exists.") 76 | return check_domain.text 77 | else: 78 | raise SystemExit(f'Failed to get ADA Domain.\nResponse"{check_domain.text}') 79 | except requests.exceptions.RequestException as e: 80 | logger.error(f"Failed to create ADA domain.\nError: {e}") 81 | raise e 82 | 83 | 84 | def create_ada_user_group(api_key: str) -> str: 85 | """ 86 | Calls ADA API for creating ADA User Group. 87 | 88 | :param api_key: Secret string for ADA API key. 89 | :return: ADA User Group object string. 90 | 91 | """ 92 | url = f"{ADA_API_BASE_URL}/identity/group/{ADA_USER_GROUP_NAME}" 93 | headers = { 94 | "Authorization": f"api-key {api_key}", 95 | "Content-Type": "application/json", 96 | "Accept": "*/*", 97 | "Accept-Encoding": "gzip, deflate, br", 98 | } 99 | data = json.dumps( 100 | { 101 | "description": "ADA AppFlow extension user group", 102 | "apiAccessPolicyIds": ["default", "manage_data_products"], 103 | "claims": [], 104 | "members": [], 105 | } 106 | ) 107 | try: 108 | check_usergroup = session.get(url, headers=headers, timeout=ADA_API_TIMEOUT) 109 | if check_usergroup.status_code == 404: 110 | create_usergroup = session.put(url, headers=headers, data=data, timeout=ADA_API_TIMEOUT) 111 | create_usergroup.raise_for_status() 112 | return create_usergroup.text 113 | elif check_usergroup.status_code == 200: 114 | logger.info(f"{ADA_USER_GROUP_NAME} user group already exists.") 115 | return check_usergroup.text 116 | else: 117 | raise SystemExit( 118 | f'Failed to get ADA usergroup.\nResponse"{check_usergroup.text}' 119 | ) 120 | except requests.exceptions.RequestException as e: 121 | logger.error(f"Failed to create ADA user group.\nError: {e}") 122 | raise e 123 | 124 | 125 | def get_flows() -> list: 126 | """ 127 | Calls AppFlow API for listing flows. 128 | 129 | :return: List of existing flows. 130 | """ 131 | try: 132 | response = appflow_client.list_flows() 133 | flows = response["flows"] 134 | # custom loop as paginator not supported 135 | while "NextToken" in response: 136 | response = appflow_client.list_flows(NextToken=response["NextToken"]) 137 | flows.extend(response["flows"]) 138 | logger.debug(f"Existing flows: {flows}") 139 | 140 | target_flows = [] 141 | for flow in flows: 142 | if ( 143 | flow["destinationConnectorType"] == "S3" 144 | and flow["flowStatus"] == "Active" 145 | ): 146 | flow_detail = appflow_client.describe_flow(flowName=flow["flowName"]) 147 | flow_name = flow_detail["flowName"] 148 | destination_bucket_name = flow_detail["destinationFlowConfigList"][0][ 149 | "destinationConnectorProperties" 150 | ]["S3"]["bucketName"] 151 | destination_bucket_prefix = flow_detail["destinationFlowConfigList"][0][ 152 | "destinationConnectorProperties" 153 | ]["S3"].get("bucketPrefix") 154 | if destination_bucket_prefix is None: 155 | destination_object = f"s3://{destination_bucket_name}" 156 | else: 157 | destination_object = f"s3://{destination_bucket_name}/{destination_bucket_prefix}" 158 | 159 | target_flow_detail = { 160 | "flow-name": flow_name, 161 | "flow-arn": flow_detail["flowArn"], 162 | "created-by": flow_detail["createdBy"], 163 | "trigger-type": flow_detail["triggerConfig"]["triggerType"], 164 | "status": flow_detail["flowStatus"], 165 | "source": flow_detail["sourceFlowConfig"]["connectorType"], 166 | "source-object": flow_detail.get("sourceFlowConfig", {}), 167 | "destination": flow_detail["destinationFlowConfigList"][0][ 168 | "connectorType" 169 | ], 170 | "destination-object": destination_object, 171 | } 172 | target_flows.append(target_flow_detail) 173 | logger.debug(f"Target existing flows detail: {target_flows}") 174 | 175 | except ClientError as e: 176 | logger.error(f"Failed to get AppFlow flows.\nError: {e}") 177 | raise e 178 | except KeyError as key_err: 179 | logger.error(f"Missing key.\nError: {key_err}") 180 | return target_flows 181 | 182 | 183 | def trigger_sm(flows: list) -> None: 184 | """ 185 | Triggers state machine execution for the list of flows. 186 | 187 | :param flows: List of flows. 188 | :return: None 189 | 190 | """ 191 | for flow in flows: 192 | flow_name = flow["flow-name"] 193 | logger.info(f"Triggering state machine execution for the flow: {flow_name}") 194 | input_doc = { 195 | "version": "0", 196 | "source": "ada-appflow-extension-cr", 197 | "detail": flow, 198 | } 199 | try: 200 | sm_response = sfn_client.start_execution( 201 | stateMachineArn=STATE_MACHINE_ARN, input=json.dumps(input_doc) 202 | ) 203 | except ClientError as e: 204 | logger.error( 205 | f"Failed to trigger state machine execution for the flow: {flow_name}. Error: {e}" 206 | ) 207 | logger.info( 208 | f"Successfully triggered state machine execution for the flow: {flow_name}" 209 | ) 210 | 211 | return 212 | 213 | 214 | def lambda_handler(event, context): 215 | if event["RequestType"] == "Create": 216 | api_key = get_secret() 217 | 218 | logger.info(f"Creating ADA Domain, domain_id:{ADA_DOMAIN_NAME}") 219 | ada_domain_response = create_ada_domain(api_key) 220 | logger.info( 221 | f"ADA domain created successfully.\nResponse: {ada_domain_response}" 222 | ) 223 | 224 | logger.info(f"Creating ADA User group, user_group_id:{ADA_USER_GROUP_NAME}") 225 | ada_user_group_response = create_ada_user_group(api_key) 226 | logger.info( 227 | f"ADA user group created successfully.\nResponse: {ada_user_group_response}" 228 | ) 229 | 230 | logger.info("Getting list of existing target AppFlow flows.") 231 | flows = get_flows() 232 | logger.info("Target AppFlow flows collected successfully.\nResponse: {flows}") 233 | 234 | logger.info( 235 | f"Triggering state machine for target flows, state_machine_arn: {STATE_MACHINE_ARN}" 236 | ) 237 | trigger_sm(flows) 238 | logger.info(f"State machine execution triggering complete successfully.") 239 | 240 | else: 241 | logger.info(f'Ignoring RequestType: {event["RequestType"]}.') 242 | 243 | return 244 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | <<<<<<< HEAD 176 | of your accepting any such warranty or additional liability. 177 | ======= 178 | of your accepting any such warranty or additional liability. 179 | >>>>>>> main 180 | -------------------------------------------------------------------------------- /lambdas/create_ada_dataproduct/lambda_function.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import datetime 3 | import json 4 | import logging 5 | from os import getenv 6 | 7 | import boto3 8 | import requests 9 | from botocore.exceptions import ClientError 10 | from requests.adapters import HTTPAdapter, Retry 11 | 12 | # Set environment variables 13 | ADA_ACCOUNT_ID = getenv("ADA_ACCOUNT_ID") 14 | ADA_API_BASE_URL = getenv("ADA_API_BASE_URL").rstrip("/") 15 | ADA_API_KEY_SECRET_NAME = getenv("ADA_API_KEY_SECRET_NAME") 16 | ADA_DOMAIN_NAME = getenv("ADA_DOMAIN_NAME") 17 | ADA_USER_GROUP_NAME = getenv("ADA_USER_GROUP_NAME") 18 | FLOW_METADATA_TABLE_NAME = getenv("FLOW_METADATA_TABLE_NAME") 19 | ADA_API_TIMEOUT = 60 20 | 21 | # Initialize the logger 22 | logger = logging.getLogger() 23 | logger.setLevel(logging.INFO) 24 | 25 | # Create AWS service clients 26 | ddb_client = boto3.client("dynamodb") 27 | sm_client = boto3.client("secretsmanager") 28 | s3_client = boto3.client('s3') 29 | 30 | # Create requests session with retry configuration 31 | session = requests.Session() 32 | retries = Retry( 33 | total=5, 34 | backoff_factor=1, 35 | status_forcelist=[ 36 | 400, 37 | 500, 38 | 502, 39 | 503, 40 | 504]) 41 | session.mount("https://", HTTPAdapter(max_retries=retries)) 42 | 43 | 44 | def set_bucket_policy(data_product_bucket: str) -> None: 45 | """ 46 | Calls S3 API to set bucket policy for ADA data access. 47 | 48 | :param data_product_bucket: The name of the data product bucket. 49 | """ 50 | logger.info("Setting bucket policy to allow ADA data access.") 51 | bucket_policy = { 52 | "Version": "2012-10-17", 53 | "Statement": [ 54 | { 55 | "Sid": "Grant Automated Data Analytics on AWS Group access in one of group", 56 | "Effect": "Allow", 57 | "Action": "s3:Get*", 58 | "Resource": f"arn:aws:s3:::{data_product_bucket}/*", 59 | "Principal": { 60 | "AWS": [f"arn:aws:iam::{ADA_ACCOUNT_ID}:root"] 61 | }, 62 | "Condition": { 63 | "ForAnyValue:StringLike": { 64 | "aws:PrincipalTag/ada:groups": ["*:power-user:*", f"*:{ADA_USER_GROUP_NAME}:*"] 65 | } 66 | } 67 | }, { 68 | "Sid": "Grant Automated Data Analytics on AWS Federated Query access", 69 | "Effect": "Allow", 70 | "Action": "s3:Get*", 71 | "Resource": f"arn:aws:s3:::{data_product_bucket}/*", 72 | "Principal": { 73 | "AWS": [f"arn:aws:iam::{ADA_ACCOUNT_ID}:root"] 74 | }, 75 | "Condition": { 76 | "StringEquals": { 77 | "aws:PrincipalTag/ada:service": "query" 78 | } 79 | } 80 | } 81 | ] 82 | } 83 | 84 | # Check for existing bucket policy and append new statements if policy 85 | # already exists 86 | try: 87 | existing_policy = s3_client.get_bucket_policy( 88 | Bucket=data_product_bucket) 89 | policy_document = json.loads(existing_policy['Policy']) 90 | for statement in bucket_policy["Statement"]: 91 | if statement not in policy_document["Statement"]: 92 | policy_document["Statement"].append(statement) 93 | except s3_client.exceptions.NoSuchBucketPolicy: 94 | policy_document = bucket_policy 95 | except ClientError as e: 96 | logger.error( 97 | f"Failed to check for existing bucket policy.\nError: {e}") 98 | raise e 99 | 100 | # Set bucket policy 101 | try: 102 | s3_client.put_bucket_policy( 103 | Bucket=data_product_bucket, 104 | Policy=json.dumps(policy_document)) 105 | except ClientError as e: 106 | logger.error(f"Failed to set bucket policy.\nError: {e}") 107 | raise e 108 | 109 | 110 | def get_secret() -> str: 111 | """ 112 | Retrieves ADA API call from AWS Secrets Manager. 113 | 114 | :return: Secret string for ADA API key. 115 | """ 116 | logger.info("Getting API key value for ADA connection.") 117 | try: 118 | get_secret_value_response = sm_client.get_secret_value( 119 | SecretId=ADA_API_KEY_SECRET_NAME 120 | ) 121 | if "SecretBinary" in get_secret_value_response: 122 | secret = base64.b64decode( 123 | get_secret_value_response["SecretBinary"]) 124 | elif "SecretString" in get_secret_value_response: 125 | secret = get_secret_value_response["SecretString"] 126 | else: 127 | raise ValueError("Secret value not found in response.") 128 | except ClientError as e: 129 | logger.error(f"Failed to get secret value.\nError: {e}") 130 | raise e 131 | else: 132 | logger.info("Successfully retrieved API key.") 133 | return secret 134 | 135 | 136 | def update_flow_item(data_product_id: str, flow_name: str) -> None: 137 | """ 138 | Updates flow item in Amazon DynamoDB to add information on ADA data product. 139 | 140 | :param data_product_id: Information on ADA data product to add to flow item. 141 | :param flow_name: Name of flow to update. 142 | """ 143 | logger.info("Adding ADA data product information to flow item.") 144 | data_product_info = { 145 | "id": {"S": data_product_id}, 146 | "created-time": {"S": datetime.datetime.now().isoformat()}, 147 | "domain-id": {"S": ADA_DOMAIN_NAME}, 148 | } 149 | 150 | try: 151 | ddb_client.update_item( 152 | TableName=FLOW_METADATA_TABLE_NAME, 153 | Key={"flow-name": {"S": flow_name}}, 154 | UpdateExpression="SET #dp = :d", 155 | ExpressionAttributeValues={":d": {"M": data_product_info}}, 156 | ExpressionAttributeNames={"#dp": "data-product-info"}, 157 | ReturnValues="NONE", 158 | ) 159 | logger.info( 160 | "Successfully added ADA data product information to flow item.") 161 | except ClientError as e: 162 | logger.error(f"Failed to get secret value.\nError: {e}") 163 | raise e 164 | 165 | 166 | def create_data_product( 167 | api_key: str, flow_name: str, data_product_bucket: str, data_product_key: str 168 | ) -> str: 169 | """ 170 | Calls ADA API for creation of new data product. 171 | 172 | :param api_key: Secret string for ADA API key. 173 | :param flow_name: Name of flow corresponding to data product. 174 | :param data_product_bucket: The name of the data product bucket. 175 | :param data_product_key: The name of the data product key. 176 | :return: ID of newly created ADA data product. 177 | """ 178 | logger.info("Creating ADA data product") 179 | data_product_id = f"ada_appflow_ext_{flow_name}" 180 | url = f"{ADA_API_BASE_URL}/data-product/domain/{ADA_DOMAIN_NAME}/data-product/{data_product_id}" 181 | headers = { 182 | "Authorization": f"api-key {api_key}", 183 | "Content-Type": "application/json", 184 | "Accept": "*/*", 185 | "Accept-Encoding": "gzip, deflate, br", 186 | } 187 | payload = json.dumps( 188 | { 189 | "name": data_product_id, 190 | "description": f"Data Product created by Ada AppFlow Extension for flow: {flow_name}", 191 | "sourceType": "S3", 192 | "sourceDetails": {"bucket": data_product_bucket, "key": data_product_key}, 193 | "transforms": [], 194 | "enableAutomaticPii": True, 195 | "updateTrigger": {"updatePolicy": "APPEND", "triggerType": "ON_DEMAND"}, 196 | "tags": [{"key": "appFlowExtension", "value": "1"}], 197 | } 198 | ) 199 | try: 200 | create_data_product = session.post( 201 | url, headers=headers, data=payload, timeout=ADA_API_TIMEOUT 202 | ) 203 | create_data_product.raise_for_status() 204 | except requests.exceptions.Timeout: 205 | logger.info( 206 | "ADA did not confirm start of data creation within timeout window. Running check if creation was still successfully launched.") 207 | if data_product_exists(api_key, data_product_id): 208 | logger.info( 209 | f"Successfully confirmed existence of ADA data product with id: {data_product_id}") 210 | return data_product_id 211 | else: 212 | logger.error("ADA data product creation was not successful.") 213 | raise Exception("Could not confirm ADA data product creation.") 214 | except requests.exceptions.RequestException as e: 215 | logger.error(f"Failed to create ADA data product.\nError: {e}") 216 | raise e 217 | else: 218 | logger.info( 219 | f"Successfully created ADA data product with id: {data_product_id}") 220 | return data_product_id 221 | 222 | 223 | def data_product_exists( 224 | api_key: str, data_product_id: str 225 | ) -> str: 226 | """ 227 | Calls ADA API to check if data product exists. 228 | 229 | :param api_key: Secret string for ADA API key. 230 | :param data_product_id: ID of ADA data product. 231 | :return: True if the data product exists (status code is 200), False otherwise. 232 | """ 233 | logger.info("Getting status of ADA data product") 234 | url = f"{ADA_API_BASE_URL}/data-product/domain/{ADA_DOMAIN_NAME}/data-product/{data_product_id}" 235 | headers = { 236 | "Authorization": f"api-key {api_key}", 237 | "Accept": "*/*", 238 | "Accept-Encoding": "gzip, deflate, br", 239 | } 240 | try: 241 | get_data_product = session.get( 242 | url, headers=headers, timeout=ADA_API_TIMEOUT 243 | ) 244 | status_code = get_data_product.status_code 245 | if status_code == 200: 246 | logger.info( 247 | f"Successfully verified existence of ADA data product: {data_product_id}") 248 | return True 249 | else: 250 | logger.info( 251 | f"ADA data product not found. Status code: {status_code}") 252 | return False 253 | except requests.exceptions.RequestException as e: 254 | logger.error(f"Failed to get ADA data product.\nError: {e}") 255 | raise e 256 | 257 | 258 | def delete_data_product_permissions(api_key, data_product_id) -> None: 259 | """ 260 | Calls ADA API to delete permissions for data product as a prerequisite to setting permissions for ADA_USER_GROUP_NAME. 261 | 262 | :param api_key: Secret string for ADA API key. 263 | :param data_product_id: ID of ADA data product to update. 264 | """ 265 | logger.info("Deleting ADA data product permissions.") 266 | url = f"{ADA_API_BASE_URL}/governance/policy/domain/{ADA_DOMAIN_NAME}/data-product/{data_product_id}" 267 | headers = { 268 | "Authorization": f"api-key {api_key}", 269 | "Content-Type": "application/json", 270 | "Accept": "*/*", 271 | "Accept-Encoding": "gzip, deflate, br", 272 | } 273 | try: 274 | delete_permissions = session.delete( 275 | url, headers=headers, timeout=ADA_API_TIMEOUT) 276 | if delete_permissions.status_code == 404: 277 | logger.info(f"No permissions to delete.") 278 | return 279 | delete_permissions.raise_for_status() 280 | logger.info("Successfully deleted ADA data product permissions.") 281 | except requests.exceptions.RequestException as e: 282 | logger.error( 283 | f"Failed to delete permissions for ADA data product.\nError: {e}") 284 | raise e 285 | 286 | 287 | def set_data_product_permissions(api_key, data_product_id) -> None: 288 | """ 289 | Calls ADA API to set ADA_USER_GROUP_NAME permissions for data product. 290 | 291 | :param api_key: Secret string for ADA API key. 292 | :param data_product_id: ID of ADA data product to update. 293 | """ 294 | logger.info( 295 | f"Updating ADA data product permissions to allow user group: {ADA_USER_GROUP_NAME}" 296 | ) 297 | url = f"{ADA_API_BASE_URL}/governance/policy/domain/{ADA_DOMAIN_NAME}/data-product/{data_product_id}" 298 | 299 | headers = { 300 | "Authorization": f"api-key {api_key}", 301 | "Content-Type": "application/json", 302 | "Accept": "*/*", 303 | "Accept-Encoding": "gzip, deflate, br", 304 | } 305 | payload = json.dumps( 306 | { 307 | "dataProductId": data_product_id, 308 | "domainId": ADA_DOMAIN_NAME, 309 | "permissions": { 310 | ADA_USER_GROUP_NAME: {"access": "FULL"}, 311 | "admin": {"access": "FULL"}, 312 | }, 313 | } 314 | ) 315 | 316 | try: 317 | set_permissions = session.put( 318 | url, headers=headers, data=payload, timeout=ADA_API_TIMEOUT) 319 | set_permissions.raise_for_status() 320 | logger.info("Successfully updated ADA data product permissions.") 321 | except requests.exceptions.RequestException as e: 322 | logger.error( 323 | f"Failed to set permissions for ADA data product.\nError: {e}") 324 | raise e 325 | 326 | 327 | def lambda_handler(event, context): 328 | flow_name = event["flow-name"] 329 | data_product_bucket = event["destination-details"]["bucket"] 330 | data_product_key = event["destination-details"]["key"] 331 | 332 | set_bucket_policy(data_product_bucket) 333 | api_key = get_secret() 334 | data_product_id = create_data_product( 335 | api_key, flow_name, data_product_bucket, data_product_key 336 | ) 337 | 338 | update_flow_item(data_product_id, flow_name) 339 | delete_data_product_permissions(api_key, data_product_id) 340 | set_data_product_permissions(api_key, data_product_id) 341 | 342 | return { 343 | "statusCode": 200, 344 | "body": { 345 | "request-type": "create-data-product", 346 | "data-product-id": data_product_id, 347 | "flow-name": flow_name, 348 | }, 349 | } 350 | -------------------------------------------------------------------------------- /ada_appflow_extension/ada_appflow_extension_stack.py: -------------------------------------------------------------------------------- 1 | from os import path 2 | 3 | from aws_cdk import ( 4 | Fn, 5 | Stack, 6 | Duration, 7 | CfnParameter, 8 | CustomResource, 9 | SecretValue, 10 | BundlingOptions, 11 | RemovalPolicy, 12 | aws_lambda as _lambda, 13 | aws_sns as sns, 14 | aws_sns_subscriptions as sns_subs, 15 | aws_logs as logs, 16 | aws_dynamodb as dynamodb, 17 | aws_stepfunctions as _aws_stepfunctions, 18 | aws_stepfunctions_tasks as _aws_stepfunctions_tasks, 19 | aws_events as events, 20 | aws_events_targets as events_targets, 21 | aws_iam as iam, 22 | aws_secretsmanager as secretsmanager, 23 | aws_kms as kms, 24 | custom_resources as cr, 25 | ) 26 | from constructs import Construct 27 | 28 | LAMBDA_DIR = path.join(path.dirname(path.realpath(__file__)), "..", "lambdas") 29 | 30 | 31 | class AdaAppflowExtensionStack(Stack): 32 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 33 | super().__init__(scope, construct_id, **kwargs) 34 | 35 | # Parameters 36 | 37 | # ADA API Base URL 38 | ada_api_base_url = CfnParameter( 39 | self, "AdaApiBaseUrl", type="String", description="Ada api base url" 40 | ).value_as_string 41 | 42 | # ADA API Key 43 | ada_api_key = CfnParameter( 44 | self, 45 | "AdaApiKey", 46 | type="String", 47 | description="Ada api access key", 48 | no_echo=True, 49 | ) 50 | 51 | # ADA Account Id 52 | ada_account_id = CfnParameter( 53 | self, 54 | "AdaAccountId", 55 | type="String", 56 | description="Ada account id", 57 | ).value_as_string 58 | 59 | # ADA AppFlow Extension Domain name 60 | ada_appflow_ext_domain_name = CfnParameter( 61 | self, 62 | "AdaAppflowExtDomainName", 63 | default="ada_appflow_extension_domain", 64 | min_length=3, 65 | max_length=255, 66 | allowed_pattern="^[a-z][a-z_0-9]*$", 67 | ).value_as_string 68 | 69 | # ADA AppFlow Extension User Group name 70 | ada_appflow_ext_usergroup_name = CfnParameter( 71 | self, 72 | "AdaAppflowExtUserGroupName", 73 | default="ada_appflow_extension_usergroup", 74 | min_length=3, 75 | max_length=100, 76 | allowed_pattern="^[a-z][a-z_0-9]*$", 77 | ).value_as_string 78 | 79 | # ADA AppFlow Extension Notification Email 80 | ada_appflow_ext_notification_email = CfnParameter( 81 | self, 82 | "AdaAppflowExtNotificationEmail", 83 | ).value_as_string 84 | 85 | # SNS AWS KMS key 86 | sns_aws_key = kms.Key.from_lookup( 87 | self, 88 | 'snsAwsKey', 89 | alias_name='alias/aws/sns' 90 | ) 91 | 92 | # ADA Api access key secret 93 | ada_api_key_secret = secretsmanager.Secret( 94 | self, 95 | "AdaApiKeySecret", 96 | secret_string_value=SecretValue.unsafe_plain_text( 97 | ada_api_key.value_as_string 98 | ), 99 | ) 100 | 101 | # Metadata DDB Table 102 | flow_metadata_table = dynamodb.Table( 103 | self, 104 | "AdaAppFlowExtensionFlowMetadataTable", 105 | partition_key=dynamodb.Attribute( 106 | name="flow-name", type=dynamodb.AttributeType.STRING 107 | ), 108 | removal_policy=RemovalPolicy.DESTROY 109 | ) 110 | flow_metadata_table_name = flow_metadata_table.table_name 111 | 112 | # Extension Notification topic 113 | notification_topic = sns.Topic( 114 | self, 115 | "AdaAppFlowExtensionNotificationTopic", 116 | display_name="ADA AppFlow Extension Notification", 117 | master_key=sns_aws_key 118 | ) 119 | notification_topic.add_subscription(sns_subs.EmailSubscription(email_address=ada_appflow_ext_notification_email)) 120 | 121 | 122 | # Lambda handler definitions 123 | 124 | # update-flow-metadata lambda 125 | update_flow_metadata_function = _lambda.Function( 126 | self, 127 | "updateFlowMetadataFunction", 128 | description="Update flow metadata function", 129 | handler="lambda_function.lambda_handler", 130 | runtime=_lambda.Runtime.PYTHON_3_11, 131 | timeout=Duration.seconds(300), 132 | code=_lambda.Code.from_asset(path.join(LAMBDA_DIR, "update_flow_metadata")), 133 | environment={ 134 | "FLOW_METADATA_TABLE_NAME": flow_metadata_table_name, 135 | "ADA_DOMAIN_NAME": ada_appflow_ext_domain_name, 136 | }, 137 | ) 138 | 139 | # create_ada_dataproduct lambda 140 | create_ada_dataproduct_function = _lambda.Function( 141 | self, 142 | "createAdaDataProductFunction", 143 | description="Create Ada data product function", 144 | handler="lambda_function.lambda_handler", 145 | runtime=_lambda.Runtime.PYTHON_3_11, 146 | timeout=Duration.seconds(300), 147 | code=_lambda.Code.from_asset( 148 | path.join(LAMBDA_DIR, "create_ada_dataproduct"), 149 | bundling=BundlingOptions( 150 | image=_lambda.Runtime.PYTHON_3_11.bundling_image, 151 | command=[ 152 | "bash", 153 | "-c", 154 | "pip install --no-cache -r requirements.txt -t /asset-output && cp -au . /asset-output", 155 | ], 156 | ), 157 | ), 158 | environment={ 159 | "ADA_API_BASE_URL": ada_api_base_url, 160 | "ADA_API_KEY_SECRET_NAME": ada_api_key_secret.secret_name, 161 | "ADA_ACCOUNT_ID": ada_account_id, 162 | "FLOW_METADATA_TABLE_NAME": flow_metadata_table_name, 163 | "ADA_DOMAIN_NAME": ada_appflow_ext_domain_name, 164 | "ADA_USER_GROUP_NAME": ada_appflow_ext_usergroup_name, 165 | }, 166 | log_retention=logs.RetentionDays.ONE_YEAR, 167 | ) 168 | 169 | create_ada_dataproduct_function.add_to_role_policy( 170 | iam.PolicyStatement( 171 | effect=iam.Effect.ALLOW, 172 | actions=["s3:ListAllMyBuckets", "s3:GetBucketPolicy", "s3:PutBucketPolicy"], 173 | resources=["*"] 174 | ) 175 | ) 176 | 177 | # trigger_ada_data_update lambda 178 | trigger_ada_data_update_function = _lambda.Function( 179 | self, 180 | "triggerAdaDataUpdateFunction", 181 | description="Trigger Ada data update function", 182 | handler="lambda_function.lambda_handler", 183 | runtime=_lambda.Runtime.PYTHON_3_11, 184 | timeout=Duration.seconds(300), 185 | code=_lambda.Code.from_asset( 186 | path.join(LAMBDA_DIR, "trigger_ada_data_update"), 187 | bundling=BundlingOptions( 188 | image=_lambda.Runtime.PYTHON_3_11.bundling_image, 189 | command=[ 190 | "bash", 191 | "-c", 192 | "pip install --no-cache -r requirements.txt -t /asset-output && cp -au . /asset-output", 193 | ], 194 | ), 195 | ), 196 | environment={ 197 | "ADA_API_BASE_URL": ada_api_base_url, 198 | "ADA_API_KEY_SECRET_NAME": ada_api_key_secret.secret_name, 199 | "FLOW_METADATA_TABLE_NAME": flow_metadata_table_name, 200 | "ADA_DOMAIN_NAME": ada_appflow_ext_domain_name, 201 | "ADA_USER_GROUP_NAME": ada_appflow_ext_usergroup_name, 202 | }, 203 | log_retention=logs.RetentionDays.ONE_YEAR, 204 | ) 205 | 206 | # notify_user lambda 207 | notify_user_function = _lambda.Function( 208 | self, 209 | "notifyUserFunction", 210 | handler="lambda_function.lambda_handler", 211 | description="Notify user function", 212 | runtime=_lambda.Runtime.PYTHON_3_11, 213 | timeout=Duration.seconds(300), 214 | code=_lambda.Code.from_asset(path.join(LAMBDA_DIR, "notify_user")), 215 | environment={ 216 | "FLOW_METADATA_TABLE_NAME": flow_metadata_table_name, 217 | "ADA_DOMAIN_NAME": ada_appflow_ext_domain_name, 218 | "ADA_USER_GROUP_NAME": ada_appflow_ext_usergroup_name, 219 | "NOTIFICATION_TOPIC_ARN": notification_topic.topic_arn 220 | }, 221 | log_retention=logs.RetentionDays.ONE_YEAR, 222 | ) 223 | 224 | # notification function permission for sns 225 | notification_topic.grant_publish(notify_user_function) 226 | 227 | # lambda permissions for ddb r/w 228 | for fn in ( 229 | update_flow_metadata_function, 230 | create_ada_dataproduct_function, 231 | trigger_ada_data_update_function, 232 | notify_user_function, 233 | ): 234 | flow_metadata_table.grant_read_write_data(fn) 235 | 236 | # lambda permissions for secret read 237 | for fn in create_ada_dataproduct_function, trigger_ada_data_update_function: 238 | ada_api_key_secret.grant_read(fn) 239 | 240 | # step function steps definition 241 | 242 | # update-flow-metadata step 243 | update_flow_metadata_step = _aws_stepfunctions_tasks.LambdaInvoke( 244 | self, 245 | "updateFlowMetadataStep", 246 | lambda_function=update_flow_metadata_function, 247 | output_path="$.Payload", 248 | ) 249 | 250 | # create-ada-dataproduct step 251 | create_ada_dataproduct_step = _aws_stepfunctions_tasks.LambdaInvoke( 252 | self, 253 | "createAdaDataProductStep", 254 | lambda_function=create_ada_dataproduct_function, 255 | output_path="$.Payload", 256 | ) 257 | 258 | # trigger-ada-data-product step 259 | trigger_ada_data_update_step = _aws_stepfunctions_tasks.LambdaInvoke( 260 | self, 261 | "triggerAdaDataUpdateStep", 262 | lambda_function=trigger_ada_data_update_function, 263 | output_path="$.Payload", 264 | ) 265 | 266 | # notify-user step 267 | notify_user_step = _aws_stepfunctions_tasks.LambdaInvoke( 268 | self, 269 | "notifyUserStep", 270 | lambda_function=notify_user_function, 271 | output_path="$.Payload", 272 | ) 273 | 274 | # succeed step 275 | succeed_step = _aws_stepfunctions.Succeed( 276 | self, "succeed", comment="Extension flow succeeded" 277 | ) 278 | 279 | # failed step 280 | failed_step = _aws_stepfunctions.Fail( 281 | self, "failed", comment="Extension flow failed" 282 | ) 283 | 284 | # step function chain 285 | chain = update_flow_metadata_step.next( 286 | _aws_stepfunctions.Choice(self, "dataProductExists?") 287 | .when( 288 | _aws_stepfunctions.Condition.boolean_equals( 289 | "$.data_product_exists", False 290 | ), 291 | create_ada_dataproduct_step.next(notify_user_step), 292 | ) 293 | .when( 294 | _aws_stepfunctions.Condition.boolean_equals( 295 | "$.data_product_exists", True 296 | ), 297 | trigger_ada_data_update_step.next(notify_user_step.next(succeed_step)), 298 | ) 299 | .otherwise(failed_step) 300 | ) 301 | 302 | # step function log group 303 | sm_log_group = logs.LogGroup( 304 | self, 305 | "AdaAppFlowExtensionStateMachineLogGroup", 306 | log_group_name=f'/aws/vendedlogs/states/AdaAppFlowExtSmLogGroup-{Fn.select(4, Fn.split("-", Fn.select(2, Fn.split("/", self.stack_id))))}', 307 | retention=logs.RetentionDays.ONE_YEAR, 308 | ) 309 | 310 | # step function state machine 311 | state_machine = _aws_stepfunctions.StateMachine( 312 | self, 313 | "AdaAppFlowExtensionStateMachine", 314 | definition_body=_aws_stepfunctions.DefinitionBody.from_chainable(chain), 315 | logs=_aws_stepfunctions.LogOptions( 316 | destination=sm_log_group, level=_aws_stepfunctions.LogLevel.ALL 317 | ), 318 | tracing_enabled=True, 319 | ) 320 | 321 | # existing-flow-handler custom-resource lambda 322 | existing_flow_handler_cr_function = _lambda.Function( 323 | self, 324 | "existingFlowHandlerCrFunction", 325 | description="Existing flow handler custom resource function", 326 | handler="lambda_function.lambda_handler", 327 | runtime=_lambda.Runtime.PYTHON_3_11, 328 | timeout=Duration.seconds(300), 329 | code=_lambda.Code.from_asset( 330 | path.join(LAMBDA_DIR, "existing_flow_handler_cr"), 331 | bundling=BundlingOptions( 332 | image=_lambda.Runtime.PYTHON_3_11.bundling_image, 333 | command=[ 334 | "bash", 335 | "-c", 336 | "pip install --no-cache -r requirements.txt -t /asset-output && cp -au . /asset-output", 337 | ], 338 | ), 339 | ), 340 | environment={ 341 | "ADA_API_BASE_URL": ada_api_base_url, 342 | "ADA_API_KEY_SECRET_NAME": ada_api_key_secret.secret_name, 343 | "ADA_DOMAIN_NAME": ada_appflow_ext_domain_name, 344 | "ADA_USER_GROUP_NAME": ada_appflow_ext_usergroup_name, 345 | "STATE_MACHINE_ARN": state_machine.state_machine_arn, 346 | }, 347 | log_retention=logs.RetentionDays.ONE_YEAR, 348 | ) 349 | 350 | # lambda permissions for secret read 351 | ada_api_key_secret.grant_read(existing_flow_handler_cr_function) 352 | 353 | # allow appflow access iam policy 354 | existing_flow_handler_cr_function.add_to_role_policy( 355 | iam.PolicyStatement( 356 | effect=iam.Effect.ALLOW, 357 | actions=["appflow:ListFlows", "appflow:DescribeFlow"], 358 | resources=["*"], 359 | ) 360 | ) 361 | 362 | # allow triggering state machine 363 | existing_flow_handler_cr_function.add_to_role_policy( 364 | iam.PolicyStatement( 365 | effect=iam.Effect.ALLOW, 366 | actions=["states:StartExecution"], 367 | resources=[state_machine.state_machine_arn], 368 | ) 369 | ) 370 | 371 | # existing-flow-handler custom-resource provider 372 | existing_flow_handler_cr_provider = cr.Provider( 373 | self, 374 | "existingFlowHandlerCrProvider", 375 | on_event_handler=existing_flow_handler_cr_function, 376 | ) 377 | 378 | existing_flow_handler_cr = CustomResource( 379 | self, 380 | "existingFlowHandlerCr", 381 | service_token=existing_flow_handler_cr_provider.service_token, 382 | ) 383 | existing_flow_handler_cr.node.add_dependency(state_machine) 384 | 385 | # event rules 386 | 387 | # AppFlow flow run report rule: Flow with s3 destination ended successfully 388 | flow_run_report_rule = events.Rule( 389 | self, 390 | "FlowRunReportRule", 391 | event_pattern=events.EventPattern( 392 | source=["aws.appflow"], 393 | detail_type=["AppFlow End Flow Run Report"], 394 | detail={"destination": ["S3"], "status": ["Execution Successful"]}, 395 | ), 396 | ) 397 | 398 | # rule target 399 | flow_run_report_rule.add_target(events_targets.SfnStateMachine(state_machine)) 400 | --------------------------------------------------------------------------------