Skip to content

Instantly share code, notes, and snippets.

@leandroribeiro
Created March 6, 2024 13:27
Show Gist options
  • Save leandroribeiro/0dcfaa96d32864a23611418f65a4e21e to your computer and use it in GitHub Desktop.
Save leandroribeiro/0dcfaa96d32864a23611418f65a4e21e to your computer and use it in GitHub Desktop.
Amazon CloudWatch Synthetics Canary - Cloud Formation Sample
CloudWatchSyntheticsRole:
Type: AWS::IAM::Role
Properties:
RoleName: ${self:service}-${self:provider.region}-ExecutionRole
Description: CloudWatch Synthetics lambda execution role for running canaries
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: ${self:service}-${self:provider.region}-ExecutionRolePolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:GetBucketLocation
Resource:
- "arn:aws:s3:::${self:custom.canariesResultsBucketName}/*"
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- arn:aws:logs:${self:provider.region}:${aws:accountId}:log-group:/aws/lambda/cwsyn-*
- Effect: Allow
Action:
- s3:ListAllMyBuckets
- xray:PutTraceSegments
Resource: '*'
- Effect: Allow
Resource: '*'
Action: cloudwatch:PutMetricData
Condition:
StringEquals:
cloudwatch:namespace: CloudWatchSynthetics
- Effect: Allow
Resource: '*'
Action:
- ec2:AttachNetworkInterface
- ec2:CreateNetworkInterface
- ec2:DescribeNetworkInterfaces
- ec2:DeleteNetworkInterface
- xray:PutTraceSegments
loginSyntheticsCanary:
Type: 'AWS::Synthetics::Canary'
Properties:
Name: ${self:custom.canaryLoginName} # máximo de 21 caracteres
ExecutionRoleArn: !Sub 'arn:aws:iam::${aws:accountId}:role/${CloudWatchSyntheticsRole}'
Code: {Handler: apiCanaryBlueprint.handler, Script: "const synthetics=require('Synthetics'),log=require('SyntheticsLogger'),syntheticsConfiguration=synthetics.getConfiguration(),apiCanaryBlueprint=async function(){syntheticsConfiguration.setConfig({restrictedHeaders:[],restrictedUrlParameters:[]});let e={hostname:'${self:custom.${self:custom.stage}.domainName}',method:'POST',path:'/auth/token',port:'443',protocol:'https:',body:'grant_type =client_credentials&client_id=fulano@demo.com&client_secret=fulano123',headers:{'Content-Type':'application/x-www-form-urlencoded'}};e.headers['User-Agent']=[synthetics.getCanaryUserAgentString(),e.headers['User-Agent']].join(' ');await synthetics.executeHttpStep('Verify Token Issuer',e,(async function(e){return new Promise(((t,n)=>{if(e.statusCode<200||e.statusCode>299)throw new Error(e.statusCode+' '+e.statusMessage);let s='';e.on('data',(e=>{s+=e})),e.on('end',(()=>{t()}))}))}),{includeRequestHeaders:!0,includeResponseHeaders:!0,includeRequestBody:!0,includeResponseBody:!0,continueOnHttpStepFailure:!0})};exports.handler=async()=>await apiCanaryBlueprint();"}
ArtifactS3Location: 's3://${self:custom.canariesResultsBucketName}'
RuntimeVersion: syn-nodejs-puppeteer-6.2
Schedule: {Expression: 'rate(1 hour)'}
RunConfig: {TimeoutInSeconds: 30}
FailureRetentionPeriod: 30
SuccessRetentionPeriod: 30
Tags: [{Key: application, Value: "${self:service}"},{Key: stage, Value: "${self:custom.stage}"}]
StartCanaryAfterCreation: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment