Enable CloudWatch logs in API GatewayV2 Stage with cloud formation - aws-cloudformation

There is a similar question but it does not use AWS::ApiGatewayV2::Stage, and I need the AutoDeploy that only the V2 seems to provide.
How do I enable CloudWatch logs and log full message data (as per the image) using CloudFormation in an AWS API Gateway?
I can't find anything at the documentation for the Stage
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html#cfn-apigatewayv2-stage-deploymentid
I am using an autodeployed stage. I am able to create the log groups, the IAM role to write logs in CloudWatch, but I can't enable the logging itself.
wsApiGateway:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: foo-ws-gateway
Description: Api Gateway for Websockets
ProtocolType: WEBSOCKET
RouteSelectionExpression: $request.body.action
DisableExecuteApiEndpoint: true # I use custom domain
# routes and integrations ommitted.
wsApiStage:
Type: AWS::ApiGatewayV2::Stage
DependsOn:
- wsConnectRoute
- wsSendRoute
- wsDisconnectRoute
Properties:
StageName: production
Description: Autodeploy in production
AutoDeploy: true
ApiId: !Ref wsApiGateway
AccessLogSettings:
DestinationArn: !GetAtt wsApiGatewayLogGroup.Arn
Format: '{"requestTime":"$context.requestTime","requestId":"$context.requestId","httpMethod":"$context.httpMethod","path":"$context.path","routeKey":"$context.routeKey","status":$context.status,"responseLatency":$context.responseLatency, "responseLength":$context.responseLength, "integrationError":$context.integration.error}'
I also had to go to ApiGateway previous version to define the Account so that I could specify the IAM role ARN that has write access to CloudWatch logs in the account (The section on Settings at,the console's API Gateway). It doesn't seem to have a AWS::ApiGateway2::Account.
apiGatewayAccountConfig:
Type: "AWS::ApiGateway::Account"
Properties:
CloudWatchRoleArn: !GetAtt apiGatewayWatchLogsRole.Arn

How do I enable CloudWatch logs and log full message data (as per the image) using CloudFormation in an AWS API Gateway?
You can't. Execution logs are not supported by HTTP API (i.e. ApiGatewayV2) as explained by AWS here:
HTTP APIs currently support access logging only, and logging setup is different for these APIs. For more information, see Configuring logging for an HTTP API.

Related

How to add lambda invoke role in custom authorizer of api gateway using serverless framework

I would like to add Lambda invoke role in custom authorizer for an api gateway using serverless framework.
events:
- http:
path: controls
method: GET
cors: ${self:custom.lambdaCORS}
authorizer:
arn: arn:aws:lambda:us-east-1:XYZ:function:SLS-XYZ
managedExternally: true
identitySource: method.request.header.x-api-key
resultTtlInSeconds: 0
type: request
Can someone help me in finding the property under authorizer to add "Lambda invoke role". I was able to do it manually from aws console. I am trying to access authorizer defined in other region. It seems API gateway needs a permission to invoke lambda authorizer in another region.
So the solution I was able to come up with was to add a specific permission to the generate API Gateway Cloudformation template.
The AWS docs outline what the Cloudformation template should look like to add a permission for API Gateway to access a lambda:
https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-rest-api-lambda-integrations/#To_add_Lambda_invoke_permission_to_a_REST_API_with_a_Lambda_integration_using_a_CloudFormation_template
So if you adapt that and add this block to the bottom of your serverless.yaml you should be able to access the Authorizer referenced by the FunctionName field!
resources:
Resources:
InvokeAuthorizerPermission:
Type: AWS::Lambda::Permission
Properties:
Action: "lambda:InvokeFunction"
FunctionName: ARN_OF_AUTHORIZER
Principal: "apigateway.amazonaws.com"
SourceArn: "arn:aws:execute-api:${aws:region}:${aws:accountId}:*/*/*/*"
Hope this helps another lost soul and I smashed my head up against this for a good long while!

how to restrict access to serverless api via resource policy?

a serverless api gateway stack built via cloudformation template ( see below) . I added a resource policy to whitelist a particular IP address. Does this block all other IP address, without specifying a black list or do I have add a IpRangeBlacklist values as well?
Resources:
serverlessapiGateway:
Type: AWS::Serverless::Api
Properties:
Auth:
ResourcePolicy:
IpRangeWhitelist:
- "10.20.30.40"
Verified, only list of IP under IpRangeWhitelist range are allowed. I wonder if there is a way to customize the error message we get, when not allowed.

GCP - How do you create a URL Redirect path rule with gcloud url-maps?

I want to create a GCP Load Balancer path redirect rule programatically using the gcloud tool.
As a test, I created one manually through the GCP Console web interface.
For my manually created rule, gcloud compute url-maps describe my-url-map returns something that looks like:
creationTimestamp: '2021-02-23T20:26:04.825-08:00'
defaultService: https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-backend-service
fingerprint: abcdefg=
hostRules:
- hosts:
- blah.my-site.com
pathMatcher: path-matcher-1
id: '12345678'
kind: compute#urlMap
name: my-url-map
pathMatchers:
- defaultService: https://www.googleapis.com/compute/v1/projects/my-project/global/backendServices/my-backend-service
name: path-matcher-1
pathRules:
- paths:
- /my-redirect-to-root
urlRedirect:
httpsRedirect: false
pathRedirect: /
redirectResponseCode: MOVED_PERMANENTLY_DEFAULT
stripQuery: false
selfLink: https://www.googleapis.com/compute/v1/projects/my-project/global/urlMaps/my-url-map
What I would like to do is to recreate the urlRedirect rule above (redirecting from /my-redirect-to-root to /), but using the gcloud tool.
Looking through the gcloud docs I can't seem to find anything referring to redirects. Is it that this is not possible to do via the gcloud tool? and if not, is there any other solution for creating these redirect rules programatically?
I'm basically trying to get around another GCP issue to do with GCS URLs for static websites by using Load Balancer redirects for each folder in our static site (~400 folders).
Currently Cloud SDK does not support creating url maps with redirects.
If you think that functionality should be available, you can create a Feature Request at Public Issue Tracker to have this option added in future.
For now, you can use API which allows creating url maps with redirects.

API: sqs:CreateQueue always ACCESS DENIED

I'm trying to create an sqs queue with cloudformation but I keep getting this error in the console.
API: sqs:CreateQueue Access to the resource https://sqs.us-east-1.amazonaws.com/ is denied.
Obviously I'm missing some sort of permission. This guide didn't really specify how I could resolve this.
Here's the code I made:
AWSTemplateFormatVersion: "2010-09-09"
Resources:
MyQueue:
Type: AWS::SQS::Queue
Properties:
FifoQueue: false
QueueName: sqs-test
ReceiveMessageWaitTimeSeconds: 20
RedrivePolicy:
deadLetterTargetArn:
Fn::GetAtt:
- "MyDLQ"
- "Arn"
maxReceiveCount: 4
Tags:
-
Key: "ProjectName"
Value: "project-x"
MyDLQ:
Type: AWS::SQS::Queue
Properties:
FifoQueue: false
QueueName: sqs-dlq-test
I'm trying to understand this doc. But I'm not sure how I could attach a policy to allow creation of queues. Someone please give me a full example.
tyron's comment on your question is spot on. Check permissions of the user executing the CloudFormation. If you're running commands directly, this is usually pretty easy to check. In some cases, you may be working with a more complicated environment with automation.
I find the best way to troubleshoot permissions in an automated world is via CloudTrail. After any API call has failed, whether from the CLI, CloudFormation, or another source, you can look up the call in CloudTrail.
In this case, searching for "Event Name" = "CreateQueue" in the time range of the failure will turn up a result with details like the following:
Source IP Address; this field may say something like cloudformation.amazonaws.com, or the IP of your machine/office. Helpful when you need to filter events based on the source.
User name; In my case, this was the EC2 instance ID of the agent running the CFN template.
Access Key ID; For EC2 instances, this is likely a set of temporary access credentials, but for a real user, it will show you what key was used.
Actual event data; Especially helpful for non-permissions errors, the actual event may show you errors in the request itself.
In my case, the specific EC2 instance that ran automation was out of date and needed to be updated to use the correct IAM Role/Instance Profile. CloudTrail helped me track that down.
If you are using AWS CodePipeline (where you may be using AWS CodeBuild to run & deploy your CloudFormation stack), remember your CodeBuild role (created under IAM Roles) must have the correct permissions.
You can identify which role is being used & attach required policies -
Open CodeBuild Project
Go to Build Details > Environment > Service Role
Open Service Role (hyperlinked)
Add SQS to role policies

How to get the auto generated RestApi from my AWS SAM template? To use in another SAM template

I used AWS SAM to generate my Lambda/APIs. But I want to be able to get this RestApi so I can use it in another SAM template.
The idea is to have 1 base infra CloudFormation/SAM template that creates the network, ALB, API Gateway things
Then each "micro-service" will have its own SAM template and it will create API endpoints referencing this "root" RestApi by specifying the RestApiId attribute
Is this a correct approach? Wonder if when I deploy each service, will it remove the APIs for the other services?
You can access default auto generated RestApi as ServerlessRestApi. This is logical resource id for auto generated RestApi resource.
ServerlessRestApi access example in template.yaml is as follows.
Outputs:
ApiRootURL:
Description: API Root URL
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/${ServerlessRestApi.Stage}"
You can see ServerlessRestApi in the resource list of you CloudFormation stack. ServerlessRestApi is not documented, so it might be changed in the future version.