I'm looking for a tutorial/example of implementing a lambda -- Python runtime -- with access to the AppSync GraphQLAPI referenced inamplify_outputs.json. Can someone point me to a repo that demonstrates this functionality as part of the CI/CD pipeline while maintaining working sandbox apps? I've explored a lot of strategies and keep coming up short. My current understanding is that python runtimes are not supported for defineFunction, making environment variables and secrets challenging to pass to the lambda without a lot of custom parsing, permission settings, etc.
#Lambda with Python runtime and AppSync GraphQLApi access
3 messages · Page 1 of 1 (latest)
Update: I'm able to access environment variables and secrets from within my python lambda. These are included during the deployment pipeline by editing the amplify.yml at your project root:
phases:
build:
commands:
- export ENVIRONMENT="${AWS_BRANCH:-DEVELOPMENT}"
- npm ci --cache .npm --prefer-offline
- npx ampx pipeline-deploy --branch $AWS_BRANCH --app-id $AWS_APP_ID
- export GRAPHQL_API_URL=$(npx node-jq -r ".data.url" amplify_outputs.json)
- export GRAPHQL_API_KEY=$(npx node-jq -r ".data.api_key" amplify_outputs.json)
- export LAMBDA_NAME=$(npx node-jq -r ".custom.helloWorldLambdaName" amplify_outputs.json)
- export SECRET_NAME="GraphQLApiKey-${AWS_BRANCH:-UNKNOWN}"
- |
export UPDATED_ENV=$(npx node-jq -n -c \
--arg url "$GRAPHQL_API_URL" \
--arg branch "${AWS_BRANCH:-DEVELOPMENT}" \
'{"Variables": {"GRAPHQL_API_URL": $url, "ENVIRONMENT": $branch}}')
- |
aws lambda update-function-configuration \
--function-name "$LAMBDA_NAME" \
--environment "$UPDATED_ENV"
- |
aws secretsmanager create-secret \
--name $SECRET_NAME \
--secret-string "{\"api_key\": \"$GRAPHQL_API_KEY\"}" \
--region $AWS_REGION \
|| \
aws secretsmanager update-secret \
--secret-id $SECRET_NAME \
--secret-string "{\"api_key\": \"$GRAPHQL_API_KEY\"}" \
--region $AWS_REGION```
I then manually added inline permissions to access both lambda config and secrets to my `AmplifySSRLoggingRole` via the aws console. I'm not sure if this step can be automated. Now we'll see about what's needed to actually call the graphqlapi with the creds...any input/criticism is appreciated!
And here is accessing the secrets and environment variables from within the lambda. I append the branch name onto the secret so that sandbox environments can coexist with main/production:
import boto3
import json
def get_api_url():
api_url = os.getenv("GRAPHQL_API_URL")
if not api_url:
raise EnvironmentError("GRAPHQL_API_URL is not set. Check your deployment pipeline.")
return api_url
def get_api_key():
environment = os.getenv("ENVIRONMENT")
secrets_client = boto3.client('secretsmanager')
response = secrets_client.get_secret_value(SecretId=f"GraphQLApiKey-{environment}")
secret = json.loads(response['SecretString'])
return secret["api_key"]
def handler(event, context):
api_url = get_api_url()
api_key = get_api_key()
return {
'statusCode': 200,
'body': "Test"
}```