Question: How do I set up ExternalDNS with Amazon EKS?

I want to set up ExternalDNS with my Amazon Elastic Kubernetes Service (Amazon EKS).

Answer: "I want to set up ExternalDNS with my Amazon Elastic Kubernetes Service (Amazon EKS).Short descriptionExternalDNS is a pod that runs in your Amazon EKS cluster. To use ExternalDNS as a plugin with Amazon EKS, set up AWS Identity and Access Management (IAM) permissions. These permissions must allow Amazon EKS access to Amazon Route 53.Note: Before starting the following resolution, make sure that a domain name and a Route 53 hosted zone exist.ResolutionSet up IAM permissions and deploy ExternalDNS1.    Set up IAM permissions to give the ExternalDNS pod permissions to create, update, and delete Route 53 records in your AWS account.IAM policy:{  "Version": "2012-10-17",  "Statement": [    {      "Effect": "Allow",      "Action": [        "route53:ChangeResourceRecordSets"      ],      "Resource": [        "arn:aws:route53:::hostedzone/*"      ]    },    {      "Effect": "Allow",      "Action": [        "route53:ListHostedZones",        "route53:ListResourceRecordSets"      ],      "Resource": [        "*"      ]    }  ]}Note: You can also adjust the preceding policy to allow updates to explicit hosted zone IDs.2.    Use the preceding policy to create an IAM role for the service account:eksctl create iamserviceaccount --name SERVICE_ACCOUNT_NAME --namespace NAMESPACE --cluster CLUSTER_NAME --attach-policy-arn IAM_POLICY_ARN --approveNote: Replace SERVICE_ACCOUNT_NAME with your service account's name, NAMESPACE with your namespace, CLUSTER_NAME with your cluster's name, and IAM_POLICY_ARN with your IAM policy's ARN.To check the name of your service account, run the following command:kubectl get saExample output:NAME           SECRETS   AGEdefault        1         23hexternal-dns   1         23hIn the preceding example output, external-dns is the name that was given to the service account when it was created.3.    Deploy ExternalDNS.Check if RBAC is turned on in your Amazon EKS cluster:kubectl api-versions | grep rbac.authorization.k8s.ioNote: Before you apply the following manifests, check for the latest version of ExternalDNS (from the GitHub website).Run the following command:kubectl apply DEPLOYMENT_MANIFEST_FILE_NAME.yamlNote: Replace DEPLOYMENT_MANIFEST_FILE_NAME with your deployment manifest's file name.If RBAC is turned on, then use the following manifest to deploy ExternalDNS:apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolemetadata:  name: external-dnsrules:- apiGroups: [""]  resources: ["services","endpoints","pods"]  verbs: ["get","watch","list"]- apiGroups: ["extensions","networking.k8s.io"]  resources: ["ingresses"]  verbs: ["get","watch","list"]- apiGroups: [""]  resources: ["nodes"]  verbs: ["list","watch"]---apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata:  name: external-dns-viewerroleRef:  apiGroup: rbac.authorization.k8s.io  kind: ClusterRole  name: external-dnssubjects:- kind: ServiceAccount  name: external-dns  namespace: default---apiVersion: apps/v1kind: Deploymentmetadata:  name: external-dnsspec:  strategy:    type: Recreate  selector:    matchLabels:      app: external-dns  template:    metadata:      labels:        app: external-dns    spec:      serviceAccountName: external-dns      containers:      - name: external-dns        image: k8s.gcr.io/external-dns/external-dns:v0.10.2        args:        - --source=service        - --source=ingress        - --domain-filter=external-dns-test.my-org.com # will make ExternalDNS see only the hosted zones matching provided domain, omit to process all available hosted zones        - --provider=aws        - --policy=upsert-only # would prevent ExternalDNS from deleting any records, omit to enable full synchronization        - --aws-zone-type=public # only look at public hosted zones (valid values are public, private or no value for both)        - --registry=txt        - --txt-owner-id=my-hostedzone-identifier      securityContext:        fsGroup: 65534 # For ExternalDNS to be able to read Kubernetes and AWS token filesIf RBAC isn't turned on, then use the following manifest to deploy ExternalDNS:apiVersion: apps/v1kind: Deploymentmetadata:  name: external-dnsspec:  strategy:    type: Recreate  selector:    matchLabels:      app: external-dns  template:    metadata:      labels:        app: external-dns    spec:      containers:      - name: external-dns        image: k8s.gcr.io/external-dns/external-dns:v0.10.2        args:        - --source=service        - --source=ingress        - --domain-filter= <Your_R53_Domain_Name>  # will make ExternalDNS see only the hosted zones matching provided domain, omit to process all available hosted zones        - --provider=aws        - --policy=upsert-only # would prevent ExternalDNS from deleting any records, omit to enable full synchronization        - --aws-zone-type=public # only look at public hosted zones (valid values are public, private or no value for both)        - --registry=txt        - --txt-owner-id=<Your_R53_HostedZone_Id>4.    Verify that the deployment was successful:kubectl get deploymentsExample output:NAME           READY   UP-TO-DATE   AVAILABLE   AGEexternal-dns   1/1     1            1           85mYou can also check the logs to verify that the records are up to date:kubectl logs external-dns-9f85d8d5b-sx5fgExample output:........time="2022-02-10T20:22:02Z" level=info msg="Instantiating new Kubernetes client"time="2022-02-10T20:22:02Z" level=info msg="Using inCluster-config based on serviceaccount-token"time="2022-02-10T20:22:02Z" level=info msg="Created Kubernetes client https://10.100.0.1:443"time="2022-02-10T20:22:09Z" level=info msg="Applying provider record filter for domains: [<yourdomainname>.com. .<yourdomainname>.com.]"time="2022-02-10T20:22:09Z" level=info msg="All records are already up to date"........Verify that ExternalDNS is working1.    Create a service that's exposed as LoadBalancer and that can be routed externally through the domain name that's hosted on Route 53:kubectl apply SERVICE_MANIFEST_FILE_NAME.yamlNote: Replace SERVICE_MANIFEST_FILE_NAME with your service manifest's file name.Manifest:apiVersion: v1kind: Servicemetadata:  name: nginx  annotations:    external-dns.alpha.kubernetes.io/hostname: DOMAIN_NAMEspec:  ports:    - port: 80      targetPort: 80      protocol: TCP  type: LoadBalancer  selector:    app: nginx---apiVersion: apps/v1kind: Deploymentmetadata:  name: nginxspec:  selector:    matchLabels:      app: nginx  template:    metadata:      labels:        app: nginx    spec:      containers:        - image: nginx          name: nginx          ports:            - containerPort: 80              name: httpNote: Replace DOMAIN_NAME with your domain's name.2.    Check that the NGINX service was created with the LoadBalancer type:kubectl get svcExample output:NAME         TYPE           CLUSTER-IP      EXTERNAL-IP                                                              PORT(S)        AGEkubernetes   ClusterIP      10.100.0.1      <none>                                                                   443/TCP        26hnginx        LoadBalancer   10.100.234.77   a1ef09255d52049f487e05b4f74faea6-954147917.us-west-1.elb.amazonaws.com   80:30792/TCP   74mNote: The service automatically creates a Route 53 record for the hosted zone.Check the logs to verify that the Route 53 record was created:kubectl logs external-dns-9f85d8d5b-sx5fgExample output:.........time="2022-02-10T21:22:43Z" level=info msg="Applying provider record filter for domains: [<domainname>.com. .<domainname>.com.]"time="2022-02-10T21:22:43Z" level=info msg="Desired change: CREATE <domainname>.com A [Id: /hostedzone/Z01155763Q6AN7CEI3AP6]"time="2022-02-10T21:22:43Z" level=info msg="Desired change: CREATE <domainname>.com TXT [Id: /hostedzone/Z01155763Q6AN7CEI3AP6]"time="2022-02-10T21:22:43Z" level=info msg="2 record(s) in zone xxx.com. [Id: /hostedzone/Z01155763Q6AN7CEI3AP6] were successfully updated"time="2022-02-10T21:23:43Z" level=info msg="Applying provider record filter for domains: [<domainname>.com. .<domainname>.com.]"time="2022-02-10T21:23:43Z" level=info msg="All records are already up to date".........For more information and examples for ExternalDNS, see Setting up ExternalDNS for services on AWS (on the GitHub website) and Set up ExternalDNS (on the Kubernetes website).Follow"


Question: How do I troubleshoot CloudWatch Logs so that it streams to my OpenSearch Service domain?

I can't stream my Amazon CloudWatch logs to my Amazon OpenSearch Service domain.

Answer: "I can't stream my Amazon CloudWatch logs to my Amazon OpenSearch Service domain.ResolutionI can't stream multiple CloudWatch log groups to the same OpenSearch Service domainBy default, Amazon CloudWatch creates only one AWS Lambda function for each OpenSearch Service domain. If you set up multiple log groups to index data into your domain, then all the multiple log groups invoke the same Lambda function. When the first log group invokes a Lambda function, the invocation creates an index and a type field in your domain.Indices that are created in OpenSearch Service 6.0.0 or later can contain only a single mapping type. Indices that are created in 5.x with multiple mapping types continue to function in OpenSearch Service 6.x. For more information about OpenSearch Service mapping types deprecation, see Removal of mapping types on the Elastic website.When other log groups try to invoke the same Lambda function, the invocation fails with the following error:"reason": "Rejecting mapping update to [<index_name>] as the final mapping would have more than 1 type: [log-group-1, log-group-2]”To resolve this issue, first update your Lambda function with the following syntax:var indexName = [     'cwl-' + payload.logGroup.toLowerCase().split('/').join('-') + '-' + timestamp.getUTCFullYear(),     ('0' + (timestamp.getUTCMonth() + 1)).slice(-2),     ('0' + timestamp.getUTCDate()).slice(-2)      ].join('.');This syntax creates multiple indices for the different log groups that are streaming into your OpenSearch Service domain.Save the updated Lambda function to create separate indices for the multiple log groups that are streaming into your domain.I can't stream to a VPC-based OpenSearch Service domain in the same AWS accountImportant: Before streaming the CloudWatch log groups to your virtual private cloud (VPC)-based OpenSearch Service domain, update your AWS Identity and Access Management (IAM) role policy. The IAM role that's attached to the corresponding Lambda function must have the AWSLambdaVPCAccessExecutionRole policy attached to it.Here's an AWSLambdaVPCAccessExecutionRole policy in JSON format:{  "Version": "2012-10-17",  "Statement": [    {      "Effect": "Allow",      "Action": [        "logs:CreateLogGroup",        "logs:CreateLogStream",        "logs:PutLogEvents",        "ec2:CreateNetworkInterface",        "ec2:DescribeNetworkInterfaces",        "ec2:DeleteNetworkInterface"      ],      "Resource": "*"    }  ]}Note: This managed policy allows the Lambda function to write the CloudWatch log group to your cluster in the VPC.After you attach the policy to your Lambda function, you can begin streaming the logs to your OpenSearch Service domain in the VPC.I can't stream my CloudWatch log group to an OpenSearch Service domain when fine-grained access control is activatedIf you stream your CloudWatch logs to an OpenSearch Service domain with fine-grained access control, then you might receive an error similar to the following one:"{\"statusCode\":403,\"responseBody\":{\"error\":{\"root_cause\":[{\"type\":\"security_exception\",\"reason\":\"no permissions for [indices:data/write/bulk] and User [name=arn:aws:iam::123456789101:role/lambda_opensearch_execution, roles=[arn:aws:iam::123456789101:role/lambda_opensearch_execution], requestedTenant=null]\"}],\"type\":\"security_exception\",\"reason\":\"no permissions for [indices:data/write/bulk] and User [name=arn:aws:iam::123456789101:role/lambda_opensearch_execution, roles=[arn:aws:iam::123456789101:role/lambda_opensearch_execution], requestedTenant=null]\"},\"status\":403}}"If you received this error message from your Lambda function logs, then the role mapping is incomplete.Note: By default, OpenSearch Service creates an Lambda function for you.OpenSearch Service domains running 7.9 and later (including OpenSearch version 1.x)To resolve the error message, complete the following steps:1.    Open OpenSearch Dashboards. You can find a link to OpenSearch Dashboards in the domain summary of your OpenSearch Service console.2.    From the navigation pane, choose Security.3.    Choose Roles.4.    Choose the all_access role.5.    Choose the Mapped users tab.6.    On the Mapped users dialog page, choose Manage mapping.7.    Under Backend roles, enter the Lambda function execution role ARN.8.    Choose Map. Your logs now stream to your OpenSearch Service domain.For more information about role mapping, see Mapping roles to users.OpenSearch Service domains running 7.8 and earlierTo resolve the error message, complete the following steps:1.    Open OpenSearch Dashboards. You can find a link to OpenSearch Dashboards in the domain summary of your OpenSearch Service console.2.    On the navigation pane, choose the lock icon.3.    Choose Role mappings.4.    Choose all_access and security_manager as your roles.Note: The all_access role provides access only to your cluster. Based on your use case, you can also add fine-grained access control to your cluster.5.    Edit the mapping for all_access.6.    For Backend Role, add the Lambda function's execution role and choose Submit. Your logs now stream to your OpenSearch Service domain.My CloudWatch logs aren't being delivered to my OpenSearch Service domainWhen you use the default Lambda function to stream CloudWatch logs to your OpenSearch Service domain, you might get the following error:"errorMessage": "{\"statusCode\":200,\"responseBody\":{\"took\":42,\"errors\":true}}","Note: By default, Lambda errors are returned as 200 OK responses.To troubleshoot this error message, complete the following steps:1.    Open the default Lambda function.2.    Find the following line of code:"var logFailedResponses = false;"3.    Update the var logFailedResponses value to true. This update provides additional information for any new indexing requests that use the Lambda function. You can use the additional information to identify the cause of your indexing issue.I'm getting a cluster_block_exception errorA lack of free storage space or excessive JVM memory pressure causes cluster block exceptions.For more information, see How do I troubleshoot high JVM memory pressure on my Amazon OpenSearch Service cluster?My CloudWatch subscription filter fails to send data to my cluster through a default Lambda function (OpenSearch Service 2.0 and later)If you have a CloudWatch subscription filter to send logs to OpenSearch Service 2.x using the default Lambda function, then you might get an error. If the subscription filter fails to ingest the logs and you get the following error, then a deactivated parameter caused the error:"{\"statusCode\":400,\"responseBody\":{\"error\":{\"root_cause\":[{\"type\":\"illegal_argument_exception\",\"reason\":\"Action/metadata line [1] contains an unknown parameter [_type]\"}],\"type\":\"illegal_argument_exception\",\"reason\":\"Action/metadata line [1] contains an unknown parameter [_type]\"},\"status\":400}}"In OpenSearch Service versions 2.0 and later, the _type parameter is removed from API endpoints. To resolve this error, you must also remove the parameter from your Lambda function's code.1.    Open the AWS Lambda console.2.    Select the default Lambda function for your subscription filter.3.    See the code for your function under Code source.4.    Find the transform function that's defined in the code. Within this function, the data is converted into the JSON indexing format for OpenSearch Service. The first lines of this code are similar to the following code:function transform(payload) {    if (payload.messageType === 'CONTROL_MESSAGE') {        return null;    }    var bulkRequestBody = '';    payload.logEvents.forEach(function(logEvent) {                var timestamp = new Date(1 * logEvent.timestamp);5.    Under the transform function, find the _type parameter. In most cases, this is in line 79. Remove or comment out the line of code that adds the _type parameter. After removal, your code is similar to the following code:var action = {    "index": {}};action.index._index = indexName;//action.index._type = payload.logGroup;action.index._id = logEvent.id;bulkRequestBody += [You can now successfully send indexing requests.Follow"


Question: How do I find my Amazon Connect instance ID?

I want to find my Amazon Connect instance ID.

Answer: "I want to find my Amazon Connect instance ID.ResolutionYour Amazon Connect instance ID is the 36-character string at the end of your instance's Amazon Resource Name (ARN).To see your instance's ARN, follow the instructions in Find your Amazon Connect instance ID/ARN.Related informationCreate an Amazon Connect instanceFollow"


Question: How do I change my container instance type in Amazon ECS?

"I want to change the container instance type in my Amazon Elastic Container Service (Amazon ECS) cluster. But, I don't know how."

Answer: "I want to change the container instance type in my Amazon Elastic Container Service (Amazon ECS) cluster. But, I don't know how.Short descriptionTo change your container instance type, complete the steps in one of the following sections:Update container instances that are launched in an ECS cluster through the AWS CloudFormation stackUpdate container instances that are launched manually in an ECS clusterUpdate container instances in a cluster that's associate with a capacity providerResolutionUpdate container instances that are launched in an ECS cluster through the CloudFormation stackImportant: The following steps apply only to ECS clusters that are created with resources that internally create an underlying CloudFormation stack. The stack has a name in the following format: EC2ContainerService-yourClusterName. These steps don't apply to empty ECS clusters or to customized approaches for provisioning container instances.Update the value of the EcsInstanceType parameter in the CloudFormation stackOpen the AWS CloudFormation console.Select the stack that contains your ECS cluster.Note: The cluster name is appended to the end of your stack name (for example, EC2ContainerService-yourClusterName).Choose Actions, and then choose Update Stack.Choose Use current template, and then choose Next.For EcsInstanceType, set a value that's appropriate for the instance type in your container instance, and then choose Next.Skip the Options section, choose Next, and then choose Update.Replace the old container instances in the clusterTo update the CloudFormation stack, complete steps 1 through 4 in the preceding section.For AsgMaxSize, enter a parameter value that's double the current size.Note: For example, if the current value is 2, set the new value to 4. This helps prevent downtime when you change the instance type.Open the Amazon ECS console.In the navigation pane, choose Clusters, and then choose your cluster.Choose the ECS Instances tab, and then select the container instance IDs for the old container instances that you want to replace.Note: If DeploymentConfiguration allows for replacement tasks to be placed on container instances, then Amazon ECS automatically places the replacement tasks.Choose the Actions menu, and then choose Drain instances to drain the instances.On the ECS Instances tab, verify that Running tasks count is 0 for your old container instances.In the navigation pane, choose Clusters, and then select your cluster.Choose the ECS Instances tab, select the container instance IDs of your old container instances, and then choose Deregister.Note: Deregistering an instance removes it from Amazon ECS.In your CloudFormation template, set the value of AsgMaxSize to the original value to terminate the older container instances.Important: This step assumes that your Auto Scaling group has the Default Termination Policy.Update container instances that are manually launched in an ECS clusterCopy the launch configuration of your Auto Scaling group, and then name your new launch configuration.Change your instance type.In the Amazon EC2 console, in the Auto Scaling section of the navigation pane, choose Auto Scaling Groups. Then, select the Auto Scaling group for your container instance.Choose Actions, and then choose Edit.In the pop-up window, for Launch Configuration, choose the launch configuration that you created in step 1 of this section.For Desired Capacity, enter a value that's double the size of the current value, and then update the value of Max as needed.Note: Desired capacity must be between minimum and maximum group size, inclusive.In the navigation pane of the Amazon ECS console, choose Clusters, and then choose your cluster.Choose the ECS Instances tab, select the container instance IDs for the old container instances that you want to replace.Choose the Actions menu, and then choose Drain instances to drain the instances.On the ECS Instances tab, for your old container instances, verify that Running tasks count is 0.Choose the ECS Instances tab, select the container instance IDs for your old container instances, and then choose Deregister.Note: Deregistering an instance removes it from Amazon ECS.In the Amazon EC2 console, in the Auto Scaling section of the navigation pane, choose Auto Scaling Groups.Choose Actions, and then choose Edit.In your Auto Scaling group configuration, set Desired Capacity and Max to their original values, and then save your changes.Note: This terminates the old container instances in the ECS cluster.Update container instances in a cluster that's associated with a capacity providerNote: This section assumes that you have capacity providers associated with your cluster and services associated with capacity provider strategy.If the cluster was created using CloudFormation, then complete the following steps:Follow steps 1 through 6 in the preceding subsection:Update the value of the EcsInstanceType parameter in the CloudFormation stackIn the navigation pane of the Amazon ECS console, choose Clusters, and then choose your cluster.Choose the ECS Instances tab, then select the container instance ID for the old container instance that you want to replace.Choose the Actions menu, and then choose Drain instances to drain the instances.Note: When you drain the instances, the capacity provider launches new container instances based on the DeploymentConfiguration of the services.On the ECS Instances tab of your old container instance, verify that the Running tasks count is 0.If the cluster was created manually, then complete the following steps:Follow steps 1 through 5 in the preceding section:Update container instances that are manually launched in an ECS clusterIn the navigation pane of the Amazon ECS console, choose Clusters, and then choose your cluster.Choose the ECS Instances tab, then select the container instance ID for the old container instance that you want to replace.Choose the Actions menu, and then choose Drain instances to drain the instances.Note: When you drain the instances, the capacity provider launches new container instances based on the DeploymentConfiguration of the services.On the ECS Instances tab of your old container instance, verify that the Running tasks count is 0.Note: The capacity provider automatically terminates drained instances after a defined period of time.Follow"


Question: How can I troubleshoot the "You have exceeded the maximum limit for Lambda HyperPlane elastic network interfaces for your VPC" error when configuring a Lambda function in an Amazon VPC?

I created or updated an AWS Lambda function that's connected to an Amazon Virtual Private Cloud (Amazon VPC). I received the error "You have exceeded the maximum limit for Lambda HyperPlane ENIs for your VPC."

Answer: "I created or updated an AWS Lambda function that's connected to an Amazon Virtual Private Cloud (Amazon VPC). I received the error "You have exceeded the maximum limit for Lambda HyperPlane ENIs for your VPC."Short descriptionWhen you configure a Lambda function to access resources in an Amazon VPC, Lambda creates a Hyperplane elastic network interface (ENI). The Hyperplane elastic network interface is created the first time that a unique subnet and security group combination is defined.The default quota limit for elastic network interfaces per Amazon VPC is 250. Exceeding the elastic network interface quota results in a limit exceeded error.For more information, see Configuring a Lambda function to access resources in a VPC.ResolutionNote: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you're using the most recent AWS CLI version.Identify the usage of Hyperplane elastic network interfaces in your Amazon VPCRun the AWS CLI command describe-network-interfaces to find the total number of Hyperplane ENIs in use by Lambda for your Amazon VPC.Note: Replace VPC with your Amazon VPC ID and region with your AWS Region.$ aws ec2 describe-network-interfaces --region us-east-1 \  --filters 'Name=vpc-id,Values=VPC' 'Name=status,Values=in-use' \  --query 'NetworkInterfaces[?InterfaceType=='lambda'].NetworkInterfaceId'Remove Amazon VPC configurations for Lambda functions that don't access private resourcesIt's a best practice to configure an Amazon VPC for your Lambda function to access only private resources. After you update a function to remove its Amazon VPC configuration, Lambda deletes the attached Hyperplane elastic network interface.Note: Lambda deletes the Hyperplane elastic network interface only if no other functions or published versions are using that Hyperplane elastic network interface.To identify the function using an elastic network interface, see Why can't I detach or delete an elastic network interface that Lambda created?Remove unused versions for active Lambda functions and reuse Hyperplane elastic network interfacesIf your Lambda function configured with your Amazon VPC has multiple published versions, then it's a best practice to remove unused versions. Removing unused Lambda function versions helps to release unused Hyperplane elastic network interfaces.If a Lambda function remains idle for consecutive weeks, then Lambda reclaims the unused Hyperplane elastic network interfaces and sets the function state to idle. Lambda doesn't delete Hyperplane elastic network interfaces that are in use by Lambda functions.Lambda reuses the Hyperplane elastic network interface for other Amazon VPC activated functions in your account that use the same subnet and security group combination. Depending on your use case, you can try reusing the elastic network interfaces across functions by configuring the same security group subnet pairing.For more information, see Creating elastic network interfaces.Create Lambda functions across multiple Amazon VPCsThe limit of 250 Hyperplane elastic network interfaces is per Amazon VPC. Depending on your use case, you can create the Lambda functions across different Amazon VPCs so that the Hyperplane elastic network interface limit isn't reached.Open a quota increase case in the Service Quotas dashboardIf you determine that your use case requires a higher service quota for Hyperplane elastic network interfaces, you can request a service quota increase.1.    Open the Service Quotas dashboard.2.    Choose the AWS Lambda card. The Lambda Service quotas page opens.3.    Choose Elastic network interfaces per VPC, and then choose Request quota increase.4.    For Change quota value, enter your quota amount, and then choose Request.Note: The initial status of a request is Pending. After the status changes to Quota requested, the AWS Support case number appears.5.    Choose the case number to open the ticket for your request.6.    In the ticket's comment thread, add the description of your Lambda function's use case.Note: You'll receive a status update email from AWS Support that either approves or denies the request.For more information, see Requesting a quota increase.Related informationHow do I request a concurrency limit increase for my Lambda function?Follow"


Question: How can I prevent or restrict users from updating or deleting my Route 53 health checks?

"I created several Amazon Route 53 health checks. I want to either prevent all other users from modifying these health checks, or control which users can modify them."

Answer: "I created several Amazon Route 53 health checks. I want to either prevent all other users from modifying these health checks, or control which users can modify them.ResolutionUse AWS Identity and Access Management (IAM) policies to prevent changes to your Route 53 health checks. For more information, see Using identity-based policies (IAM policies) for Amazon Route 53.Option 1: Explicitly deny other users from deleting or updating health checksTo restrict other users from running the delete and update commands on your health checks, use the following IAM policy :{  "Version": "2012-10-17",  "Statement": [    {      "Effect": "Deny",      "Action": [        "route53:DeleteHealthCheck",        "route53:UpdateHealthCheck"      ],      "Resource": "*"    }  ]}Option 2: Require other users to perform multi-factor authentication (MFA) to delete or update health checksTo control which users can update health checks, use MFA to be sure that only MFA authenticated users can modify them. If a user isn't MFA authenticated, then any update or delete calls that they attempt fail.The following statement specifies that any MFA unauthenticated user can't perform the listed actions:{  "Version": "2012-10-17",  "Statement": [    {      "Sid": "VisualEditor0",      "Effect": "Deny",      "Action": [        "route53:UpdateHealthCheck",        "route53:DeleteHealthCheck"      ],      "Resource": "*",      "Condition": {        "BoolIfExists": {          "aws:MultiFactorAuthPresent": "false"        }      }    }  ]}For more information, see How do I use an MFA token to authenticate access to my AWS resources through the AWS Command Line Interface (AWS CLI)?Follow"


Question: How do I move a Direct Connect connection from one AWS account to another?

I want to move an AWS Direct Connect connection from one AWS account to another. How can I do this?

Answer: "I want to move an AWS Direct Connect connection from one AWS account to another. How can I do this?Short descriptionTo move a Direct Connect connection between AWS accounts, you must transfer ownership of that connection. The source (current owner) and destination (new owner) AWS accounts must each open separate AWS Support cases to transfer ownership of the Direct Connect connection. This process helps verify that both the source and the destination AWS accounts agree to the transfer.The transfer of a Direct Connect connection changes ownership and billing of the connection to the transferred account. No changes are made to the Direct Connect connection during the transfer. No network outages occur during the ownership transfer of Direct Connect connections from one AWS account to another.Note:This ownership transfer is only for the Direct Connect connection.Transfer of ownership is available only for AWS Direct Connect dedicated connections. If you have a hosted connection from an AWS partner, then transfer of ownership isn’t possible.Virtual interfaces associated with the Direct Connect connection aren't part of the transfer. They remain associated with the AWS account where they were created.Direct Connect gateways can't be moved from one AWS account to another.ResolutionBefore you begin, be sure that both the current and new owners agree to the Direct Connect connection transfer.1.    Open an AWS Support case from the source account (the current owner of the Direct Connect connection). Be sure to grant permission for AWS Support to transfer the Direct Connect connection from this account to the destination account. Also, be sure to provide the Direct Connect connection ID.2.    Open an AWS Support case from the destination account (the new owner of the Direct Connect connection). Be sure to grant permission for this account to accept ownership of the Direct Connect connection. Also, be sure to provide the Direct Connect connection ID.3.    After the destination account's case is created, note the case ID.4.    Update the source account's case with the destination account's case number.5.    Wait for AWS Support to review both cases and process the ownership transfer.Related informationAWS Direct Connect connectionsFollow"


Question: Why do my AWS Health events still appear in the AWS Health Dashboard after I've taken the requested notification action?

I took the requested action in the AWS Health Dashboard but the notification still appears.

Answer: "I took the requested action in the AWS Health Dashboard but the notification still appears.Short descriptionYou can use the AWS Health Dashboard to view the health of all AWS services. Health events (public or account-specific) might request you to act on resources in your AWS account. For example, stopping an Amazon Elastic Compute Cloud (Amazon EC2) instance that has scheduled maintenance. You can review the event description to understand the issue, identify affected resources, and follow the requested actions. The event status tells you if the Health event is open, closed, or upcoming. You can view Health events in the AWS Health Dashboard, or the AWS Health API, for up to 90 days.For more information, see AWS Health events.ResolutionAfter taking the requested action, the Health event might still appear in the AWS Health Dashboard. For example, under the Open and recent issues and Scheduled changes sections the Health event is still displayed after taking the requested action. The Other notifications section displays events for several days or until the scheduled end time has been reached.If you've already taken the requested action in the AWS Health Dashboard, then you can ignore the notification.For more information, see AWS Health Dashboard – Service health.Related informationAre you a first-time AWS Health user?How can I use AWS Health Aware to send events to channels across my organization in Organizations?Follow"


Question: How can I decode and verify the signature of an Amazon Cognito JSON Web Token?

I want to use an Amazon Cognito user pool as the authentication method for my application. What is a secure way to verify the ID and access tokens sent by clients to my application?

Answer: "I want to use an Amazon Cognito user pool as the authentication method for my application. What is a secure way to verify the ID and access tokens sent by clients to my application?Short descriptionWhen clients authenticate to your application with a user pool, Amazon Cognito sends an ID token. You can manually verify the ID token in scenarios similar to the following:You created a web application and want to use an Amazon Cognito user pool for authentication.You use an Amazon Cognito user pool for authentication and an Amazon Cognito identity pool to retrieve AWS Security Token Service (AWS STS) temporary credentials. AWS Lambda is invoked with those credentials, but Lambda doesn't have information about who originally authenticated with the user pool.To get Amazon Cognito user details contained in an Amazon Cognito JSON Web Token (JWT), you can decode the token and then verify the signature.ResolutionAWS released the following library that you can use to verify JWTs: https://github.com/awslabs/aws-jwt-verifyimport { CognitoJwtVerifier } from "aws-jwt-verify";// Verifier that expects valid access tokens:const verifier = CognitoJwtVerifier.create({  userPoolId: "<user_pool_id>",  tokenUse: "access",  clientId: "<client_id>",});try {  const payload = await verifier.verify(    "eyJraWQeyJhdF9oYXNoIjoidk..." // the JWT as string  );  console.log("Token is valid. Payload:", payload);} catch {  console.log("Token not valid!");}After a user logs in, an Amazon Cognito user pool returns a JWT. The JWT is a base64url-encoded JSON string ("claims") that contains information about the user. Amazon Cognito returns three tokens: the ID token, the access token, and the refresh token. The ID token contains the user fields defined in the Amazon Cognito user pool.Tokens include three sections: a header, a payload, and a signature.The following is the header of a sample ID token. The header contains the key ID ("kid"), as well as the algorithm ("alg") used to sign the token. In this example, the algorithm is "RS256", which is an RSA signature with SHA-256.{  "kid": "abcdefghijklmnopqrsexample=",  "alg": "RS256"}The following is an example of the payload, which has information about the user, as well as timestamps of the token creation and expiration:{  "sub": "aaaaaaaa-bbbb-cccc-dddd-example",  "aud": "xxxxxxxxxxxxexample",  "email_verified": true,  "token_use": "id",  "auth_time": 1500009400,  "iss": "https://cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-2_example",  "cognito:username": "anaya",  "exp": 1500013000,  "given_name": "Anaya",  "iat": 1500009400,  "email": "anaya@example.com"}The last section is the signature, which is a hashed and encrypted combination of the header and the payload.Amazon Cognito generates two RSA key pairs for each user pool. The private key of each pair is used to sign the respective ID token or access token. The public keys are made available at an address in the following format:https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.jsonThe JSON file (jwks.json) is structured in the following format:{    "keys": [{        "alg": "RS256",        "e": "AQAB",        "kid": "abcdefghijklmnopqrsexample=",        "kty": "RSA",        "n": "lsjhglskjhgslkjgh43lj5h34lkjh34lkjht3example",        "use": "sig"    }, {        "alg":        "RS256",        "e": "AQAB",        "kid": "fgjhlkhjlkhexample=",        "kty": "RSA",        "n": "sgjhlk6jp98ugp98up34hpexample",        "use": "sig"    }]}To verify the signature of an Amazon Cognito JWT, first search for the public key with a key ID that matches the key ID in the header of the token. Then, you can use libraries, such as aws-jwt-verify or those recommended by jwt.io or OpenID Foundation, to validate the signature of the token and extract values, such as expiration and user name.Apart from the signature, it's also a best practice to verify the following:The token isn't expired.The audience ("aud") specified in the payload matches the app client ID created in the Amazon Cognito user pool.The aws-jwt-verify library includes these checks on your behalf. For more code examples on how to decode and verify an Amazon Cognito JWT using Lambda, see Decode and verify Amazon Cognito JWT tokens.Related informationVerifying a JSON Web TokenUsing tokens with user poolsFollow"


Question: How can I troubleshoot permissions issues while creating a SageMaker Feature Group?

"I'm trying to create an Amazon SageMaker Feature Group, but I'm getting the "AccessDenied" error."

Answer: "I'm trying to create an Amazon SageMaker Feature Group, but I'm getting the "AccessDenied" error.Short descriptionSageMaker "AccessDenied" errors indicate that the AWS Identity and Access Management (IAM) role doesn't have sufficient permissions to perform the Create Feature Group operation. You might get the “AccessDenied” error when the execution role permissions are missing or misconfigured the following:Missing AmazonSageMakerFeatureStoreAccess policy and Amazon Simple Storage Service (Amazon S3) bucket naming requirementsMissing LakeFormation permissionsMissing AWS Key Management Service (AWS KMS) policyAmazon S3 bucket policyResolutionNote: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.To view a detailed error message while creating Feature Group, run the following command from terminal, and check the FailureReason:$ aws sagemaker describe-feature-group --feature-group-name nameofthefeaturegroupMissing AmazonSageMakerfeatureStoreAccess policy and Amazon S3 bucket naming requirementsThe execution role that you're using might be missing the Amazon managed AmazonSageMakerFeatureStore policy. Review the policies attached to the execution role. Then, attach the AmazonSageMakerFeatureStoreAccess policy if it's missing:{  "Version": "2012-10-17",  "Statement": [    {      "Effect": "Allow",      "Action": [        "s3:PutObject",        "s3:GetBucketAcl",        "s3:PutObjectAcl"      ],      "Resource": [        "arn:aws:s3:::*SageMaker*",        "arn:aws:s3:::*Sagemaker*",        "arn:aws:s3:::*sagemaker*"      ]    }  ]}The creation of the Feature Group might fail even after adding the AmazonSageMakerFeatureStoreAccess policy. Because the policy is an Amazon managed policy that's stored in an S3 bucket, the bucket must have the word "sagemaker" in the name.Missing Lake Formation permissionsThe creation of the Feature Group might fail due to insufficient AWS Lake Formation permissions. When a Feature Group is created, an AWS Glue database is automatically created. Any Feature Groups created using SageMaker are created as tables within this AWS Glue database.Confirm that the execution role used is granted permission to create an AWS Glue database. If the execution role doesn't have permission, do the following:Note: AWS Lake Formation requires each principal (user or role) to be authorized to perform actions on Lake Formation managed resources.Open the LakeFormation consoleFrom the left sidebar, choose Permissions, then Data PermissionsChoose GrantChoose the IAM execution role from the principals dropdown menu, then grant the required permissionsFor more information about granting database permissions, see Granting permissions on a database or table shared with your account.Missing AWS KMS policyThe CreateFeatureGroup API call might fail due to missing AWS KMS policies. To check, review the IAM policies of the execution role and then confirm that it has the following policies attached:kms:GenerateDataKeykms:Decryptkms: EncryptIf the preceding polices aren't visible after running the CLI command, attach the policies and then retry.S3 bucket policyThe "AccessDenied" errors might also occur due to an Amazon S3 bucket policy preventing access to the bucket. Review the S3 bucket policy and then check if the execution role used to create the Feature Group has the access to the bucket.Related informationGranting permissions on a database or table shared with your accountGranting resource link permissionsUsing bucket policesFollow"


Question: How do I configure my Site-to-Site VPN connection to prefer tunnel A over tunnel B?

My AWS Site-to-Site VPN connection consists of two virtual private network (VPN) tunnels. These tunnels exist between a customer gateway device and either a virtual private gateway or a transit gateway. How can I be sure that tunnel A is preferred over tunnel B when sending traffic from AWS to an on-premises network?

Answer: "My AWS Site-to-Site VPN connection consists of two virtual private network (VPN) tunnels. These tunnels exist between a customer gateway device and either a virtual private gateway or a transit gateway. How can I be sure that tunnel A is preferred over tunnel B when sending traffic from AWS to an on-premises network?ResolutionStatic VPNs created between a customer gateway and either a virtual private gateway or a transit gatewayIn this scenario, the virtual private gateway or transit gateway sends traffic from AWS to the on-premises network on a single VPN tunnel. This tunnel is randomly chosen by AWS and is referred to as the preferred tunnel.If the AWS VPN connection (static routing type) has an Active/Active configuration (both tunnels are UP), then you can't configure AWS to prefer a specific tunnel to send traffic. For example, tunnel A was randomly chosen by AWS as the preferred VPN tunnel for sending traffic from AWS to the on-premises network. If tunnel A goes down, then traffic from AWS automatically fails over to tunnel B.Note: With an Active/Active configuration, the customer gateway must have Asymmetric routing activated on the virtual tunnel interfaces.If the AWS VPN connection (static routing type) has an Active/Passive configuration (Tunnel A is UP, but tunnel B is DOWN), then traffic from AWS to the on-premises network traverses tunnel A because it's in the UP state.Dynamic VPNs created between a customer gateway and either a virtual private gateway or a transit gatewayFor virtual private gateway or transit gateway configurations with ECMP deactivatedTraffic from AWS to the on-premises network is sent over the preferred tunnel (randomly chosen by AWS) when the AWS VPN connection:Has an Active/Active configuration (both tunnels are UP), andIs advertising the same prefixes to the virtual private gateway or transit gateway with the same Border Gateway Protocol (BGP) attributes.Note: With an Active/Active configuration, the customer gateway must have Asymmetric routing activated on the virtual tunnel interfaces.If the AWS VPN connection (dynamic routing type) has an Active/Passive configuration (tunnel A is UP, but tunnel B is DOWN), traffic from AWS to the on-premises network traverses tunnel A because it's in the UP state.For transit gateway configurations with ECMP activatedThe transit gateway load balances traffic from AWS to the on-premises network between the VPN tunnels:If the same prefixes are advertised from the customer gateway device over the tunnels, andBGP attributes for the prefixes advertised from the customer gateway device must be identical on the VPN tunnels. These BGP attributes include the AS-Path prepend and the first AS in the AS_SEQUENCE, MED.For dynamic AWS VPN connectionsSet the customer gateway device to prefer one VPN tunnel over the other by leveraging the order of preference criteria:Advertise a more specific prefix to the virtual private gateway or transit gateway on the tunnel that the customer prefers to receive traffic from AWS.For matching prefixes where each VPN connection uses BGP, the AS PATH is compared and the prefix with the shortest AS PATH is preferred.When the AS PATHs are the same length, and the first AS in the AS_SEQUENCE is the same across multiple paths, multi-exit discriminators (MEDs) are compared. The path with the lowest MED value is preferred.Note: It's a best practice to avoid using AS Path prepending so that both tunnels have an equal AS PATH value. With an equal AS PATH value, the MED value that AWS sets on the tunnel during VPN tunnel endpoint updates determines tunnel priority.ECMP isn't supported for Site-to-Site VPN connections on a virtual private gateway.ECMP is supported for Site-to-Site VPN connections on a transit gateway.Follow"


Question: How do I know if my dedicated IP address for Amazon SES is warmed up?

I leased a dedicated IP address for my Amazon Simple Email Service (Amazon SES) account. How can I confirm that the dedicated IP address is warmed up?

Answer: "I leased a dedicated IP address for my Amazon Simple Email Service (Amazon SES) account. How can I confirm that the dedicated IP address is warmed up?ResolutionTo view the warm-up status of your dedicated IP address, follow these steps:Open the Amazon SES console.From the navigation pane, under Email Sending, choose Dedicated IPs.On this page, you can view the percent completion for the warm-up process: IP Address Warm Up Status (% completed)Related InformationWarming up Dedicated IP AddressesFollow"


Question: How do I assign a static hostname to an Amazon EC2 instance running RHEL 7 or CentOS 7?

"I changed the hostname of my Amazon Elastic Compute Cloud (Amazon EC2) instance. However, when I reboot or stop and then start the instance, the hostname changes back."

Answer: "I changed the hostname of my Amazon Elastic Compute Cloud (Amazon EC2) instance. However, when I reboot or stop and then start the instance, the hostname changes back.Short descriptionTo make a hostname persist when you reboot or stop and start your EC2 instance, add the hostname to the appropriate configuration files on the instance.Note: The following steps apply to RHEL 7 or CentOS 7. For instructions that apply to other distributions, see one of the following:Change the system hostnameHow do I assign a static hostname to an Amazon EC2 instance running RHEL 5 or 6, CentOS 5 or 6, or Amazon Linux?How do I assign a static hostname to an Amazon EC2 instance running SLES?How do I assign a static hostname to an Amazon EC2 instance running Ubuntu Linux?Resolution1.    Run the hostnamectl command  from the shell to update the hostname of your RHEL 7 or CentOS 7 Linux instance. Replace persistent-hostname with the name you want the instance to use:sudo hostnamectl set-hostname --static persistent-hostnameNote: Changing the hostname by using the hostnamectl command doesn't update the /etc/hosts file. However, if necessary, you can manually edit this file to add the new hostname.2.    Use the vi text editor to update the /etc/cloud/cloud.cfg file on your RHEL 7 or CentOS 7 Linux instance. For general information about using the vi editor, run the command info vi from the command shell:Note: For instances running RHEL 7.4 and above, skip this step.sudo vi /etc/cloud/cloud.cfg3.    Add the following string to the bottom of the /etc/cloud/cloud.cfg file to be sure that the new hostname is preserved between restarts and reboots:preserve_hostname: trueSave and exit the vi editor.4.    Run the reboot command to reboot the EC2 instance and associate the new hostname with the instance:sudo reboot5.    Run the Linux hostname command without any parameters to verify that the hostname change persisted:hostnameThe command returns the new hostname that you specified in step 1.Note: If you install any system updates that affect the /etc/hosts file, the hostname file, or the hostname utility, then you must run these steps again.Follow"


Question: How do I recover deleted DNS records from my Route 53 hosted zone?

I want to recover deleted DNS records from my Amazon Route 53 hosted zone.

Answer: "I want to recover deleted DNS records from my Amazon Route 53 hosted zone.ResolutionCheck your CloudTrail event history1.    Open the AWS CloudTrail console. Be sure that you're in the N. Virginia Region. Route 53 DNS service API calls are logged in this Region only.2.    In the navigation pane, choose Event history.3.    Choose the Event name filter.4.    Enter the event name as ChangeResourceRecordSets.You can now view all events that are logged when a DNS record is created, changed, or deleted. An event is in JSON format and provides information such as name, type, and TTL. To narrow your search, you can use the time filter.Note: Different record types have different JSON syntax. For more information, see change-resource-record-sets.Download CloudTrail eventsIf you're not sure when the DNS record was deleted, then you can download all events and filter the results using the DELETE action:1.    Choose Download events.2.    Choose Download as JSON.3.    Search for the DELETE keyword, and then review the details about the deleted DNS record.View CloudTrail events using the AWS CLINote: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.Use the lookup-events command to view the CloudTrail event history for the DELETE action:aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=ChangeResourceRecordSets --region us-east-1 | grep "DELETE"Use the details about the deleted DNS record to create the record in the desired Route 53 hosted zone.Note: You can view event history for only the past 90 days. To view CloudTrail logs that are older than 90 days, create a trail. Then, send the logs to an Amazon Simple Storage Service (Amazon S3) bucket or to Amazon CloudWatch Logs. Note that it can take up to 15 minutes for events to be logged in CloudTrail.Follow"


Question: How can I receive notifications for scheduled events for my EC2 instance using EventBridge?

I want to receive notifications from Amazon EventBridge when there's a scheduled event for my Amazon Elastic Compute Cloud (Amazon EC2) instance.

Answer: "I want to receive notifications from Amazon EventBridge when there's a scheduled event for my Amazon Elastic Compute Cloud (Amazon EC2) instance.Short descriptionYou can create an EventBridge rule to start on a scheduled event for your EC2 instance. Then, you can configure Amazon Simple Notification Service (Amazon SNS) notifications for events that match your event pattern. You can also configure further processing through AWS Lambda.ResolutionImportant: Before you begin, be sure that you have an SNS topic for notifications. If you don't have one, create a new SNS topic and subscribe to it.Use the EventBridge console to create an EventBridge rule that initiates on an event:1.    Assign a Name to the rule. (Optional) You can also assign a Description to the rule.2.    For Event bus, select default.3.    For Rule type, choose Rule with an event pattern.4.    Choose Next.5.    For Event Source, choose AWS events or EventBridge partner events.6.    (Optional) For Sample events, choose the type of event.7.    For Creation method, choose Use pattern form.8.    For Event source, choose AWS services.9.    For AWS service, choose Health. This is the name of the AWS service as the event source**.**10.    For Event Type, choose Specific Health events.11.    Choose Specific service(s), and then choose EC2.12.    Choose Specific event type category(s), and then choose scheduledChange.13.    (Optional) To create a more specific rule, choose Specific event type code(s) or Specific resource(s). By adding one of these options to the rule, notifications are sent for specific events or instances.These settings create the following event pattern:Note: You can also copy and paste the following code as your rule to create your event pattern. After you choose Create Rule, choose Edit in the Event Pattern preview section. Insert the following code, choose Save, and then create an SNS target:{  "source": [    "aws.health"  ],  "detail-type": [    "AWS Health Event"  ],  "detail": {    "service": [      "EC2"    ],    "eventTypeCategory": [      "scheduledChange"    ]  }}14.    Select your SNS target:Choose Add Target.For the target, choose SNS topic.For Topic, choose the SNS topic that you want to use for notifications.The following example is an EventBridge event that's forwarded to the target:{  "version": "0",  "id": "9a06e7c4-fa42-ad91-6186-19a256fdb733",  "detail-type": "AWS Health Event",  "source": "aws.health",  "account": "123456789101",  "time": "2023-03-03T17:00:00Z",  "region": "us-east-1",  "resources": [    "i-abcdefg"  ],  "detail": {    "eventArn": "arn:aws:health:region::event id="" ",    "service": "EC2",    "eventTypeCode": "AWS_EC2_MAINTENANCE_SCHEDULED",    "eventTypeCategory": "scheduledChange",    "startTime": "Fri, 3 Mar 2023 17:00:00 GMT",    "endTime": "Fri, 3 Mar 2023 18:00:00 GMT",    "eventDescription": [      {        "language": "en_US",        "latestDescription": "A description of the event will be provided here"      }    ],    "affectedEntities": [      {        "entityValue": "i-abcdefg"      }    ]  }}If your use case requires delivering specific fields to the target, then attach an input transformer under Configure input. Or, attach a Lambda function as a target to run designated processing.Related informationAWS Health events (CloudWatch Events)Monitoring AWS Health events with Amazon EventBridgeHow do I set up human-readable EventBridge notifications for API calls using input transformer?Follow"


Question: Why can't I access an object that was uploaded to my Amazon S3 bucket by another AWS account?

"An AWS Identity and Access Management (IAM) user from another AWS account uploaded an object to my Amazon Simple Storage Service (Amazon S3) bucket. When I try to access that object, I receive the 403 Access Denied error. How can I fix this?"

Answer: "An AWS Identity and Access Management (IAM) user from another AWS account uploaded an object to my Amazon Simple Storage Service (Amazon S3) bucket. When I try to access that object, I receive the 403 Access Denied error. How can I fix this?Short descriptionFor existing Amazon S3 buckets with the default object ownership settings, the object owner is the AWS account which uploaded the object to the bucket. For these existing buckets, an object owner had to explicitly grant permissions to an object (by attaching an access control list). Otherwise, the bucket owner would be unable to access the object.With S3 Object Ownership, bucket owners can now manage the ownership of any objects uploaded to their buckets. By default, all newly created S3 buckets have the bucket owner enforced setting enabled. When the bucket owner enforced setting is enabled, bucket owners become the object owners for all objects inside the bucket. Additionally, any ACLs on a bucket and its objects are disabled.You can also set S3 Object Ownership on existing buckets by either enabling the bucket owner enforced setting or bucket owner preferred setting. When the bucket owner preferred setting is enabled, ACLs are still enabled. Also, only objects uploaded to the bucket with a bucket-owner-full-control ACL are owned by the bucket owner. If you enable the bucket owner enforced setting on an existing bucket, then note that you can also disable it at any time. (Disabling the bucket owner enforced setting on an existing bucket re-enables any buckets and object ACLs that were previously applied.)It's a best practice that bucket owners use the bucket owner enforced setting on new and existing buckets, while managing permissions through IAM and bucket policies.Important: Before you disable any ACLs on existing buckets, assess the potential impact. If there are several ACLs on an object or bucket, review and update your bucket and IAM policies to grant the required permissions.ResolutionTo disable ACLs on for your bucket and to take ownership of all objects in the bucket, run the following command:aws s3api put-bucket-ownership-controls --bucket example-bucket --ownership-controls 'Rules=[{ObjectOwnership=BucketOwnerEnforced}]'If you can't disable ACLs on your bucket, then use the following options to grant access to objects in your bucket.Grant access during a put or copy operationDuring a put or copy operation, the object owner can specify that the ACL of the object gives full control to the bucket owner.For a put operation, the object owner can run this command:aws s3api put-object --bucket destination_DOC-EXAMPLE-BUCKET --key dir-1/my_images.tar.bz2 --body my_images.tar.bz2 --acl bucket-owner-full-controlNote: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.For a copy operation of a single object, the object owner can run one of these commands:aws s3api copy-object --bucket destination_DOC-EXAMPLE-BUCKET --key source_DOC-EXAMPLE-BUCKET/myobject --acl bucket-owner-full-control-or-aws s3 cp s3://source_DOC-EXAMPLE-BUCKET/myobject s3://destination_DOC-EXAMPLE-BUCKET/ --acl bucket-owner-full-controlFor a copy operation of multiple objects, the object owner can run this command:aws s3 cp s3://source_DOC-EXAMPLE-BUCKET/ s3://destination_DOC-EXAMPLE-BUCKET/ --acl bucket-owner-full-control --recursiveGrant access after the object is added to the bucketIf the object is already in a bucket in another account, then the object owner can grant the bucket owner access with a put-object-acl command:aws s3api put-object-acl --bucket destination_DOC-EXAMPLE-BUCKET --key keyname --acl bucket-owner-full-controlRequire that objects grant the bucket owner full controlYou can use a bucket policy to require that any objects uploaded to your bucket by another account must set the ACL as "bucket-owner-full-control". For an example, see When other AWS accounts upload objects to my S3 bucket, how can I require that they grant me ownership of objects?Related informationIAM tutorial: Delegate access across AWS accounts using IAM rolesGranting cross-account permissions to upload objects while ensuring the bucket owner has full controlFollow"


Question: Why aren't my Savings Plans applying to my AWS billing in the way that I expected?

"I purchased a Savings Plan, but it's being used in a way that I didn't expect."

Answer: "I purchased a Savings Plan, but it's being used in a way that I didn't expect.ResolutionAWS Cost Explorer shows you details on the savings realized with your Savings Plans. You can also use the Savings Plans performance reports in AWS Cost Explorer to understand how well you are using your Savings Plans.For Savings Plans to apply, the following conditions must be true:The upfront cost (partial or all) for your Savings Plan must process successfully. Check the status of your payments on the Payment History page of the Billing and Cost Management console. To retry a failed Savings Plans payment, contact AWS Support. Failed Savings Plans purchases from previous billing periods can’t be retried.Your Savings Plan must still be active. When you purchase a Savings Plan, you choose a one-year or three-year term. After the term expires, your usage is billed at the On-Demand Instance price. To continue receiving the savings, purchase another Savings Plan with the same specifications. To check if your Savings Plans are active, you can check the AWS Cost Management console.Tip: To avoid gaps in savings, set Savings Plans alerts.You must have AWS compute usage in a supported service with the corresponding plan type. Amazon Elastic Compute Cloud (Amazon EC2), AWS Fargate, AWS Lambda, or Amazon SageMaker are eligible services for Savings Plans.If the conditions listed above are met, consider the following scenarios:Savings Plans commitment are hourly and will apply up to the hourly commitment for each hour as long as there is eligible usage. As Savings Plans are hourly, there could be remaining Savings Plans commitment in some hours and additional On-Demand charges in other hours. The remaining Savings Plans commitment in one hour can't be applied to On-Demand charges in another hour.If you have both Reserved Instances (RI) and Savings plans, RIs will apply before Savings Plans and any uncovered On Demand usage will be covered by Savings Plans.When Savings Plans apply to usage, the On Demand charges are displayed first followed by a corresponding discount for that On Demand usage. Savings Plans are applied to the qualifying usage, starting with the usage that receives the largest calculated savings. If other usage provides a larger savings, AWS will apply the Savings Plans to that usage.AWS Free Tier benefits are applied before Savings Plan benefits. Any excess usage that isn't covered by free tier, will be covered by Savings Plans.If you have multiple Savings Plans active at the same time, your bill will be generated by taking into account all active Savings Plans.The benefit of Savings Plans is applied to usage every hour. Any unused benefits will not be carried over to the next hour.Savings Plans are applied differently in an organization's consolidated bill, depending on whether sharing is turned on or off. For more information, see How is the pricing benefit of a Savings Plan applied across an organization's consolidated bill?Related informationCan I schedule my Savings Plan to renew automatically?How do I save money on my AWS usage using a Savings Plan?Follow"


Question: How can I troubleshoot an S3AccessDenied error from my file gateway's CloudWatch health logs?

"I'm trying to access my Network File System (NFS) or Server Message Block (SMB) file share on AWS Storage Gateway. However, my file gateway's health logs from Amazon CloudWatch are showing an S3AccessDenied error. How can I troubleshoot this?"

Answer: "I'm trying to access my Network File System (NFS) or Server Message Block (SMB) file share on AWS Storage Gateway. However, my file gateway's health logs from Amazon CloudWatch are showing an S3AccessDenied error. How can I troubleshoot this?ResolutionTo resolve an S3AccessDenied error, you must review the permissions policies associated with your file share. Then, you must add any required permissions that are missing. Identify the permissions that you must review based on when you get the Access Denied error:Creating the file share and the file share is stuck in the creating or unavailable stateWriting files to the file shareReading files from the file shareCreating the file share and the file share is stuck in the creating or unavailable stateIf you get the Access Denied error when creating the file share, and the file share is stuck in the creating or unavailable state, the CloudWatch log is similar to the following:{"severity": "ERROR","bucket": "AWSDOC-EXAMPLE-BUCKET","prefix": "","roleArn": "arn:aws:iam::123456789:role/service-role/StorageGatewayBucketAccessRolec6914add-b232-40dc-abef-4a9eeaaed8","source": "share-ABCD1234","type": "S3AccessDenied","operation": "s3:ListObjects","gateway": "sgw-ABCD1234","timestamp": "1597486809991"}Review the following permissions settings:1.    Check the AWS Identity and Access Management (IAM) role that's associated with your file share to confirm that it has the following permissions for the associated Amazon Simple Storage Service (Amazon S3) bucket:s3:GetBucketLocations3:ListBucket2.    Review the bucket policy of the associated bucket to confirm that there are no explicit deny statements ("Effect": "Deny") that block the access needed for the following permissions:s3:GetBucketLocations3:ListBucket3.    If the Amazon Virtual Private Cloud (Amazon VPC) that the file gateway is in uses a VPC endpoint for Amazon S3, then review the VPC endpoint policy. Confirm that the policy allows your file gateway to access the S3 bucket and objects.Writing files to the file shareIf you get the Access Denied error when writing files to the file share, the CloudWatch log is similar to the following:{"severity": "ERROR","bucket": "AWSDOC-EXAMPLE-BUCKET","prefix": "/test1","roleArn": "arn:aws:iam::123456789:role/service-role/StorageGatewayBucketAccessRole0617b6ee-4809-48bc-b646-8dda9e9c32","source": "share-ABCD1234","type": "S3AccessDenied","operation": "S3Upload","gateway": "sgw-ABCD1234","timestamp": "1597493322178"}Review the following permissions settings: 1.    Check the IAM role that's associated with your file share to confirm that it has the following permissions for the associated Amazon S3 bucket:s3:PutObjects3:PutObjectAcl2.    Review the bucket policy of the associated bucket to confirm that there are no explicit deny statements ("Effect": "Deny") that block the access that you need for the following permissions:s3:PutObjects3:PutObjectAcl3.    If the Amazon VPC that the file gateway is in uses a VPC endpoint for Amazon S3, then review the VPC endpoint policy. Confirm that the policy allows your file gateway to access the S3 bucket and objects.4.    If the associated S3 bucket is encrypted with AWS Key Management Service (AWS KMS), then review the encryption key's policy. The key policy must grant the following permissions to the IAM role that's associated with your file share:kms:Decryptkms:Encryptkms:ReEncryptkms:GenerateDataKeykms:DescribeKeyIf your file share's IAM role and the AWS KMS key belong to different AWS accounts, then these permissions must be set within both the key policy and the IAM role's policy.Reading files from the file shareIf you get the Access Denied error when reading files from the file share, the CloudWatch log is similar to the following:{"severity": "ERROR","bucket": "AWSDOC-EXAMPLE-BUCKET","prefix": "/test1","roleArn": "arn:aws:iam::123456789:role/service-role/StorageGatewayBucketAccessRole0617b6ee-4809-48bc-b646-8dda9e9c32","source": "share-ABCD1234","type": "S3AccessDenied","operation": "s3:HeadObject","gateway": "sgw-ABCD12347","timestamp": "1597488260202"}Review the following permissions settings: 1.    Check the IAM role that's associated with your file share to confirm that it has the following permissions for the associated Amazon S3 bucket:s3:GetObjects3:GetObjectAcl2.    Review the bucket policy of the associated bucket to confirm that there are no explicit deny statements ("Effect": "Deny") that block the access that you need for the following permissions:s3:GetObjects3:GetObjectAcl3.    If the Amazon VPC that the file gateway is in uses a VPC endpoint for Amazon S3, then review the VPC endpoint policy. Confirm that the policy allows your file gateway to access the S3 bucket and objects.4.    If the associated S3 bucket is encrypted with AWS KMS, then review the encryption key's policy. The key policy must grant the following permissions to the IAM role that's associated with your file share:kms:Decryptkms:Encryptkms:ReEncryptkms:GenerateDataKeykms:DescribeKeyIf your file share's IAM role and the AWS KMS key belong to different AWS accounts, then these permissions must be set within both the key policy and the IAM role's policy.Note: The following example IAM policy grants your file share the required permissions for listing a bucket, as well as uploading, downloading, and deleting objects from the bucket (AWSDOC-EXAMPLE-BUCKET):{"Version": "2012-10-17","Statement": [{"Action": ["s3:GetAccelerateConfiguration","s3:GetBucketLocation","s3:GetBucketVersioning","s3:ListBucket","s3:ListBucketVersions","s3:ListBucketMultipartUploads"],"Resource": "arn:aws:s3:::AWSDOC-EXAMPLE-BUCKET","Effect": "Allow"},{"Action": ["s3:AbortMultipartUpload","s3:DeleteObject","s3:DeleteObjectVersion","s3:GetObject","s3:GetObjectAcl","s3:GetObjectVersion","s3:ListMultipartUploadParts","s3:PutObject","s3:PutObjectAcl"],"Resource": "arn:aws:s3:::AWSDOC-EXAMPLE-BUCKET/*","Effect": "Allow"}]}Related informationMonitoring your file gatewayFollow"


Question: Why didn't I receive an SNS notification for my CloudWatch alarm trigger?

"I created an Amazon CloudWatch alarm to send notifications for through an Amazon Simple Notification Service (Amazon SNS) topic when the alarm's state changes. However, when the CloudWatch alarm changes states, I don't receive an SNS notification."

Answer: "I created an Amazon CloudWatch alarm to send notifications for through an Amazon Simple Notification Service (Amazon SNS) topic when the alarm's state changes. However, when the CloudWatch alarm changes states, I don't receive an SNS notification.ResolutionDelivery of SNS notifications depends on the configuration of the SNS topic and the CloudWatch alarm. To determine why you don't receive SNS notifications, check the CloudWatch alarm's history to see the trigger action's status.If your trigger action failed due to SNS access policy restrictions, then the CloudWatch alarm history displays a message similar to the following message:"Failed to execute action arn:aws:sns:us-east-1:ACCOUNT_ID:TOPIC_NAME. Received error: "Resource: arn:aws:cloudwatch:us-east-1:ACCOUNT_ID:alarm:ALARM_NAME is not authorized to perform: SNS:Publish on resource: arn:aws:sns:us-east-1:ACCOUNT_ID:TOPIC_NAME""SNS restricts the sources that can publish messages to the topic using access policies. If a permissions error occurs, then you must add the following permissions under the  Statement section of the SNS access policy. This update grants permissions to the CloudWatch alarms service to publish messages to the SNS topic.Note: Replace us-east-1 with the AWS Region that this notification is for. Replace ACCOUNT_ID with your account ID. Replace TOPIC_NAME with the SNS topic name:{  "Sid": "Allow_Publish_Alarms",  "Effect": "Allow",  "Principal": {    "Service": [      "cloudwatch.amazonaws.com"    ]  },  "Action": "sns:Publish",  "Resource": "arn:aws:sns:us-east-1:ACCOUNT_ID:TOPIC_NAME"}These permissions allow anyone who's using your account to create alarms and publish messages to your SNS topic. To restrict the ability to publish messages to the topic to specific alarms, add global condition keys. The following example uses the ArnLike condition operator and the aws:SourceArn global condition key. For more information, see Example cases for Amazon SNS access control.Note: Note: Replace us-east-1 with the AWS Region that this notification is for. Replace ACCOUNT_ID with your account ID. Replace TOPIC_NAME with the SNS topic name. Replace ALARM_NAME with the alarm name:{  "Sid": "Allow_Publish_Alarms",  "Effect": "Allow",  "Principal": {    "Service": [      "cloudwatch.amazonaws.com"    ]  },  "Action": "sns:Publish",  "Resource": "arn:aws:sns:REGION:ACCOUNT_ID:TOPIC_NAME",  "Condition": {    "ArnLike": {      "aws:SourceArn": "arn:aws:cloudwatch:us-east-1:ACCOUNT_ID:alarm:ALARM_NAME"    }  }}If your trigger action fails due to SNS topic encryption, then the CloudWatch alarm history displays a message similar to the following message:"Failed to execute action arn:aws:sns:us-east-1:ACCOUNT_ID:TOPIC_NAME. Received error: "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException;)""SNS allows encryption at rest for its topic. If SNS uses the default AWS Key Management Service (AWS KMS) key alias/aws/sns for this encryption, then CloudWatch alarms can't publish messages to the SNS topic. The default AWS KMS key's policy for SNS doesn't allow CloudWatch alarms to perform kms:Decrypt and kms:GenerateDataKey API calls. Because this key is AWS managed, you can't manually edit the policy.If the SNS topic must be encrypted at rest, then use a customer managed key. The customer managed key must include the following permissions under the Statement section of the key policy. These permissions allow the CloudWatch alarms to publish messages to encrypted SNS topics:{  "Sid": "Allow_CloudWatch_for_CMK",  "Effect": "Allow",  "Principal": {    "Service": [      "cloudwatch.amazonaws.com"    ]  },  "Action": [    "kms:Decrypt",    "kms:GenerateDataKey*"  ],  "Resource": "*"}If your trigger action succeeded, then the CloudWatch alarm history displays a message similar to the following message:"Successfully executed action arn:aws:sns:us-east-1:ACCOUNT_ID:TOPIC_NAME"This means the CloudWatch alarm successfully published a message to the SNS topic. If the notification wasn't delivered by SNS, then check the SNS topic and its metrics for any delivery failures. For more information, see How do I access Amazon SNS topic delivery logs for push notifications?Note: CloudWatch doesn't test or validate the actions that you specify. It also doesn't detect Amazon EC2 Auto Scaling or Amazon SNS errors that result from an attempt to invoke nonexistent actions. Make sure that your actions exist.Related informationUsing Amazon CloudWatch alarmsEncrypting messages published to Amazon SNS with AWS KMSFollow"


Question: Can I pin an application that's running on AWS to a certificate that was issued by ACM?

I want to know if I can pin an application that's running on AWS to a certificate that was issued by AWS Certificate Manager (ACM).

Answer: "I want to know if I can pin an application that's running on AWS to a certificate that was issued by AWS Certificate Manager (ACM).Short descriptionIt's not a best practice to pin your application to an SSL/TLS certificate issued by ACM. If you pin a certificate, then you provide a browser with an ID for the public key that's used for the website. If a user visits the website, the pin is cached by the browser. That pin is also then used to verify the public key during future visits. The pin information is usually included in the header in the HTTP response and the time to live (TTL) for the pin. If the certificate changes, for example, when the certificate is renewed, then that change can cause website visitors to receive errors. These errors occur because a secure connection to the website can't be established. For more information, see Certificate pinning.Important: Starting October 11, 2022 at 9:00 AM Pacific Time, public certificates obtained through ACM are issued from one of the intermediate CAs that Amazon manages. Multiple intermediate CAs chain to an existing Amazon Trust Services root CA. With this change, leaf certificates issued to you are signed by different intermediate CAs. Before this change, Amazon maintained a limited number of intermediate CAs and issued and renewed certificates from the same intermediate CAs. For more information, see Amazon introduces dynamic intermediate certificate authorities.ResolutionIt's a best practice to pin your application to a root certificate authority (CA) rather than to an individual certificate or an intermediate CA certificate. When you pin an application to an Amazon Trust Services CA, pin the same application to all the CAs in the Amazon trust services table.Note: You must select all the CAs that you pin your application to because, when you request a certificate, ACM doesn't specify the certificate's origin.To pin a certificate, use one of the following options to be sure that the application can connect to the domain.Pin your application to an Amazon root certificateWhen you pin your application at the root certificate level, ACM-managed renewal renews the certificate under the same CA that issued the certificate. The certificate Amazon Resource Name (ARN) remains the same. You can also pin your application to multiple CAs as backup pins. If the certificate expires, then you can request a new certificate and apply the certificate to your load balancer to reduce application downtime.Import your own certificate into ACM, and then pin your application to the imported certificateImported certificates aren't renewed by the ACM-managed renewal process. You must manage the renewal of the certificate and keys. For more information, see Importing certificates into AWS Certificate Manager.Related informationACM best practicesCertificate pinning problemsFollow"


Question: How do I configure service discovery with AWS Cloud Map through the AWS CLI?

How do I create a hosted zone using AWS Cloud Map through the AWS Command Line Interface (AWS CLI)?

Answer: "How do I create a hosted zone using AWS Cloud Map through the AWS Command Line Interface (AWS CLI)?Short descriptionAWS Cloud Map automates DNS configuration and simplifies the provision of instances for services such as Amazon Elastic Container Service (Amazon ECS), AWS Fargate, and Amazon Elastic Kubernetes Service (Amazon EKS).To create a hosted zone with AWS Cloud Map using the AWS SDK or the AWS CLI:1.    Create a DNS namespace (for which a hosted zone is automatically created) to define your service naming scheme.2.    Create your service.3.    Register an instance to your service.ResolutionNote: If you receive errors when running AWS CLI commands, make sure that you’re using the most recent AWS CLI version.Create your DNS namespace1.    Create the namespace using the AWS CLI, replacing example.com with the domain name you want to use.Note: You must choose between creating a public or a private namespace. Public namespaces are visible on the internet as long as the domain name is registered. Private namespaces are visible only within the virtual private cloud (VPC). You must specify the VPC ID when you create a private namespace.To create a public namespace:$ aws servicediscovery create-public-dns-namespace --name example.comTo create a private namespace:$ aws servicediscovery create-private-dns-namespace --name example.com --vpc vpc-0c92f38bf7db24a052.    Note the value of OperationId in the output.For example:{    "OperationId": "igbkufld72o4vbsbwejfi6eyinfprhc3-jkwmz00b"}3.    Find more details about the operation using the get-operation command. Be sure to replace  <OperationId value> with the OperationId value you found in the previous step.aws servicediscovery get-operation --operation-id <OperationId value>4.    In the output, verify that the Status value is SUCCESS. Make note of the NAMESPACE value, which is the namespace ID used to create the service and register the instance.For example:{    "Operation": {        "Status": "SUCCESS",        "CreateDate": 1534428266.699,        "Id": "igbkufld72o4vbsbwejfi6eyinfprhc3-jkwmz00b",        "UpdateDate": 1534428267.113,        "Type": "CREATE_NAMESPACE",        "Targets": {            "NAMESPACE": "ns-f2wjnv2p7pqtz5f2"        }    }}Note: When you create the namespace, Route 53 automatically creates a hosted zone for the domain. The hosted zone's Domain name value is the same domain name as your namespace. The Comment value is Created by Route 53 Auto Naming. To verify the hosted zone:1.    Open the Route 53 console.2.    On the navigation pane, choose Hosted zones.3.    Find your hosted zone in the list of hosted zones in the content pane.Create your service1.    Create the service using the servicediscovery create-service command in shorthand syntax as follows. Be sure to replace workers with your preferred service name. Route 53 uses this service name when creating records.$aws servicediscovery create-service --name workers --dns-config 'NamespaceId="ns-f2wjnv2p7pqtz5f2",RoutingPolicy="WEIGHTED",DnsRecords=[{Type="A",TTL="300"}]'The default routing policy is "MULTIVALUE".  Supported routing policies are "MULTIVALUE" and "WEIGHTED".2.    Note the output. The Id value is the ID of the service you just created.Note: The CreatorRequestId is the ID of the request. If the API call fails, use the CreatorRequestId to repeat the operation.For example:{    "Service": {        "DnsConfig": {            "NamespaceId": "ns-f2wjnv2p7pqtz5f2",            "DnsRecords": [                {                    "Type": "A",                    "TTL": 300                }            ]        },        "CreatorRequestId": "93e0a17a-230b-4c58-b986-f03f3217869f",        "Id": "srv-iy3d7hhlf5cjciph",        "Arn": "arn:aws:servicediscovery:eu-west-1:356906700443:service/srv-iy3d7hhlf5cjciph",        "Name": "workers"    }}Register your instance1.    Register your instance using the servicediscovery register-instance command. Be sure to replace the <value> placeholders with your corresponding values. Note that you can run only one request to register an instance with the same service-id and instance-id options at a time.Important: The API call fails if you don't provide the service-id, instance-id, and attributes parameters. For more details, see "Options" on the register-instance page.$ aws servicediscovery register-instance --service-id srv-iy3d7hhlf5cjciph --instance-id i-039444aa1e2932ca3 --attributes=AWS_INSTANCE_IPV4=172.1.1.12.    Review the output, which includes the OperationId. For example:{    "OperationId": "z7dfqgeadkvwwid2wa2n5ckicrxs255x-jkwr1x9f"}3.    Open the Route 53 console.4.    On the navigation pane, choose Hosted zones.5.    Select the hosted zone you created earlier.6.    Choose Go to Record Sets, and then verify that the record sets are created for the hosted zone.Note: When you register the instance, Route 53 automatically creates a record with the service name and domain name.If you're using Amazon ECS and Route 53 service discovery, you can use the Route 53 namespace and service name to configure your services. Route 53 then automatically creates, deletes, or updates records in your hosted zone according to your Amazon ECS container settings.Related informationService discovery (Amazon ECS)Follow"


Question: How do I build a Lambda deployment package for Node.js?

"I want to build a deployment package for an AWS Lambda function in Node.js, but I get a "Cannot find module" error during invocation."

Answer: "I want to build a deployment package for an AWS Lambda function in Node.js, but I get a "Cannot find module" error during invocation.Short descriptionThe Cannot find module error usually occurs for one of three reasons:The Lambda function's deployment package doesn't have the correct folder structure to allow the Lambda service to load the required modules and libraries.The deployment package doesn't have the correct file permissions.The deployment package doesn't contain the module being imported.Note: Lambda requires global read permissions.ResolutionTo create a deployment package with function code in the root folder of the .zip file and then apply read and execute permissions for all files, do the following.Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.For Linux and macOSInstall dependencies to the function project folderNote: Most Node.js modules are platform-independent, but some are compiled against specific operating system environments. Lambda runs under a Linux environment. When installing modules with npm, it's a best practice to build the .zip file in a Linux environment to make sure that the correct platform dependencies are included.1.    In the command line, change directories to your project folder. For example:cd /project-folder-nameImportant: Make sure to replace project-folder-name with the name of your actual project folder.2.    Install your dependencies locally to your function project folder by running the following command for each module required for your function:Note: Also include the handler source file.npm install package-nameImportant: Make sure to replace package-name with the actual package name. There's also a 250 MB limit on your function size for unzipped files. Include only the libraries that you need for your function to work.For example, to install the AWS SDK for JavaScript modules to the root of a project folder, run the following command:npm install aws-sdkNote: Lambda includes the AWS SDK for JavaScript libraries as part of the base container configuration. To use a different version of the library, you can also include a local copy. For more information about the current Lambda environment and supported libraries, see Lambda runtimes.Build the deployment packageIn the command line, run the following command:zip -r ../function-name.zip .Note: Replace function-name with the file name that you want to give your deployment package. This puts all files in the project folder into a .zip file located in the parent folder.Verify the deployment package1.    In the command line, run the following command:zipinfo ../function-name.zipNote: Replace function-name with the actual file name of your deployment package. Or, you can run unzip -l on the .zip file to list its contents, but the output won't be as detailed.2.    Check the output to verify that the function handler source file is located in the root of the .zip file.3.    Check the output to verify that your files have global read permissions. For more information, see How do I troubleshoot "permission denied" or "unable to import module" errors when uploading a Lambda deployment package?For WindowsBuild the deployment package1.    In File Explorer, open your project folder.2.    Select all the project files, then right-click to open the context menu.3.    Choose Send to, then choose Compressed (zipped) folder.4.    Enter a name for the .zip file.Upload and verify the deployment package1.    In the Lambda console, choose your function.2.    Under Function code, for Code entry type, choose Upload a .zip file.3.    Under Function package, choose Upload.4.    Choose the .zip file you created, and then choose Open.5.    At the top of the console, choose Save.Tip: You can also run update-function-code from the AWS CLI to upload your .zip file.6.    After uploading is completed, choose Test.Tip: You can also use 7-Zip from the command line to verify your deployment package's file permissions. Download it from the 7-Zip website.Related informationDeploy Node.js Lambda functions with .zip file archivesLambda deployment packagesBuilding Lambda functions with Node.jsFollow"


Question: "Why is my Lambda IteratorAge metric increasing, and how do I decrease it?"

I see an increase (or spikes) in my AWS Lambda function's IteratorAge metric.

Answer: "I see an increase (or spikes) in my AWS Lambda function's IteratorAge metric.Short descriptionA Lambda function's iterator age increases when the function can't efficiently process the data that's written to the streams that invoke the function. To decrease your function's IteratorAge metric, you must increase your stream processing throughput.The following factors influence a function's IteratorAge metric:Runtime durationBatch sizeInvocation errorsThrottle occurrenceUnevenly distributed recordsShard countReview this article to understand how each factor affects iterator age. Then, reconfigure your function or data stream to decrease your function's iterator age based on your use case. For more information about Lambda invocations, see Working with AWS Lambda function metrics.Note: For Amazon DynamoDB streams, see Why is the Lambda IteratorAge metric increasing for my Amazon DynamoDB Streams?ResolutionDecrease your function's runtime durationA high runtime duration increases a function's iterator age. Decreasing the duration increases a function's throughput, which decreases a function's iterator age.To decrease your function's runtime duration, do one or both of the following:1.    Increase the amount of memory allocated to the function. Lambda allocates CPU power in proportion to the memory.2.    Optimize your function code so that less time is needed to process records.Note: To get more information on your Lambda duration and performance, see Using AWS Lambda and AWS X-Ray.Increase your stream's batch sizeIf your function's runtime duration is independent from the number of records in an event, then increasing your function's batch size decreases the iterator age.To increase your function's batch size, follow the instructions in Configuring a stream as an event source.Note: If your function's duration is dependent on the number of records in an event, then increasing your function's batch size doesn't decrease the iterator age. For more information, see Working with streams.Make sure that your function gracefully handles invocation errorsInvocation errors can cause a Lambda function to take longer to process an event, or process the same event more than once. Because event records are read sequentially, a function can't progress to later records if a record batch causes an error each time that it's retried. In this situation, the iterator age increases linearly as those records age.If your function returns an error, Lambda continuously retries the batch. The batch retries continue until the processing is successful, the maximum retry attempts is reached, or the data expires from the stream.Make sure that your function gracefully handles records written to the stream. As you develop your function, logging and instrumenting your code can help you diagnose errors.For more information, see the following:Error handling and automatic retries in AWS LambdaMonitoring and troubleshooting Lambda applicationsNew AWS Lambda controls for stream processing and asynchronous invocationsOptimizing batch processing with custom checkpoints in AWS LambdaManage your throttle occurrenceBecause event records are read sequentially, a function can't progress to the next record if the current invocation is throttled. In this situation, Iterator age will increase while Lambda retries the throttled invokes.To manage throttling for your Lambda function, you can request a concurrency increase or review performance issues in the function.Evenly distribute records in the streamPartition keys in each data record determine the shards in the stream that the records are written to. An increase in traffic to your stream with records containing the same partition key causes a shard to receive a disproportionate number of records. This results in a hot shard.Kinesis enhanced shard-level metrics allow you to verify the ingestion rate into each shard and troubleshoot a hot shard.For more information, see Under the hood: scaling your Kinesis data streams.Increase your stream's shard countA low number of shards in a stream increases a function's iterator age. Increasing the number of shards in a stream increases the number of concurrent Lambda functions consuming from your stream, which decreases a function's iterator age.To increase your stream's shard count, follow the instructions in Resharding a stream.Note: Shard splitting doesn't have an immediate effect on a function's iterator age. Existing records remain in the shards that they were written to. Those shards must catch up on their backlog before the iterator age for the shards decreases. For more information, see Working with streams.Increase your stream processing throughput by testing different parallelization factor settings and using enhanced fan-outTo test parallelization factor settingsYou can improve stream processing by configuring your function's parallelization factor to increase the number of concurrent Lambda invocations for each shard of a stream. This is done by specifying the number of concurrent batches that Lambda polls from each shard. This is configured on the event source configuration.If your parallelization factor is set to 10, you can have up to 50 concurrent Lambda invocations to process five Kinesis data shards.For example, concurrent runs = number of shards x concurrent batches per shard (parallelization Factor).For more information, see Using AWS Lambda with Amazon Kinesis and New AWS Lambda scaling controls for Kinesis and Amazon DynamoDB event sources.Note: When increasing the number of concurrent batches per shard, Lambda validates in-order processing at the partition key level.To use enhanced fan-outYou can reduce latency and increase read throughput by creating a data stream consumer with enhanced fan-out. Stream consumers get a dedicated connection to each shard that doesn't impact other applications that are also reading from the stream.For more information, see Developing custom consumers with dedicated throughput (enhanced fan-out) and Using AWS Lambda with Amazon Kinesis.Note: It's a best practice to use enhanced fan-out if you have many applications reading the same data, or if you're reprocessing streams with large records.Related informationBest practices for working with Lambda functionsLambda event source mappingsAWS Lambda function scalingResharding, scaling, and parallel processingConfiguring your data stream and functionFollow"


Question: How can I troubleshoot a failed CodeDeploy deployment on Amazon EC2 instances?

My AWS CodeDeploy deployment on Amazon Elastic Compute Cloud (Amazon EC2) instances failed.

Answer: "My AWS CodeDeploy deployment on Amazon Elastic Compute Cloud (Amazon EC2) instances failed.Short descriptionYou can use the AWS Systems Manager AWSSupport-TroubleshootCodeDeploy Automation runbook to troubleshoot failed deployments. The runbook helps you identify when a deployment fails for the following reasons:The CodeDeploy agent isn't installed or isn't running on the instance.The required instance profile is missing.The instance profile doesn't have correct Amazon Simple Storage Service (Amazon S3) permissions.There's an issue with one of the lifecycle hooks that's managed by CodeDeploy, such as AllowTraffic or BlockTraffic.There's an issue with one of the customer-managed lifecycle hooks.An issue occurred with an Auto Scaling group scale down event during the deployment.An AppSpec file is missing or incorrectly formatted.ResolutionImportant: Use the AWSSupport-TroubleshootCodeDeploy runbook in the same AWS Region where your CodeDeploy application is located.1.    Open the AWS Systems Manager console.2.    In the navigation pane, in the Change Management section, choose Automation.3.    Choose Execute automation.4.    On the Owned by Amazon tab, in the Automation document search box, enter AWSSupport-TroubleshootCodeDeploy. Then, select the search icon, or press Enter on your keyboard.5.    Select the radio button on the AWSSupport-TroubleshootCodeDeploy card.Note: Make sure that you select the radio button and not the hyperlinked automation name.6.    In the Document details section, choose Next.7.    In the Input parameters section, for DeploymentId, enter the deployment ID that failed.8.    For InstanceID, enter the instance ID where the deployment failed.9.    For AutomationAssumeRole, enter the Amazon Resource Name (ARN) of the role that allows Systems Manager Automation to perform actions.Note: If an AWS Identity and Access Management (IAM) role isn’t specified, Systems Manager Automation uses permissions of the IAM user role that runs the runbook. For more information about creating the assume role for Systems Manager Automation, see Task 1: Create a service role for Automation.Important: Either the AutomationAssumeRole or user role must have permissions for the following actions: codedeploy:GetDeployment, codedeploy:GetDeploymentTarget, and ec2:DescribeInstances.10.    Choose Execute.The runbook's output gives troubleshooting steps and recommendations for how to resolve the issue that caused your deployment failure.Related informationTroubleshooting CodeDeployTroubleshoot EC2/on-premises deployment issuesFollow"