Question: How do I view traffic passing through an Amazon Route 53 resolver outbound endpoint?

I want to view traffic passing through Amazon Route 53 resolver outbound endpoint. How can I do this?

Answer: "I want to view traffic passing through Amazon Route 53 resolver outbound endpoint. How can I do this?Short descriptionTo view traffic passing through Route 53 resolver endpoints, configureAmazon Virtual Private Cloud (Amazon VPC) Traffic Mirroring.ResolutionConfigure network connectivityConfirm the target EC2 instance's security group and network access control list (network ACL) allow incoming traffic on UDP port 4789 from the outbound endpoint elastic network interface.Confirm the target EC2 instance has connectivity to the outbound endpoint's network interface subnet.Confirm the outbound endpoint network interface subset is configured for outgoing traffic for the EC2 instance on UPD port 4789. The subset configuration includes network ACL, security groups, and routing tables.Set up Amazon VPC Traffic Mirroring1.    Create a traffic mirror target using the network interface of the EC2 instance you're using as the target.2.    Create a mirror filter to identify the DNS traffic from the outbound endpoint network interface to the EC2 mirror target.Example mirror filter for Route 53Note: The example values in this table represent the following:VPC A is associated with Route 53 resolve rule to forward *.test.com domain DNS queries to on-premise networkOn-premise network is hosting domain *.test.comValueInbound RuleOutbound RuleRule numberRule priorityRule priorityRule ActionAcceptAcceptProtocolUDP and TCPUDP and TCPSource port range531024-65535Destination port range1024-6553553Source CIDR blockOn-premise CIDRVPC A CIDRDestination CIDR blockVPC A CIDROn-premise CIDR3.    Create a mirror session for each outbound endpoint network interface to the mirror EC2 instance. Use the following values:            Mirror source: outbound endpoint network interfaceMirror target: traffic mirror that you created previouslySession number: 1Filter: mirror filter that you created previouslyView mirrored trafficFor Linux operating systems1.    View the captured traffic logs by running the following command:sudo tcpdump -w <filename>.pcap -i <eth> port 4789For filename, use the filename where you want to store the captured traffic logs. For eth, use the ethernet port that you want to use on your EC2 instance. 2.    Transfer the file from the EC2 instance to your local computer by running the following command:scp -i <keypair>.pem ec2-user@<ec2 instance's public/private DNS name or IP address>:<file path>/<filename>.pcap ~/Desktop/For keypair, use the keypair you used to log into the instance. For filename, use the filename where you want to store the captured traffic logs.3.    Open the capture file to view the DNS packets.For windows operating systems1.    Open the Wireshark tool.2.    Filter traffic using the IP address of the outbound resolver endpoint.3.    Open the capture file to view the DNS packets.Related informationResolving Domain Name System (DNS) queries between VPCs and your networkFollow"


Question: How do I send my container logs to multiple destinations in Amazon ECS on AWS Fargate?

"I want to forward the logs of my application container that runs on AWS Fargate to multiple destinations. These destinations could be Amazon CloudWatch, Amazon Kinesis Data Firehose, or Splunk."

Answer: "I want to forward the logs of my application container that runs on AWS Fargate to multiple destinations. These destinations could be Amazon CloudWatch, Amazon Kinesis Data Firehose, or Splunk.Short descriptionAn Amazon Elastic Container Service (Amazon ECS) task definition allows you to specify only a single log configuration object for a given container, which means that you can forward logs to a single destination only. To forward logs to multiple destinations in Amazon ECS on Fargate, you can use FireLens.Note: FireLens works with both Fluent Bit and Fluentd log forwarders. The following resolution considers Fluent Bit because Fluent Bit is more resource-efficient than Fluentd.Consider the following:FireLens uses the key-value pairs specified as options in the logConfiguration object from the ECS task definition to generate the Fluent Bit output definition. The destination where the logs are routed is specified in the [OUTPUT] definition section of a Fluent Bit configuration file. For more information, see the Output section of Configuration File on the Fluent Bit website.FireLens creates a configuration file on your behalf, but you can also specify a custom configuration file. You can host this configuration file in either Amazon Simple Storage Service (Amazon S3), or create a custom Fluent Bit Docker image with the custom output configuration file added to it.If you're using Amazon ECS on Fargate, then you can't pull a configuration file from Amazon S3. Instead, you must create a custom Docker image with the configuration file.ResolutionCreate AWS Identity and Access Management (IAM) permissionsCreate IAM permissions to allow your task role to route your logs to different destinations. For example, if your destination is Kinesis Data Firehose, then you must give the task permission to call the firehose:PutRecordBatch API.Note: Fluent Bit supports several plugins as log destinations. Permissions required by destinations like CloudWatch and Kinesis streams include logs:CreateLogGroup, logs:CreateLogStream, logs:DescribeLogStreams, logs:PutLogEvents,and kinesis:PutRecords.Create a Fluent Bit Docker image with a custom output configuration file.1.    Create a custom Fluent Bit configuration file called logDestinations.conf with your choice of [OUTPUT] definitions defined in it. For example, the following configuration file includes configurations defined for CloudWatch, Kinesis Data Firehose, and Splunk.[OUTPUT]    Name                firehose    Match               YourContainerName*    region              us-west-2    delivery_stream     nginx-stream  [OUTPUT]    Name                cloudwatch    Match               YourContainerName*    region              us-east-1    log_group_name      firelens-nginx-container    log_stream_prefix   from-fluent-bit    auto_create_group   true   [OUTPUT]    Name                splunk    Match               <ContainerName>*    Host                127.0.0.1    Splunk_Token        xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx    Splunk_Send_Raw     OnNote: Different destinations require different fields to be specified in the [OUTPUT] definition. For examples, see Amazon ECS FireLens examples.2.    Create a Docker image with a custom Fluent Bit output configuration file using the following Dockerfile example:FROM amazon/aws-for-fluent-bit:latestADD logDestinations.conf /logDestinations.confNote: For more information, see Dockerfile reference on the Docker website.3.    To create the custom fluent-bit Docker image using the Dockerfile that you created in step 2, run the following command:docker build -t custom-fluent-bit:latest .Important: Be sure to run the docker build command in the same location as the Dockerfile.4.    To confirm that the Docker image is available to Amazon ECS, push your Docker image to Amazon Elastic Container Registry (Amazon ECR) or your own Docker registry. For example, to push a local Docker image to Amazon ECR, run the following command:docker push aws_account_id.dkr.ecr.region.amazonaws.com/custom-fluent-bit:latest5.    In your task definition (TaskDefinition), update the options for your FireLens configuration (firelensConfiguration). For example:{   "containerDefinitions":[      {         "essential":true,         "image":"aws_account_id.dkr.ecr.region.amazonaws.com/custom-fluent-bit:latest",         "name":"log_router",         "firelensConfiguration":{            "type":"fluentbit",            "options":{               "config-file-type":"file",               "config-file-value":"/logDestinations.conf"            }         }      }   ]}When you update the options for your FireLens configuration, consider the following:To specify a custom configuration file, you must include the config-file-type and config-file-value options in your FireLens configuration file. You can only set these options when you create a task definition with the AWS Command Line Interface (AWS CLI).Note: If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI.You must modify the image property in the containerDefinition section of your configuration to reflect a valid Amazon ECR image location. You can specify images in Amazon ECR repositories by using the full registry/repository:tag naming convention. For example:aws_account_id.dkr.ecr.region.amazonaws.com/custom-fluent-bit:latestTo use other repositories, see the image property of the task definition.Follow"


Question: How can I troubleshoot access denied or unauthorized operation errors with an IAM policy?

I am trying to perform an action on an AWS resource and I received an "access denied" or "unauthorized operation" error. How can I troubleshoot these permission issues?

Answer: "I am trying to perform an action on an AWS resource and I received an "access denied" or "unauthorized operation" error. How can I troubleshoot these permission issues?Short descriptionTo troubleshoot issues with AWS Identity and Access Management (IAM) policies:Identify the API callerCheck the IAM policy permissionsEvaluate service control policies (SCPs)Review identity-based and resource-based policiesCheck for permission boundariesEvaluate session policiesMake sure that the condition keys in the policy are supported by the APIsReview the IAM policy errors and troubleshooting examplesResolutionIdentify the API caller and understand the error messagesImportant:Before you begin, be sure that you have installed and configured the AWS Command Line Interface (AWS CLI).If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI.Be sure that the API calls are made on behalf of the correct IAM entity before reviewing IAM policies. If the error message doesn't include the caller information, then follow these steps to identify the API caller:Open the AWS Management Console.In the upper-right corner of the page, choose the arrow next to the account information.If you're signed in as an IAM role, refer to "Currently active as" for the assumed role's name, and "Account ID" for account ID.If you're signed in as a federated user, refer to "Federated User" for the federation role name and role session name.-or-Use the AWS CLI command get-caller-identity to identify the API caller. You can also use the AWS CLI command with the --debug flag to identify the source of the credentials from the output similar to the following:2018-03-13 16:23:57,570 - MainThread - botocore.credentials - INFO - Found credentials in shared credentials file: ~/.aws/credentialsCheck the IAM policy permissionsVerify if the necessary permissions are granted to the API caller by checking the attached IAM policies. For more information, see Determining whether a request is allowed or denied within an account.Evaluate AWS Organizations SCPsIf the AWS account is a part of an AWS Organization, SCPs can be applied at the hierarchical level to allow or deny actions. The SCP permissions are inherited by all IAM entities in the AWS account. Make sure that the API caller isn't explicitly denied in the SCP.Make sure that the API being called isn't explicitly denied in an Organizational SCP policy that impacts the callerReview identity-based and resource-based policiesMake sure that there is an explicit allow statement in the IAM entities identity-based policy for the API caller. Then, make sure that the API supports resource-level permissions. If the API caller doesn't support resource-level permissions, make sure the wildcard "*" is specified in the resource element of the IAM policy statement.You can attach resource-based policies to a resource within the AWS service to provide access. For more information, see Identity-based policies and resource-based policies.To view the IAM policy summary:Open the IAM console.In the navigation pane, choose Policies.Choose the arrow next to the policy name to expand the policy details view.In the following example, the policy doesn't work because not all Amazon Elastic Compute Cloud (Amazon EC2) API actions support resource-level permissions:{    "Version": "2012-10-17",    "Statement": [        {            "Sid": "SorryThisIsNotGoingToWorkAsExpected",            "Effect": "Allow",            "Action": ["ec2:*"],            "Resource": "arn:aws:ec2:us-east-1:accountid:instance/*"        }    ]}IAM users that try to launch an Amazon EC2 instance in the us-east-1 Region with the run-instances AWS CLI command receive an error message similar to the following:"An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. Encoded authorization failure message:…"To resolve this, change the resource to a wildcard "*". This is because Amazon EC2 only supports partial resource-level permissions.To decode the authorization failure message to get more details on the reason for this failure, use the DecodeAuthorizationMessage API action similar to the following:$ aws sts decode-authorization-message --encoded-message <encoded-message-from-the-error>Check for permission boundariesIf the IAM entity has a permission boundary attached, the boundary sets the maximum permissions that the entity has.Evaluate session policiesIf the API caller is an IAM role or federated user, session policies are passed for the duration of the session. The permissions for a session are the intersection of the identity-based policies for the IAM entity used to create the session and the session policies. Make sure that the API call exists in the IAM policy and entity.Make sure that the condition keys in the policy are supported by the APIsAWS condition keys can be used to compare elements in an API request made to AWS with key values specified in a IAM policy. The condition keys can either be a global condition key or defined by the AWS service. AWS service specific condition keys can only be used within that service (for example EC2 conditions on EC2 API actions).For more information, see Actions, resources, and condition context keys for AWS services.A condition element can contain multiple conditions, and within each condition block can contain multiple key-value pairs. For more information, see Creating a condition with multiple keys or values.In this example policy, the condition element is matched if an IAM API request is called by the IAM user admin and the source IP address is from 1.1.1.0/24 or 2.2.2.0/24.{  "Version": "2012-10-17",  "Statement": [    {      "Effect": "Allow",      "Action": "iam:*",      "Resource": "*",      "Condition": {        "StringEquals": {          "aws:username": "admin"        },        "IpAddress": {          "aws:SourceIp": [            "1.1.1.0/24",            "2.2.2.0/24"          ]        }      }    }  ]}IAM policy errors and troubleshooting examplesSee the following examples to identify the error message, the API caller, the API, and the resources being called:Example error messageAPI callerAPIResourcesWhenA: "An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation."unknownDescribeInstancesunknowntime of the error occursB: "An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::123456789012:user/test is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::123456789012:role/EC2-FullAccess"arn:aws:iam::123456789012:user/testAssumeRolearn:aws:iam::123456789012:role/EC2-FullAccesstime of the error occursC: "An error occurred (AccessDenied) when calling the GetSessionToken operation: Cannot call GetSessionToken with session credentials"unknownGetSessionTokenunknowntime of the error occursD: "An error occurred (UnauthorizedOperation) when calling the AssociateIamInstanceProfile operation: You are not authorized to perform this operation. Encoded authorization failure message: ...."unknownAssociateIamInstanceProfileunknowntime of the error occursUsing this evaluation method, you can identify the cause of the error messages you can receive for permission issues for different AWS services. For more details, see the following error messages and troubleshooting steps:Example error message A:This error message indicates that you don't have permission to call the DescribeInstances API.To resolve this error, follow these steps:Identify the API caller.Confirm that the ec2:DescribeInstances API action isn't included in any deny statements.Confirm that the ec2:DescribeInstances API action is included in the allow statements.Confirm that there's no resource specified for this API action. Note: This API action doesn't support resource-level permissions.Confirm that all IAM conditions specified in the allow statement are supported by the DescribeInstances action and that the conditions are matched.For more information, see DescribeInstanceStatus.Example error message B:This error message includes the API name, API caller, and target resource. Be sure that the IAM identity that called the API has the correct access to the resources. Review the IAM policies using the previous evaluation method.To resolve this error, follow these steps to confirm the trust policy of IAM role: EC2-FullAccess:Confirm arn:aws:iam::123456789012:user/test or arn:aws:iam::123456789012:root isn't included in any deny statement of the trust policy.Confirm arn:aws:iam::123456789012:user/test or arn:aws:iam::123456789012:root is included in the allow statement of the trust policy.Confirm all IAM conditions specified in that allow statement are supported by sts:AssumeRole API action and matched.Follow these steps to confirm the IAM policies attached to the API caller (arn:aws:iam::123456789012:user/test):Confirm arn:aws:iam::123456789012:role/EC2-FullAccess isn't included in any deny statement with sts:AssumeRole API action.If arn:aws:iam::123456789012:root is in the allow statement of the trust policy, then confirm arn:aws:iam::123456789012:role/EC2-FullAccess is included in the allow statement of the IAM policies with sts:AssumeRole API action.Confirm all IAM conditions specified in that allow statement are supported by sts:AssumeRole API action and match.Example error message C:This error message indicates that get-session-token isn't supported by temporary credentials. For more information, see Comparing the AWS STS API operations.Example error message D:This error message returns an encoded message that can provide details about the authorization failure. To decode the error message and get the details of the permission failure, see DecodeAuthorizationMessage. After decoding the error message, identify the API caller and review the resource-level permissions and conditions.To resolve this error, follow these steps to review the IAM policy permissions:If the error message indicates that the API is explicitly denied, then remove ec2:AssociateIamInstanceProfile or iam:PassRole API actions from the matched statement.Confirm that ec2:AssociateIamInstanceProfile and iam:PassRole are in the allow statement with supported and correct resource targets. For example, confirm that the resource targets of ec2:AssociateIamInstanceProfile API action are EC2 instances and the resource targets of iam:PassRole are IAM roles.If ec2:AssociateIamInstanceProfile and iam:PassRole API actions are in the same allow statement, confirm that all conditions are supported by ec2:AssociateIamInstanceProfile and iam:PassRole API action and that the conditions match.If ec2:AssociateIamInstanceProfile and iam:PassRole API actions are in separate allow statements, confirm that all conditions in each allow statement are supported by an action and that the conditions match.For more information, see Policy evaluation logic and Determining whether a request is allowed or denied within an account.Related informationTroubleshoot IAM policiesWhy did I receive an "AccessDenied" or "Invalid information" error trying to assume a cross-account IAM role?IAM JSON policy elements referenceFollow"


Question: How do I customize my nginx configuration to modify the "client_max_body_size" in Elastic Beanstalk?

I want to upload large size files to my AWS Elastic Beanstalk environment without receiving the error message "413 Request Entity Too Large".

Answer: "I want to upload large size files to my AWS Elastic Beanstalk environment without receiving the error message "413 Request Entity Too Large".Short descriptionBy default, NGINX has a limit of 1MB on file uploads. If the size of a request exceeds the configured value, then the 413 Request Entity Too Large error is returned. To upload files larger than 1 MB, configure the client_max_body_size directive in the NGINX configuration files.Important: M and MB are equivalent expressions for "megabyte". For example, 2M is equal to 2 MB. However, use only M in your configuration file, as MB isn't valid in a configuration file.ResolutionTo configure the client_max_body_size in Amazon Linux 2 environments, do the following:1.    To extend the Elastic Beanstalk default NGINX configuration, add the .conf configuration file client_max_body_size.conf that includes the following:client_max_body_size 50M;Note: In the preceding example, the value of the client_max_body_size is updated to 50M. Substitute any value in place of 50 as per your requirements.2.    Copy the .conf configuration file client_max_body_size.conf to a folder named .platform/nginx/conf.d/ in your application source bundle. The Elastic Beanstalk NGINX configuration includes .conf files in this folder automatically. Make sure to create this path if it doesn't exist in your source bundle. The following example shows the structure of the .platform directory and .conf file in the application zip file:-- .ebextensions       -- other non nginx server config files            -- .platform       -- nginx           -- conf.d                 -- client_max_body_size.conf                   -- other application filesThe file client_max_body_size.conf has a path like this: my-app/.platform/nginx/conf.d/client_max_body_size.conf.3.    Deploy your code and the new .platform/ directory together as a new application version in your Elastic Beanstalk environment.4.    After the deployment is completed, log in to the instance running on the Elastic Beanstalk environment. After logging in, check that the settings to the NGINX server are applied. To do this, use the following command:$ sudo nginx -T | egrep -i "client_max_body_size"nginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successfulclient_max_body_size 50M;Follow"


Question: How do I troubleshoot BGP connection issues over VPN?

My BGP session can't establish a connection or is in an idle state over my VPN tunnel. How can I troubleshoot this?

Answer: "My BGP session can't establish a connection or is in an idle state over my VPN tunnel. How can I troubleshoot this?ResolutionTo troubleshoot BGP connection issues over VPN, check the following:Check the underlying VPN connectionFor BGP-based VPN connections, the BGP session can be established only if the VPN tunnel is up. If the VPN tunnel is down or flapping, then you experience issues with establishing the BGP session. Verify that the VPN is up and stable. If the VPN isn't coming up or it isn't stable, see the following:Why is IKE (phase 1 of my VPN tunnel) failing in Amazon VPC?I can’t establish my VPN tunnel: IPsec is failingHow do I troubleshoot VPN tunnel inactivity or instability or tunnel down on my customer gateway device?Check the BGP configuration on your customer gateway deviceThe IP addresses of the local and remote BGP peers must be configured with the downloaded VPN configuration file from the VPC console.The local and remote BGP Autonomous System Numbers (ASN) must be configured with the downloaded VPN configuration file from the VPC console.If the configuration settings are correct, then ping the remote BGP peer IP from your local BGP peer IP to verify the connectivity between BGP peers.Be sure that the BGP peers are directly connected to each other. External BGP (EBGP) multi-hop is turned off on AWS.Note: If your BGP session is flapping between active and connect states, verify that TCP port 179 and other relevant ephemeral ports are not blocked.Debugs and packet capturesIf the BGP configuration on the customer gateway is verified and the pings between the BGP peer IPs are working, then collect this information from the customer gateway device for further analysis:BGP and TCP debugsBGP logsPacket captures for traffic between the BGP peer IPsCheck if the BGP session is going from established to idle statesFor VPN on a VGW, if you see the BGP session going from established to idle state, then verify the number of routes that you are advertising over the BGP session. You can advertise up to 100 routes over the BGP session. If the number of routes advertised over the BGP session is more than 100, then the BGP session goes to the idle state.To resolve this, do one of the following:Advertise a default route to route to AWS, or summarize the routes so that the number of routes received is fewer than 100.-or-You can migrate your VPN connection to a transit gateway as transit gateway supports 1,000 routes advertised from a customer gateway.For more information, see Site-to-Site VPN quotas.Related informationHow can I troubleshoot BGP connection issues over Direct Connect?Amazon VPC FAQsFollow"


Question: How do I troubleshoot issues with IP-based routing in Route 53?

I see unexpected results when testing the DNS resolution on my Amazon Route 53 IP-based routing policy.

Answer: "I see unexpected results when testing the DNS resolution on my Amazon Route 53 IP-based routing policy.ResolutionExample scenarioYou have IP-based routing records for clients with the CIDR 172.32.0.0/16 and 172.33.0.0/16 pointing towards two Elastic Load Balancing (ELB) load balancers. One ELB load balancer is located in Virginia (us-east-1) and the other is in Ireland (eu-west-1). Clients with CIDR 172.32.0.0/16 resolve the domain to the load balancer in us-east-1. Clients with CIDR 172.33.0.0/16 resolve the domain to the load balancer in eu-west-1. However, clients aren't receiving the expected output.Note: IP-based routing isn't supported for private hosted zones.To troubleshoot IP-based routing, complete the following steps:1.    Confirm that you correctly configured the IP-based resource records for your Route 53 hosted zone for your use case. Open the Route 53 console, and check the default location that's specified in your Route 53 hosted zone configuration.Note: If CIDR blocks aren't specified in the CIDR collection that matches the source IP address, then Route 53 answers with the default "*" location.Route 53 answers with NODATA if the following are true:A default “*” location isn't specified.The query originates from a CIDR block that doesn't match any specified CIDR blocks in the CIDR collection.Route 53 matches DNS queries that have a CIDR that's longer than your specified CIDR to the shorter specified CIDR in the CIDR collection. For example, if you specify 2001:db8::/32 as the CIDR in your CIDR collection and receive a query from 2001:0db8:1234::/48, then the CIDR matches. If, you specify 2001:db8:1234::/48 in your CIDR collection and receive a query from 2001:db8::/32, then it doesn't match. Route 53 answers with the record for the “*” location.For CIDR collection and CIDR block limit quotas, see Quotas on records.2.    Check if the client resolves correctly.If the client is resolving within the virtual private cloud (VPC) and using VPC DNS .2 resolver, then IP-based routing doesn't work. This is because the .2 resolver doesn't support EDNS Client Subnet (ECS).If the client is resolving outside of the VPC, then run the following command to verify that your DNS resolver supports EDNS0:Linux or macOSdig TXT o-o.myaddr.google.com -4Windowsnslookup -type=txt o-o.myaddr.google.comThe following example output shows DNS resolvers that don't support EDNS0:$ dig TXT o-o.myaddr.google.com -4; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.amzn2.5.2 <<>> TXT o-o.myaddr.google.com -4;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 38328;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1;; OPT PSEUDOSECTION:; EDNS: version: 0, flags:; udp: 4096;; QUESTION SECTION:;o-o.myaddr.google.com. IN TXT;; ANSWER SECTION:o-o.myaddr.google.com. 60 IN TXT "3.209.83.70"The following example output shows DNS resolvers that do support EDNS0:$ dig TXT o-o.myaddr.google.com -4 @8.8.8.8; <<>> DiG 9.11.4-P2-RedHat-9.11.4-26.P2.amzn2.5.2 <<>> TXT o-o.myaddr.google.com -4 @8.8.8.8;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 30624;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1;; OPT PSEUDOSECTION:; EDNS: version: 0, flags:; udp: 512;; QUESTION SECTION:;o-o.myaddr.google.com. IN TXT;; ANSWER SECTION:o-o.myaddr.google.com. 60 IN TXT "172.253.8.137"o-o.myaddr.google.com. 60 IN TXT "edns0-client-subnet 54.82.0.0/24"3.    To check DNS resolution, use your hosted zone's authoritative name server to resolve the record. Run the following command. In the following example command, replace example.com with your domain.dig A example.com +subnet=172.3.0.0/16 @ns-1875.awsdns-42.co.ukOr, use dig or nslookup to verify that the DNS resolution works as expected. In the following example commands, replace example.com with your domain.dig example.com @8.8.8.8nslookup example.com 8.8.8.84.    If you configure health check records for IP-based resource records, then use these records to verify the health status. If a health check fails for a record with a default (*) location, then Route 53 returns the default location as a DNS query response.Related informationIP-based routingFollow"


Question: "How can I find who stopped, rebooted, or terminated my EC2 Windows instance?"

"My Amazon Elastic Compute Cloud (Amazon EC2) Windows instance was unexpectedly stopped, rebooted, or terminated. How can I identify who stopped, restarted, or terminated the instance?"

Answer: "My Amazon Elastic Compute Cloud (Amazon EC2) Windows instance was unexpectedly stopped, rebooted, or terminated. How can I identify who stopped, restarted, or terminated the instance?ResolutionAn EC2 Windows instance can be stopped or rebooted either through AWS or through the Windows operating system. An EC2 Windows instance can be terminated only through AWS.If the instance was stopped, rebooted, or terminated through AWSYou can stop, reboot, or terminate your instance through AWS from:The AWS Management ConsoleThe AWS Command Line Interface (AWS CLI)AWS Tools for PowerShellAWS APIsAWS SDKIf the event occurred in the last 90 days, then you can get more information about the event using AWS CloudTrail logs. To view the event on CloudTrail, follow these steps:Open the CloudTrail console.In the navigation pane, choose Event history.In the Lookup attributes dropdown menu, select Event name.For Enter an event name, enter StopInstances if your instance was stopped. Enter RebootInstances if your instance was rebooted. Enter TerminateInstances if your instance was terminated.To see more information about an event, choose the event name. On the StopInstances, RebootInstances, or TerminateInstances details page, you can see the user of the AWS Identity and Access Management (IAM) that initiated the event.If the instance was stopped or rebooted within the Windows OSIf the instance wasn't stopped or rebooted through AWS, then the event was likely initiated within the Windows OS. To find more information about this event within the Windows OS, follow these steps while logged in to the instance:Open Event Viewer.On the navigation pane, expand Windows Logs and then choose System.On the Actions pane, choose Filter Current Log.In the All Event IDs field, enter 1074 or 1076.The event log indicates which user initiated the event in the Source field.Note: An EC2 Windows stop or reboot can occur at the Windows OS level when:A user is logged into the instance and a Windows update reboots the OS.An unexpected hardware failure occurs.An AWS planned maintenance event stops or restarts the instance.A third-party tool issued the command.AWS sends notifications about planned instance retirements and unexpected hardware failure over email or on your Personal Health Dashboard.Follow"


Question: How can I resolve issues accessing an encrypted AWS Secrets Manager secret?

"I want to retrieve or access an AWS Secrets Manager secret, but I receive an error."

Answer: "I want to retrieve or access an AWS Secrets Manager secret, but I receive an error.ResolutionIf you can't retrieve or access a Secrets Manager secret, then you might see one of the following errors: "You can't access a secret from a different AWS account if you encrypt the secret with the default KMS service key.""Access to KMS is not allowed""InternalFailure""An unknown error occurred""Access to KMS is not allowed. This version of secret is not encrypted with the current KMS key."To troubleshoot any of these errors, complete the following steps.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.Verify that the secret isn't encrypted with an AWS KMS managed key when accessing a secret in another account.AWS managed key policies can't be edited because they're read-only. However, you can view AWS Key Management Service (AWS KMS) managed key and customer managed key policies. Because AWS KMS managed key policies can't be edited, cross-account permissions can't be granted for these key policies. Secrets Manager secrets that are encrypted using an AWS KMS managed key can't be accessed by other AWS accounts.For cross accounts, verify that the identity-based policy and resource-based policy allows the principal to access the AWS KMS key.The identity policy should allow the principal to access the AWS KMS key, similar to the following:{  "Version": "2012-10-17",  "Statement": [    {      "Effect": "Allow",      "Action": "kms:Decrypt",      "Resource": "arn:aws:kms:Region:AccountID:key/EncryptionKey"    }  ]}The resource-based policy should allow the principal to access the AWS KMS key, similar to the following:{  "Effect": "Allow",  "Principal": {    "AWS": [      "arn:aws:iam::AccountID:user/UserName",      "arn:aws:iam::AccountID:role/RoleName"    ]  },  "Action": [    "kms:Decrypt",    "kms:DescribeKey"  ],  "Resource": "*"}After the AWS KMS key is updated, verify that the secret is encrypted with the new AWS KMS key.Updating the AWS KMS key associated with a Secrets Manager secret using the AWS CLI doesn't re-encrypt current or previous versions of the secret with the new KMS key. This means that external accounts, also called cross-accounts, can't access the secret because the secret hasn't been re-encrypted with the new AWS KMS key. You must re-encrypt the secret using the new AWS KMS key to retrieve the secret value from the cross-account.Note: Using the Secrets Manager console to change the AWS KMS key associated with a secret by default creates a new version of the secret and encrypts it with the new AWS KMS key. For more information, see Secret encryption and decryption in AWS Secrets Manager.Re-encrypt the secret with the new AWS KMS key.Follow these steps to re-encrypt the secret with the new AWS KMS key using the AWS Management Console or the AWS CLI.AWS Management Console1.    Open the Secrets Manager console.2.    In Secret name, choose your secret.3.    Choose Actions, and then choose dropdown list, select the AWS KMS key, select the check box for Create new version of secret with new encryption key, and then choose Save.AWS CLIFollow these steps from the source account where the secret resides.1.    Run the AWS CLI command get-secret-value similar to the following:$ aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:123456789012:secret:cross-account --query SecretString --output text    {"CrossAccount":"DefaultEncryption"}2.    Create a file named creds.txt.$ cat creds.txt    {"CrossAccount":"DefaultEncryption"}3.    Run the AWS CLI update-secret command to re-encrypt the encryption key similar to the following:.    Note: If you use a customer managed key, you must also have kms:GenerateDataKey and kms:Decrypt permissions on the key.$ aws secretsmanager update-secret --secret-id arn:aws:secretsmanager:us-east-1:123456789012:secret:cross-account --secret-string file://creds.txt    {    "ARN": "arn:aws:secretsmanager:us-east-1:123456789012:cross-account",    "Name": "cross-account",    "VersionId": "f68246e8-1cfb-4c3b-952b-17c9298d3462"    }4.    Run the AWS CLI command get-secret-value from the cross-account similar to the following:$ aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:123456789012:secret:cross-account --version-stage AWSCURRENT --profile    {"CrossAccount":"DefaultEncryption"}Related informationHow to use resource-based policies in the AWS Secrets Manager console to securely access secrets across AWS accountsHow do I share AWS Secrets Manager secrets between AWS accounts?Permissions to AWS Secrets Manager secrets for users in a different accountFollow"


Question: How do I resolve data incompatibility errors in Redshift Spectrum?

"I'm trying to use an external schema, object, or file format in Amazon Redshift Spectrum. However, I receive an error. How do I troubleshoot this error?"

Answer: "I'm trying to use an external schema, object, or file format in Amazon Redshift Spectrum. However, I receive an error. How do I troubleshoot this error?ResolutionIncompatible data format errorTo resolve your incompatible data format error in Redshift Spectrum, perform the following steps:1.    Retrieve the complete error message from the SVL_S3LOG system view:select * from SVL_S3LOG where query = '<query_ID_of_the_Spectrum_query>';A mismatch in incompatible Parquet schema produces the following error message:File 'https://s3bucket/location/file has an incompatible Parquet schema for column ‘s3://s3bucket/location.col1'. Column type: VARCHAR, Par...2.    Check the Message column to view the error description. The error description explains the data incompatibility between Redshift Spectrum and the external file.3.    FSPCheck the schema of your external file, and then compare it with the column definition in the CREATE EXTERNAL TABLE definition.4.    (Optional) If the column definition in the Apache Parquet file differs from the external table, modify the column definition in the external table. The column definition must match the columnar file format of the Apache Parquet file.5.    Run the following query for the SVV_EXTERNAL_COLUMNS view:select * from SVV_EXTERNAL_COLUMNS where schemaname = '<ext_schema_name>' and tablename = '<ext_table_name>';This query checks the data type of the column in the CREATE EXTERNAL TABLE definition.Note: For columnar file formats such as Apache Parquet, the column type is embedded with the data. The column type in the CREATE EXTERNAL TABLE definition must match the column type of the data file. Mismatched column definitions result in a data incompatibility error.Invalid type length errorIf you select a Redshift Spectrum table with columns that are of DECIMAL data type, you might encounter the following error:S3 Query Exception (Fetch). Task failed due to an internal error. File ‘https://s3.amazonaws.com/…/<file_name>’ has an incompatible Parquet schema for column ‘<column_name>’column ‘<column_name>’ has an invalid type lengthTo resolve the invalid type length error in Redshift Spectrum, use an external table definition. The table definition must match the "precision" and "scale" values defined in the external file. For example:create external table ext_schema.tablename (c1 int, c2 decimal (6,2)) stored as PARQUET location 's3://.../.../';In this example, the updated values (in the c2 decimal column) for "precision" and "scale" values are set to 6 and 2, respectively. Therefore, the CREATE EXTERNAL TABLE definition values listed in the c2 column must match the values defined in the Apache Parquet file.Internal errorIf you select an external schema from an Amazon Athena catalog, you might receive the following error in Redshift Spectrum:Task failed due to an internal error. File 'https://s3...snappy.parquet  has an incompatible Parquet schema for column 's3://.../tbl.a'. Column type: BOOLEAN, Parquet schema:\noptional int32 b [i:26 d:1 r:0]In Redshift Spectrum, the column ordering in the CREATE EXTERNAL TABLE must match the ordering of the fields in the Parquet file. For Apache Parquet files, all files must have the same field orderings as in the external table definition. If you skip this ordering or rearrange any data type column, you receive an internal error.Note: Although you can import Amazon Athena data catalogs into Redshift Spectrum, running a query might not work in Redshift Spectrum. In Redshift Spectrum, column names are matched to Apache Parquet file fields. Meanwhile, Amazon Athena uses the names of columns to map to fields in the Apache Parquet file.To resolve the internal error, specify the following column names in the SELECT statement:select col_1, col_2, col_3, .... col_n from athena_schema.tablename;Also, be sure that the AWS Identity and Access Management (IAM) role allows access to Amazon Athena. For more information, see IAM policies for Amazon Redshift Spectrum.Invalid column type errorIf you use Redshift Spectrum to query VARCHAR data type columns from an AWS Glue Data Catalog table, you might receive the following error:<column_name> - Invalid column type for column <column_name>. Type: varchar"Both AWS Glue and Redshift Spectrum support the VARCHAR data type. However, the VARCHAR data type defined by AWS Glue Catalog doesn't include a size parameter (such as VARCHAR (256)). When Redshift Spectrum queries a VARCHAR column defined without a size parameter, the result is an invalid column type error.To resolve the invalid column type error, perform the following steps:1.    Run the following AWS Command Line Interface (AWS CLI) syntax to retrieve and store the AWS Glue table data in a local file:aws glue get-table --region us-east-1 --database gluedb --name click_data_json > click-data-table.jsonNote: If you receive an error while running an AWS CLI command, be sure to use the most recent version of the AWS CLI.2.    Open the click-data-table.json file using any text editor and remove the outer {"Table": ...} envelope. For example, the updated configuration should now read like this:{"Name": "my-table", ...}3.    Remove any fields that aren't allowed in the UpdateTable action. For example, you can remove the following fields:DatabaseNameOwnerCreateTimeUpdateTimeLastAccessTimeCreatedByIsRegisteredWithLakeFormation.4.    Modify the STRING column types to "varchar" with the desired size parameter. For example:"Type": "varchar(1000)"5.    Use the following command syntax to update your AWS Glue table:aws glue update-table --region us-east-1 --database gluedb --table-input "$(cat click-data-table.json)"6.    Check your table definition in AWS Glue and verify that the data types have been modified.7.    Query the AWS Glue table for the external schema in Amazon Redshift. For example:create external schema glue_schema from data catalog database ‘gluedb’ iam_role 'arn:aws:iam::111111111111:role/myRedshiftRole' region 'us-east-1';8.    Run the following query for click_data_json:select * from glue_schema.click_data_json;Invalid range errorRedshift Spectrum expects that files in Amazon Simple Storage Service (Amazon S3) that belong to an external table aren't overwritten during a query. If this happens, it can result in an error similar to the following:Error: Spectrum Scan Error. Error: HTTP response error code: 416 Message: InvalidRange The requested range is not satisfiableTo prevent the preceding error, be sure Amazon S3 files aren't overwritten while they're queried with Redshift Spectrum.Invalid Parquet version numberRedshift Spectrum verifies the metadata of each Apache Parquet file that it accesses. If the verification fails, it might result in an error similar to the following:File 'https://s3.region.amazonaws.com/s3bucket/location/file has an invalid version numberThe verification can fail for the following reasons:The Parquet file was overwritten during the queryThe Parquet file is corruptRelated informationTroubleshooting queries in Amazon Redshift SpectrumFollow"


Question: How do I use AWS Cloud Map to set up cross-account service discovery for ECS services?

I want to use AWS Cloud Map to set up cross-account service discovery for my Amazon Elastic Container Service (Amazon ECS) services.

Answer:
"I want to use AWS Cloud Map to set up cross-account service discovery for my Amazon Elastic Container Service (Amazon ECS) services.Short descriptionCreating a private namespace in AWS Cloud Map, also creates an Amazon Route 53 hosted zone. Because the Route 53 hosted zone is associated with an Amazon Virtual Private Cloud (Amazon VPC), DNS records are discoverable. So, other AWS accounts and Amazon VPCs can't discover the Amazon ECS service through DNS.Prerequisites:Two Amazon VPCs in the same or different accounts with the required subnets, security groups, and non-overlapping CIDR.Both Amazon VPCs using AmazonProvidedDNS, with the attributes enableDnsHostnames and enableDnsSupport turned on.One Amazon ECS cluster.The latest version of AWS Command Line Interface (AWS CLI) installed and configured with the appropriate permissions.Note: If you receive errors when running AWS CLI, confirm that you're running a recent version of the AWS CLI.ResolutionImportant: The following steps use examples for the target Amazon VPC, the source Amazon VPC, and the Amazon ECS cluster. In the AWS CLI, replace the example values with your values.The example Amazon ECS cluster example-cluster is in AWS account 1.The example target Amazon VPC example-target-vpc hosts the Amazon ECS task and is in AWS account 1.The example source Amazon VPC example-source-vpc performs the DNS query and is in AWS account 2.Create a namespace and an AWS Cloud Map service1.    Configure your AWS CLI with the credentials of account 1.2.    Create a private AWS Cloud Map service discovery namespace in account 1:$ aws servicediscovery create-private-dns-namespace --name example-namespace  --vpc example-target-vpcNote: The preceding command creates a namespace with name example-namespace and returns OperationID as the output in JSON.3.    Use the OperationID to check the status of the namespace and namespace ID:$ aws servicediscovery get-operation --operation-id <example-OperationId> --query 'Operation.{Status: Status, NamespaceID: Targets.NAMESPACE}'4.     Locate the hosted zone ID that's associated with the namespace:$ aws servicediscovery get-namespace --id <example-NamespaceID> --query 'Namespace.Properties.DnsProperties.{HoztedZoneId: HostedZoneId}'5.    Use the namespace ID to create an AWS Cloud Map service:$ aws servicediscovery create-service \    --name myservice \    --namespace-id  <example-NamespaceID> \    --dns-config "NamespaceId=<example-NamespaceID>,RoutingPolicy=MULTIVALUE,DnsRecords=[{Type=A,TTL=60}]"Note: The preceding command creates an AWS Cloud Map service with name example-myservice and returns a service ARN as the output.Register a task definition that uses the awsvpc network modeRegister a task definition that's compatible with AWS Fargate and uses the awsvpc network mode:1.    Create a file named fargate-task.json with the following task definition contents:{    "family": "tutorial-task-def",        "networkMode": "awsvpc",        "containerDefinitions": [            {                "name": "sample-app",                "image": "httpd:2.4",                "portMappings": [                    {                        "containerPort": 80,                        "hostPort": 80,                        "protocol": "tcp"                    }                ],                "essential": true,                "entryPoint": [                    "sh",                    "-c"                ],                "command": [                    "/bin/sh -c \"echo '  <title>Amazon ECS Sample App</title>

Amazon ECS Sample App

Congratulations!

Your application is now running on a container in Amazon ECS.

' >  /usr/local/apache2/htdocs/index.html && httpd-foreground\""                ]            }        ],        "requiresCompatibilities": [            "FARGATE"        ],        "cpu": "256",        "memory": "512"}2.    Use the fargate-task.json file to register the task definition:$ aws ecs register-task-definition --cli-input-json file://fargate-task.jsonCreate an Amazon ECS service1.    Create a file named ecs-service-discovery.json, and include the contents of the Amazon ECS service that you're creating:Specify launchType as FARGATE.Specify platformVersion as the latest version.Make sure that the securityGroups and subnets parameters belong to the example-target-vpc. You can get the security group and subnet IDs from your Amazon VPC console.Note: Because the task definition uses awsvpc network mode, an awsvpcConfiguration is required.Example JSON file:{    "cluster": "example-cluster",    "serviceName": "ecs-service-discovery",    "taskDefinition": "tutorial-task-def",    "serviceRegistries": [       {          "registryArn": "<Cloudmap service ARN>"       }    ],    "launchType": "FARGATE",    "platformVersion": "example-latest-version",    "networkConfiguration": {       "awsvpcConfiguration": {          "assignPublicIp": "ENABLED",          "securityGroups": [ "example-target-vpc-sg" ],          "subnets": [ "example-target-vpc-subnet" ]       }    },    "desiredCount": 1}2.    Use the ecs-service-discovery.json file to create your Amazon ECS service:$ aws ecs create-service --cli-input-json file://ecs-service-discovery.json3.    Confirm whether the service task is registered as an instance in the AWS Cloud Map service:$ aws servicediscovery list-instances --service-id <example-cloud-map-service-id>Note: Your Amazon ECS service is now discoverable within example-target-vpc.Associate the source Amazon VPC to the Route 53 hosted zone1.    If the Amazon VPCs are in different accounts, then submit an Amazon VPC association authorization request to account 2:$ aws route53 create-vpc-association-authorization --hosted-zone-id <example-HoztedZoneId>  --vpc VPCRegion=<example_VPC_region>,VPCId=<example-source-vpc>2.    Configure awscli with the credentials of account 2, and associate the example-source-vpc in account 2 with the hosted zone in account 1:$ aws route53 associate-vpc-with-hosted-zone --hosted-zone-id <example-HoztedZoneId> --vpc VPCRegion=<example_VPC_region>,VPCId=<example-source-vpc>3.    Check whether the example-source-vpc is added to the hosted zone:aws route53 get-hosted-zone --id <example-HoztedZoneId> --query 'VPCs'4.    Check that the Amazon ECS service is discoverable through DNS in example-source-vpc. Query the DNS from an Amazon Elastic Compute Cloud (Amazon EC2) instance with example-source-vpc:$ dig +short example-service.example-namespaceNote: In the preceding command example-service.example-namespace is the DNS name. Replace it with your AWS Cloud Map service and namespace.Set up Amazon VPC peering 1.    Use Amazon VPC peering to connect example-target-vpc with example-source-vpc.2.    Update the route tables.3.    Update the security groups.Note: After you set up Amazon VPC peering with the route tables and security groups, resources in example-source-vpc can connect to Amazon ECS tasks in example-target-vpc.If you experience issues when setting up Amazon VPC peering, then see the following AWS Knowledge Center articles:Issues when creating Amazon VPC peering: Why can’t I create an Amazon VPC peering connection with a VPC in another AWS account?Connectivity issues between Amazon VPCs: How do I troubleshoot problems establishing communication over VPC peering?Follow"


Question: How do I protect my data against accidental EC2 instance termination?

What are some options that AWS offers that can help me protect my data against accidental Amazon Elastic Compute Cloud (Amazon EC2) instance termination? How can I troubleshoot and collect more information about probable termination causes and behaviors?

Answer: "What are some options that AWS offers that can help me protect my data against accidental Amazon Elastic Compute Cloud (Amazon EC2) instance termination? How can I troubleshoot and collect more information about probable termination causes and behaviors?ResolutionTo help protect against data loss caused by accidental termination of an Amazon EC2 instance, consider the following options when you configure EC2 infrastructure:Enable termination protection. Termination protection prevents an instance from accidental termination. By default, this option is disabled for EC2 instances. Enable this option to protect your instance from any unintentional termination. For more information, see Enable termination protection.Regularly back up your data. Back up your instance by doing one or more of the following:Create an Amazon Machine Image (AMI). An AMI can capture the data on all the EBS volumes attached to an instance. You can use the AMI to launch a new instance.Schedule regular Amazon Elastic Block Store (Amazon EBS) snapshots.Use AWS Backup.Output data to another AWS service or source. Consider using one of the following services to store the workflows you run on your instance:Amazon Simple Storage Service (Amazon S3)Amazon Relational Database Service (Amazon RDS)Amazon DynamoDBRecreate your instance or restore data from a terminated instance. If you backed up your instances, then you can use the backup to restore the terminated instance. For more information, see How do I recreate a terminated EC2 instance?Troubleshoot termination behaviors to identify the causes of termination. Several issue can cause your instance to terminate immediately on start-up. Or, your instance configuration might lead to instance termination. For more information, see Troubleshoot instance termination (shutting down) and Why did Amazon EC2 terminate my instance?Related informationBest practices for Amazon EC2Best practices for Windows on Amazon EC2How can I automate Amazon EBS snapshot management using Amazon Data Lifecycle Manager?Follow"


Question: How do I troubleshoot CORS errors from my API Gateway API?

I get the error "No 'Access-Control-Allow-Origin' header is present on the requested resource" when I try to invoke my Amazon API Gateway API. How do I troubleshoot this error and other CORS errors from API Gateway?

Answer: "I get the error "No 'Access-Control-Allow-Origin' header is present on the requested resource" when I try to invoke my Amazon API Gateway API. How do I troubleshoot this error and other CORS errors from API Gateway?Short descriptionCross-Origin Resource Sharing (CORS) errors occur when a server doesn’t return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.For more information on configuring CORS for REST APIs, see Turning on CORS for a REST API resource. For HTTP APIs, see Configuring CORS for an HTTP API.Note: CORS must be configured at the resource level and can be handled using API Gateway configurations or backend integrations, such as AWS Lambda.ResolutionThe following example procedure shows how to troubleshoot the No ‘Access-Control-Allow-Origin’ header present CORS error. However, you can use a similar procedure to troubleshoot all CORS errors. For example: Method not supported under Access-Control-Allow-Methods header errors and No ‘Access-Control-Allow-Headers’ headers present errors.Note: The No 'Access-Control-Allow-Origin' header present error can occur for any of the following reasons:The API isn't configured with an OPTIONS method that returns the required CORS headers.Another method type (such as GET, PUT, or POST) isn't configured to return the required CORS headers.An API with proxy integration or non-proxy integration isn't configured to return the required CORS headers.(For private REST APIs only) The incorrect invoke URL is called, or the traffic isn't being routed to the interface virtual private cloud (VPC) endpoint.Confirm the cause of the errorThere are two ways to confirm the cause of a CORS error from API Gateway:Create an HTTP Archive (HAR) file when you invoke your API. Then, confirm the cause of the error in the file by checking the headers in the parameters returned in the API response.-or-Use the developer tools in your browser to check the request and response parameters from the failed API request.Configure CORS on your API resource that’s experiencing the errorFor REST APIsFollow the instructions to Turn on CORS on a resource using the API Gateway console.For HTTP APIsFollow the instructions in Configuring CORS for an HTTP API.Important: If you configure CORS for an HTTP API, then API Gateway automatically sends a response to preflight OPTIONS requests. This response is sent even if there isn't an OPTIONS route configured for your API. For a CORS request, API Gateway adds the configured CORS headers to the response from an integration.While configuring CORS on your API resource, make sure that you do the following:For Gateway Responses for <api-name> API, choose the DEFAULT 4XX and DEFAULT 5XX check boxes.Note: When you select these default options, API Gateway responds with the required CORS headers, even when a request doesn't reach the endpoint. For example, if a request includes an incorrect resource path, API Gateway still responds with a 403 "Missing Authentication Token" error.For Methods, choose the check box for the OPTIONS method, if it isn't already selected. Also, choose the check boxes for all of the other methods that are available to CORS requests. For example: GET, PUT, and POST.Note: Configuring CORS in the API Gateway console adds an OPTIONS method to the resource if one doesn’t already exist. It also configures the OPTIONS method's 200 response with the required Access-Control-Allow-* headers. If you already configured CORS using the console, configuring it again overwrites any existing values.Configure your REST API integrations to return the required CORS headersConfigure your backend AWS Lambda function or HTTP server to send the required CORS headers in its response. Keep in mind the following:Allowed domains must be included in the Access-Control-Allow-Origin header value as a list.For proxy integrations, you can't set up an integration response in API Gateway to modify the response parameters returned by your API's backend. In a proxy integration, API Gateway forwards the backend response directly to the client.If you use a non-proxy integration, you must manually set up an integration response in API Gateway to return the required CORS headers.Note: For APIs with a non-proxy integration, configuring CORS on a resource using the API Gateway console automatically adds the required CORS headers to the resource.(For private REST APIs only) Check the private DNS setting of your interface endpointFor private REST APIs, determine if private DNS is activated on the associated interface VPC endpoint.If private DNS is activatedMake sure that you invoking your private API from within your Amazon Virtual Private Cloud (Amazon VPC) using the private DNS name.If private DNS isn't activatedYou must manually route traffic from the invoke URL to the IP addresses of the VPC endpoint.Note: You must use the following invoke URL, whether private DNS is activated or not:https://api-id.execute-api.region.amazonaws.com/stage-nameMake sure that you replace the values for api-id, region, and stage-name with the required values for your API. For more information, see How to invoke a private API.Important: If CORS is configured when private DNS isn't activated, keep in mind the following limitations:You can't use endpoint-specific public DNS names to access your private API from within your Amazon VPC.You can't use the Host header option, because requests from a browser don't allow Host header manipulation.You can’t use the x-apigw-api-id custom header, because it initiates a preflight OPTIONS request that doesn't include the header. API calls that use the x-apigw-api-id header won’t reach your API.Related informationTesting CORSTurn on CORS on a resource using the API Gateway import APIFollow"


Question: How do I create a snapshot of an Amazon EBS RAID array?

I want to create snapshots of my Amazon Elastic Block Store (Amazon EBS) volumes that are configured in a RAID array. How can I take crash consistent snapshots across multiple Amazon EBS volumes on an Amazon Elastic Compute Cloud (Amazon EC2) instance?

Answer: "I want to create snapshots of my Amazon Elastic Block Store (Amazon EBS) volumes that are configured in a RAID array. How can I take crash consistent snapshots across multiple Amazon EBS volumes on an Amazon Elastic Compute Cloud (Amazon EC2) instance?Short descriptionTo create snapshots for Amazon EBS volumes that are configured in a RAID array, use the multi-volume snapshot feature of your instance. The multi-volume snapshot feature is a one-click solution that takes individual, point-in-time backups of all Amazon EBS volumes attached to your instance. This process makes sure that the backup of your Amazon EBS volumes attached to the instance are in sync relative to each other, resulting in an accurate restore of the Amazon EBS volumes in RAID.Note: You can automate snapshot creation using the Amazon Data Lifecycle Manager.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.Use the AWS Management Console or AWS CLI to create snapshots.Note: After the snapshots are created, each snapshot is treated like an individual snapshot. It's a best practice that you tag your multiple volume snapshots to manage them together during operations such as restore, copy, or retention.AWS Management Console1.    Open the Amazon EC2 console.2.    Under Elastic Block Store, select Snapshots.3.    Select Create Snapshot.4.    Choose Instance as the resource type.5.    Select the instance ID from the drop-down menu.6.    (Optional) Enter a Description of the snapshot.7.    (Optional) Select Copy Tags to automatically copy tags from the source volume to the corresponding snapshots.8.    Click Create Snapshot.AWS Command Line Interface (AWS CLI)Use the CreateSnapshots API.create-snapshots[--description <value>]--instance-specification <value>[--tag-specifications <value>][--dry-run | --no-dry-run][--copy-tags-from-source <value>][--cli-input-json <value>][--generate-cli-skeleton <value>]For parameter descriptions and example calls, refer to AWS CLI Command Reference - create-snapshots.Related informationTaking crash-consistent snapshots across multiple Amazon EBS volumes on an Amazon EC2 instanceCreating an Amazon EBS snapshot - Multi-volume snapshotsRAID configuration on WindowsRAID configuration on LinuxBenchmark EBS volumesFollow"


Question: How do I troubleshoot issues related to a signed URL or signed cookies in CloudFront?

"I'm using Amazon CloudFront and a signed URL or signed cookies to secure private content. However, I'm receiving a 403 Access Denied error."

Answer: "I'm using Amazon CloudFront and a signed URL or signed cookies to secure private content. However, I'm receiving a 403 Access Denied error.ResolutionIf Amazon CloudFront encounters an issue with a signed URL or signed cookies, then you might receive a 403 Access Denied error. A signed URL or signed cookie doesn't include the correct signerWhen you turn on Restrict Viewer Access in a behavior, you must determine a signer. A signer is either a trusted key group that you create in CloudFront, or an AWS account that contains a CloudFront key pair. The following 403 error messages indicate that the signer information is missing or incorrect:The error includes the message "Missing Key-Pair-Id query parameter or cookie value."This message indicates a missing or empty Key-Pair-Id query parameter when using a signed URL. Or, it indicates a missing CloudFront-Key-Pair-ID query string parameter in a signed cookie.The error includes the message "Unknown Key."This message indicates that CloudFront can't verify signer information through Key-Pair-ID (for signed URLs) or CloudFront-Key-Pair-ID (for signed cookies). To resolve this issue, confirm that the correct Key-Pair-ID value is used for a signed URL or CloudFront-Key-Pair-ID for signed cookies:If you use a signed URL, then find and note the value of Key-Pair-ID.-or-If you use signed cookies, then find and note the value of CloudFront-Key-Pair-ID.Then, find the Key ID and confirm that it matches the Key-Pair-ID or CloudFront-Key-Pair-ID:1.    Open the CloudFront console. In the navigation menu, choose Distributions.2.    Select your distribution. Then, choose the Behaviors tab.3.    Select the behavior name, and then choose Edit.4.    Find the Restrict viewer access setting. Note: If it's set to Yes, then requests for files that match the path pattern of this cache behavior must use the signed URL or signed cookie.5.    After you confirm that the Restrict view access field is set to Yes, check the Trusted authorization type field.6.    If the Trusted authorization type value setting is Trusted key groups, then note the name of the trust key group.Find the public key IDs for a trust key group:Open the CloudFront console. Choose Key Groups.In the list of key groups, choose the name of the trusted key group that you noted.Confirm that the Key-Pair-Id or CloudFront-Key-Pair-Id value that you noted in step 1 matches one of the public key IDs in the trusted key group.7.    If the value of Trusted authorization type is Trusted Signer, then CloudFront uses the credentials that AWS generates. In this case, the value of Key-Pair-Id or CloudFront-Key-Pair-Id that you noted in step 1 must match the Access Key ID of the CloudFront credentials. To find the Access Key ID of CloudFront credentials, see Creating key pairs for your signers.A signed URL or signed cookie isn't sent at a valid timeWhen you create a signed URL or signed cookie, a policy statement in JSON format specifies the restrictions on the signed URL. This statement determines how long the URL is valid. CloudFront returns a 403 Access Denied error in any of the following scenarios:A signed URL is sent at time that's greater than the Expires value in a signed URL that uses a canned policy.A signed cookie is sent at a time that's greater than the CloudFront-Expires value in a signed cookie that uses a canned policy.A signed URL or a signed cookie is sent at time that's greater than the DateLessThan value in a custom policy. Or, it's sent at a time that's less than the DateGreaterThan value.Note: The Expires, CloudFront-Expires, DateLessThan, and DateGreaterThan values are in Unix time format (in seconds) and Coordinated Universal Time (UTC). For example, January 1, 2013 10:00 AM UTC converts to 1357034400 in Unix time format. If you use epoch time, then use a 32-bit integer for a date that's no later than 2147483647 (January 19, 2038 at 03:14:07 UTC).The Policy parameter in a signed URL or the CloudFront-Policy attribute in a signed cookie indicates that you use a custom policy. The policy statement is in JSON format and is base64 encoded. To find out the DateLessThan or DateGreaterThan value, use a 64base decode command.Example of a base64 encoded custom policy:eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovL2QxMTExMTFhYmNkZWY4LmNsb3VkZnJvbnQubmV0L2dhbWVfZG93bmxvYWQuemlwIiwiQ29uZGl0aW9uIjp7IklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIxOTIuMC4yLjAvMjQifSwiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0MjY1MDAwMDB9fX1dfQ__To decode a custom policy that's in base64 encoded format into JSON format, run the following Linux command. This example uses the value from the previous example. Replace the policy value with your own custom policy value.$ echo -n eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovL2QxMTExMTFhYmNkZWY4LmNsb3VkZnJvbnQubmV0L2dhbWVfZG93bmxvYWQuemlwIiwiQ29uZGl0aW9uIjp7IklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIxOTIuMC4yLjAvMjQifSwiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0MjY1MDAwMDB9fX1dfQ__ | base64 -diYou receive an output that looks similar to the following message:{ "Statement": [{ "Resource": "http://d111111abcdef8.cloudfront.net/game_download.zip", "Condition": { "IpAddress": { "AWS:SourceIp": "192.0.2.0/24" }, "DateLessThan": { "AWS:EpochTime": 1426500000 } } }] }A signed URL or signed cookie has more than one statement in the policyIf more than one statement is included in a canned policy or custom policy, then CloudFront returns a 403 Access Denied error.To troubleshoot this issue, run the Linux command in the previous section to check the custom policy statement. Verify your code details, and then confirm that only one statement is included in the canned policy or custom policy.A signed URL or signed cookie has an incorrect base URL in the policyCloudFront returns a 403 Access Denied error in any of the following scenarios:The base URL is abbreviated (www.example.com) in the Resource key in the policy statement. Use a full URL (http://www.example.com).The base URL doesn't have UTF-8 character encoding.The base URL doesn't include all punctuation and parameter names.The HTTP or HTTPS protocol in the base URL doesn't match the protocol that's used in a request that's sending a signed URL or signed cookies.The base URL's domain name doesn't match the host header that's the user agent uses to send a signed URL or signed cookies.The base URL query string includes characters that aren't valid.A signed URL or signed cookie has an incorrect signature in the policyCloudFront returns a 403 Access Denied error in any of the following scenarios:The policy statement includes white spaces (including tabs and newline characters).The canned policy or custom policy isn't formatted as string before it's hashed. This happens if you create a signed URL or signed cookie without using an AWS SDK.The policy isn't hashed before it generates the signature. This happens if you create the signed URL or signed cookie without using an AWS SDK.For signature best practices when using a signed URL or signed cookies, see Code examples for creating a signature for a signed URL.A signed URL or signed cookie was sent from an IP address or IP range that's not permitted in the custom policyCloudFront returns a 403 Access Denied error in any of the following scenarios:A signed URL or signed cookie is sent from an IPv6 IP address.A signed URL or signed cookie isn't sent from an IPv4 IP address or an IPv4 IP range that's specified in the custom policy.The IpAddress key is available only in the custom policy that's in a signed URL or a signed cookie. IP addresses in IPv6 format aren't supported. If you use a custom policy that includes IpAddress, then don't turn on IPv6 for the distribution.A signed cookie doesn't include the Domain and Path attributes in Set-cookie response headersCloudFront returns a 403 Access Denied error if cookies return from CloudFront but aren't included in later requests to the same domain. In this case, check the Domain and Path cookie attributes in the Set-Cookie response header.The Domain value is the domain name for the requested file. If you don't specify a Domain attribute, then the default value is the domain name in the URL. This applies only to the specified domain name, not to subdomains. If you specify a Domain attribute, then it also applies to subdomains.If you specify a Domain attribute, then the domain name in the URL and the value of the Domain attribute must match. You can specify the domain name that CloudFront assigns to your distribution (for example, d111111abcdef8.cloudfront.net), but you can't specify *.cloudfront.net for the domain name. To use an alternate domain name, such as example.com, in URLs, add an alternate domain name to your distribution.The Path attribute is the path for the requested file. If you don't specify a Path attribute, then the default value is the path in the URL.Follow"


Question: How do I allow Amazon ECS tasks to pull images from an Amazon ECR image repository?

How do I allow Amazon Elastic Container Service (Amazon ECS) tasks to pull images from an Amazon Elastic Container Registry (Amazon ECR) image repository?

Answer: "How do I allow Amazon Elastic Container Service (Amazon ECS) tasks to pull images from an Amazon Elastic Container Registry (Amazon ECR) image repository?Short descriptionTo access the Amazon ECR image repository with your launch type, choose one of these options:For Amazon Elastic Compute Cloud (Amazon EC2) launch types, you must provide permissions to ecsTaskExecutionRole or the instance profile associated with the container instance. However, it's always a best practice to provide Amazon ECR permissions to ecsTaskExecutionRole. If permissions are provided to both the instance and the role, then ecsTaskExecutionRole takes precedence.For AWS Fargate launch types, you must grant your Amazon ECS task execution role permission to access the Amazon ECR image repository.ResolutionFor EC2 launch typesOpen the AWS Identity and Access Management (IAM) console.In the navigation pane, choose Roles, and then choose Create role.Choose the AWS service role type.In the Use Case section, select EC2. Then, select Next.Choose the default AmazonEC2ContainerServiceforEC2Role managed policy, and then choose Next.Note: The AmazonEC2ContainerServiceforEC2Role policy also allows you to register container instances to your ECS cluster and enable log streams in Amazon CloudWatch.Add tags to your policy, if desired, and then choose Next.For Role name, enter a unique name (such as ECSRoleforEC2), and then choose Create role.Launch a new container instance using the latest Amazon ECS-optimized Amazon Linux AMI.Attach the role that you created to the new container instance.Create a task definition.Important: In the containerDefinitions section of your task definition, specify the ECR image aws_account_id.dkr.ecr.region.amazonaws.com/repository:tag as the image property.Run a task or a service using the task definition that you created in step 10.(Optional) If you don't want to provide permissions to an instance profile, give permissions to the ECS Task Execution Role. Then, run a task or a service using the task definition that you created in step 10.For Fargate launch typesAn Amazon ECS task execution role is automatically created in the Amazon ECS console first-run experience. If you can't find the role or the role is deleted, complete these steps:Open the IAM console.In the navigation pane, choose Roles, and then choose Create role.In the Select type of trusted entity section, choose Elastic Container Service.For Select your use case, choose Elastic Container Service Task, and then choose Next.In the Attach permissions policy section, search for AmazonECSTaskExecutionRolePolicy, select the policy, and then choose Next.Note: This policy also provides permissions to use the awslogs log driver.For the Role Name, enter ecsTaskExecutionRole, and then choose Create role.Create a task definition.Important: In the containerDefinitions section of your task definition, specify the ECR image aws_account_id.dkr.ecr.region.amazonaws.com/repository:tag as the image property. Specify the IAM role created in step 6.Run a task or a service using the task definition that you created in step 7.Your task or service can now pull images from the Amazon ECR image repository.Related informationUsing Amazon ECR Images with Amazon ECSFollow"


Question: Why did I receive the AWS account ID status "Verification failed" with GuardDuty?

"To manage multiple accounts in Amazon GuardDuty, I invited an AWS account to associate with my AWS account using AWS Organizations. The status of the member account is "Verification failed.""

Answer: "To manage multiple accounts in Amazon GuardDuty, I invited an AWS account to associate with my AWS account using AWS Organizations. The status of the member account is "Verification failed."Short descriptionTo manage multiple accounts in GuardDuty, you must choose a single AWS account to be the administrator account for GuardDuty. You can then associate other AWS accounts with the administrator account as member accounts.You can associate accounts with a GuardDuty administrator account with either of the following:An AWS Organizations organization that both accounts are members of.An invitation that's sent through GuardDuty.To send an invitation from the GuardDuty administrator account, you must specify the member account's account ID and email address. The "Verification failed" status indicates that the root email address or the account ID that you added as a GuardDuty member account are incorrect.For more information, see Managing multiple accounts in Amazon GuardDuty.ResolutionFollow these steps to designate a GuardDuty delegated administrator, and add member accounts using the GuardDuty console.Important:Be sure to use the root email address and account ID associated with the account.GuardDuty must be turned on in the member account before sending an invitation.You can bulk add accounts by uploading a .csv file. Be sure to specify the account ID and primary email address separated by a comma on separate lines. The first line of the .csv file must contain the account ID and email header in the following format:Account ID,Email111111111111,primary1@example.com222222222222,primary2@example.comYou can also use Python scripts to turn on GuardDuty in multiple accounts simultaneously. For this method, make sure that the accounts in the input .csv file are listed one per line. Use the account ID and email address without headers in the following format:111111111111,primary1@example.com222222222222,primary2@example.comAfter the GuardDuty member account accepts the invitation, the Status column for your member account changes to Enabled in the administrator account.Related informationHow do I set up a trusted IP address list for GuardDuty?Follow"


Question: How do I analyze my audit logs using Redshift Spectrum?

I want to use Amazon Redshift Spectrum to analyze my audit logs.

Answer: "I want to use Amazon Redshift Spectrum to analyze my audit logs.Short descriptionBefore you use Redshift Spectrum, complete the following tasks:1.    Turn on your audit logs.Note: It might take some time for your audit logs to appear in your Amazon Simple Storage Service (Amazon S3) bucket.2.    Create an AWS Identity and Access Management (IAM) role.3.    Associate the IAM role to your Amazon Redshift cluster.To query your audit logs in Redshift Spectrum, create external tables, and then configure them to point to a common folder (used by your files). Then, use the hidden $path column and regex function to create views that generate the rows for your analysis.ResolutionTo query your audit logs in Redshift Spectrum, follow these steps:1.    Create an external schema:create external schema s_audit_logs from data catalog database 'audit_logs' iam_role 'arn:aws:iam::your_account_number:role/role_name' create external database if not existsReplace your_account_number to match your real account number. For role_name, specify the IAM role attached to your Amazon Redshift cluster.2.    Create the external tables.Note: In the following examples, replace bucket_name, your_account_id, and region with your bucket name, account ID, and AWS Region.Create a user activity logs table:create external table s_audit_logs.user_activity_log(logrecord varchar(max))ROW FORMAT DELIMITEDFIELDS TERMINATED BY '|'STORED AS INPUTFORMAT'org.apache.hadoop.mapred.TextInputFormat'OUTPUTFORMAT'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'LOCATION's3://bucket_name/logs/AWSLogs/your_account_id/redshift/region'Create a connection log table:CREATE EXTERNAL TABLE s_audit_logs.connections_log(event varchar(60), recordtime varchar(60),remotehost varchar(60), remoteport varchar(60),pid int, dbname varchar(60),username varchar(60), authmethod varchar(60),duration int, sslversion varchar(60),sslcipher varchar(150), mtu int,sslcompression varchar(70), sslexpansion varchar(70),iamauthguid varchar(50), application_name varchar(300))ROW FORMAT DELIMITEDFIELDS TERMINATED BY '|'STORED AS INPUTFORMAT'org.apache.hadoop.mapred.TextInputFormat'OUTPUTFORMAT'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'LOCATION 's3://bucket_name/logs/AWSLogs/your_account_id/redshift/region';Create a user log table:create external table s_audit_log.user_log(userid varchar(255),username varchar(500),oldusername varchar(500),usecreatedb varchar(50),usesuper varchar(50),usecatupd varchar(50),valuntil varchar(50),pid varchar(50),xid varchar(50),recordtime varchar(50))ROW FORMAT DELIMITEDFIELDS TERMINATED BY '|'STORED AS INPUTFORMAT'org.apache.hadoop.mapred.TextInputFormat'OUTPUTFORMAT'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'LOCATION 's3://bucket_name/logs/AWSLogs/your_account_id/redshift/region’;3.    Create a local schema to view the audit logs:create schema audit_logs_views4.    To access the external tables, create views in a database with the WITH NO SCHEMA BINDING option:CREATE VIEW audit_logs_views.v_connections_log ASselect *FROM s_audit_logs.connections_logWHERE "$path" like '%connectionlog%'with no schema binding;The returned files are restricted by the hidden $path column to match the connectionlog entries.In the following example, the hidden $path column and regex function restrict the files that are returned for v_connections_log:CREATE or REPLACE VIEW audit_logs_views.v_useractivitylog ASSELECT    logrecord,          substring(logrecord,2,24) as recordtime,          replace(regexp_substr(logrecord,'db=[^" "]*'),'db=','') as db,          replace(regexp_substr(logrecord,'user=[^" "]*'),'user=','') AS user,          replace(regexp_substr(logrecord, 'pid=[^" "]*'),'pid=','') AS pid,          replace(regexp_substr(logrecord, 'userid=[^" "]*'),'userid=','') AS userid,          replace(regexp_substr(logrecord, 'xid=[^" "]*'),'xid=','') AS xid,          replace(regexp_substr(logrecord, '][^*]*'),']','') AS query   FROM s_audit_logs.user_activity_log   WHERE "$path" like '%useractivitylog%'   with no schema binding;The returned files match the useractivitylog entries.Note: There's a limitation that's related to the multi-row queries in user activity logs. It's a best practice to query the column log records directly.Related informationAnalyze database audit logs for security and compliance using Amazon Redshift SpectrumSTL_CONNECTION_LOGFollow"


Question: How can I map Availability Zones across my accounts?

"An Availability Zone (AZ) in my account doesn't map to the same location as an AZ with the same name in a different account. I want to coordinate the distribution of my resources to the AZs across my accounts to confirm fault tolerance, improve performance, or optimize costs. How can I map AZs across accounts?"

Answer: "An Availability Zone (AZ) in my account doesn't map to the same location as an AZ with the same name in a different account. I want to coordinate the distribution of my resources to the AZs across my accounts to confirm fault tolerance, improve performance, or optimize costs. How can I map AZs across accounts?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.AZ names don't map to the same location across accounts. However, you can use Availability Zone IDs (AZ IDs) to map AZ across accounts:Open the AWS Resource Access Manager console.In the navigation bar, select your Region from the Region selector.In the Your AZ ID pane on the right, review the list of AZ names and their corresponding AZ IDs.Note: You can also use the aws ec2 describe-availability-zones --region "region-name" command in the AWS CLI to generate AZ ID information. Be sure to replace "region-name" with the name of your AWS region.Identify which AZ have the same AZ IDs across your accounts. AZs that have the same AZ IDs map to the same physical location.You can gain better insight into your resources by using the information from performing the previous steps. Then, you can make informed decisions on things such as:Launching new instances in a subnet that was created in your desired AZ.Moving an EC2 instance to another subnet, Availability Zone, or VPC.Related informationUse consistent Availability Zones in VPCs across different AWS accountsFollow"


Question: How can I invoke a Lambda function asynchronously from my Amazon API Gateway API?

I want to invoke an AWS Lambda function asynchronously instead of synchronously for my Amazon API Gateway API.

Answer: "I want to invoke an AWS Lambda function asynchronously instead of synchronously for my Amazon API Gateway API.ResolutionREST APIsIn Lambda non-proxy integration, the backend Lambda function is invoked synchronously by default. You can configure the Lambda function for a Lambda non-proxy integration to be invoked asynchronously by specifying 'Event' as the Lambda invocation type.1.    Open the API Gateway console, choose APIs, and then choose your REST API.2.    In Resources, choose GET, and then choose Integration Request.3.    In Integration type, choose Lambda Function.4.    Expand HTTP Headers, and then choose Add header.5.    For Name, enter X-Amz-Invocation-Type.6.    For Mapped from, enter 'Event'.7.    Redeploy the REST API.To invoke the Lambda function with the option for either asynchronous or synchronous, add an InvocationType header.1.    Open the API Gateway console, choose APIs, and then choose your REST API.2.    In Resources, choose GET, and then choose Method Request.3.    In Request Validator, choose the edit icon, choose the dropdown list, and then choose Validate query string parameters and headers.4.    Choose the update icon to save changes.5.    Expand HTTP Headers, and then choose Add header.6.    For Name, enter InvocationType, and then choose Required.7.    In Integration Request, Expand HTTP Headers, and then choose Add header.8.    For Name, enter X-Amz-Invocation-Type.9.     For Mapped from, enter method.request.header.InvocationType.10.    Redeploy the REST API.Clients can include the InvocationType: Event header in API requests for asynchronous invocations or InvocationType: RequestResponse for synchronous invocations.For more information, see Set up asynchronous invocation of the backend Lambda function.HTTP APIsHTTP APIs only support proxy integrations for Lambda. You can't set the X-Amz-Invocation-Type header in the API Gateway integration for HTTP APIs. You can use two Lambda functions with one acting as proxy.Example configuration:HTTP API --> Invoke Lambda1 synchronously --> Invoke Lambda2 asynchronouslyFollow"


Question: How can I decode an authorization failure message after receiving an "UnauthorizedOperation" error during an EC2 instance launch?

"I'm trying to launch an Amazon Elastic Compute Cloud (Amazon EC2) instance, but I get the error "An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. Encoded authorization failure message encoded-message". How do I resolve this?"

Answer: "I'm trying to launch an Amazon Elastic Compute Cloud (Amazon EC2) instance, but I get the error "An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. Encoded authorization failure message encoded-message". How do I resolve this?Short descriptionThe "UnauthorizedOperation" error indicates that permissions attached to the AWS Identity and Access Management (IAM) role or user trying to perform the operation doesn't have the required permissions to launch EC2 instances. Because the error involves an encoded message, use the AWS Command Line Interface (AWS CLI) to decode the message. This decoding provides more details regarding the authorization failure.PrerequisiteThe IAM user or role attempting to decode the encoded message must have permission to the DecodeAuthorizationMesssage API action with an IAM policy. If the user or role doesn't have this permission, the decode action fails and the following error message appears:"Error: A client error (AccessDenied) occurred when calling the DecodeAuthorizationMessage operation: User: xxx is not authorized to perform: (sts:DecodeAuthorizationMessage) action".Resolution1.    Verify that the AWS CLI is installed and configured on your machine with the following command:$ aws --versionNote: If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI.2.    Run the decode-authorization-message command. Replace encoded-message with the exact encoded message contained in the error message.$ aws sts decode-authorization-message --encoded-message encoded-message3.    The decoded message lists the required permissions that are missing from the IAM role or user policy.Example encoded message:Launch Failed - You are not authorized to perform this operation. Encoded authorization failure message: 4GIOHlTkIaWHQD0Q0m6XSnuUMCm-abcdefghijklmn-abcdefghijklmn-abcdefghijklmnExample decoded message:$ aws sts decode-authorization-message --encoded-message 4GIOHlTkIaWHQD0Q0m6XSnuUMCm-abcdefghijklmn-abcdefghijklmn-abcdefghijklmn{    "DecodedMessage": "{\"allowed\":false,\"explicitDeny\":false,\"matchedStatements\":{\"items\":[]},\"failures\":{\"items\":[]},\"context\":{\"principal\":{\"id\":\"ABCDEFGHIJKLMNO\",\"name\":\"AWS-User\",\"arn\":\"arn:aws:iam::accountID:user/test-user\"},\"action\":\"iam:PassRole\",\"resource\":\"arn:aws:iam::accountID:role/EC2_instance_Profile_role\",\"conditions\":{\"items\":[{\"key\":\"aws:Region\",\"values\":{\"items\":[{\"value\":\"us-east-2\"}]}},{\"key\":\"aws:Service\",\"values\":{\"items\":[{\"value\":\"ec2\"}]}},{\"key\":\"aws:Resource\",\"values\":{\"items\":[{\"value\":\"role/EC2_instance_Profile_role\"}]}},{\"key\":\"iam:RoleName\",\"values\":{\"items\":[{\"value\":\"EC2_instance_Profile_role\"}]}},{\"key\":\"aws:Account\",\"values\":{\"items\":[{\"value\":\"accountID\"}]}},{\"key\":\"aws:Type\",\"values\":{\"items\":[{\"value\":\"role\"}]}},{\"key\":\"aws:ARN\",\"values\":{\"items\":[{\"value\":\"arn:aws:iam::accountID:role/EC2_instance_Profile_role\"}]}}]}}}"}The preceding error message indicates that the request failed to call RunInstances because AWS-User didn't have permission to perform the iam:PassRole action on the arn:aws:iam::accountID:role/EC2_instance_Profile_role.4.    Edit the IAM policy associated with the IAM role or user to add the missing required permissions listed in the preceding step.Related informationWhy can't I run AWS CLI commands on my EC2 instance?Why am I unable to start or launch my EC2 instance?Follow"


Question: How can I change the encryption key used by my Amazon RDS DB instances and DB snapshots?

I want to update the encryption key used by my Amazon Relational Database Service (Amazon RDS) DB instances and DB snapshots so that they use a new encryption key.

Answer: "I want to update the encryption key used by my Amazon Relational Database Service (Amazon RDS) DB instances and DB snapshots so that they use a new encryption key.ResolutionYou can't change the encryption key used by an Amazon RDS DB instance. However, you can create a copy of the RDS DB instance, and then choose a new encryption key for that copy.Note: Data in unlogged tables might not be restored using snapshots. For more information, review Best practices for working with PostgreSQL.To create a copy of an RDS DB instance with a new encryption key, do the following:Open the Amazon RDS console.In the navigation pane, choose Databases.Choose the DB instance for which you want to create a manual snapshot.Create a manual snapshot for your DB instance.In the navigation pane, choose Snapshots.Select the manual snapshot that you created.Choose Actions, and then choose Copy Snapshot.Under Encryption, select Enable Encryption.For AWS KMS Key, choose the new encryption key that you want to use.Choose Copy snapshot.Restore the copied snapshot.The new RDS DB instance uses your new encryption key.Confirm that your new database has all necessary data and your application is using the new database. When you no longer need the old RDS DB instance, you can delete the instance.Related informationEncrypting Amazon RDS resourcesBacking up and restoring an Amazon RDS DB instanceFollow"


Question: How do I troubleshoot high latency in my API Gateway requests that are integrated with Lambda?

Response times are slow when I make requests to an Amazon API Gateway API that’s integrated with an AWS Lambda function. How do I determine the cause of high latency?

Answer: "Response times are slow when I make requests to an Amazon API Gateway API that’s integrated with an AWS Lambda function. How do I determine the cause of high latency?ResolutionHigh latency must be addressed when an API endpoint that’s integrated with a Lambda function takes too long to send responses to a client. Review the metrics for API Gateway to identify the section of the request/response flow that’s causing high latency. After you determine the cause of high latency, you can work to reduce the delays.Filter CloudWatch metrics to review latency metrics on the APITo identify the section of the request/response flow that’s causing high latency, first perform the following steps:Observe the latency of the client after sending a request to the API.After you note the overall latency, open the Amazon CloudWatch console. In the left navigation pane, choose Metrics, All metrics. In the metrics search box, enter APIGateway. From the search results, choose API Gateway, ApiId.In the list of APIs, filter for the specified API by using the API ID or the API name. After filtering, check the IntegrationLatency and Latency check boxes.Note: The API ID and API name are available from the API Gateway console.Open the Graphed metrics tab. For Statistic, choose Maximum. For Period, choose 1 minute. Above the graph, select the Custom time period. Choose the time frame during which the client experienced high latency.Review both the IntegrationLatency and Latency metrics. Note the values and timestamps when these metrics have high values. The values can explain the cause for high latency.Compare metrics to identify the cause of high latencyContinue to review the metrics related to the request/response flow to find the cause of high latency:Compare the API Gateway Latency metric to the overall latency value observed at the client.For example, an API has a Latency metric with a Maximum value that’s approximately equal to the Max Latency value at the client. These values suggest that the maximum delay in the request/response flow is the time taken by API Gateway to process requests. API Gateway processing time includes the time taken to send requests to Lambda, wait for responses from Lambda, and send responses to a client.Compare the IntegrationLatency metric with the Latency metric for the API.For example, the IntegrationLatency metric is approximately equal to the Latency metric. These values indicate that latency at the API is primarily caused by backend requests sent to Lambda that are taking longer to respond. The IntegrationLatency metric includes the time between API Gateway sending a request and API Gateway receiving a response from the backendWhen the IntegrationLatency metric is low when compared to the Latency metric for the API, the backend response times are low. In this scenario, it takes longer to process the API requests or responses.For example, mapping templates configured in the API or an API Gateway Lambda authorizer both might create delays.When the Latency metric for the API is much lower than the latency observed at the client, the route might be causing delays. Review the route between the client and API Gateway to confirm whether there are any intermediate endpoints that are adding delays.For example, private VPN connections or proxies might create delays.View Lambda metrics to identify the cause of high IntegrationLatencyFinally, focus on the Lambda metrics related to the request/response flow to find the cause of high IntegrationLatency:Check the Lambda function Duration metric to confirm whether the Lambda function’s execution time is longer. If the Lambda function’s execution time has increased, review the CloudWatch log to find the section of code that’s causing high latency. By default, Lambda functions log the START, END, and REPORT statements in CloudWatch logs. Add custom log statements at each logical section of the Lambda function code to get verbose CloudWatch logs.If the Duration metric didn't change during the period of high latency at the client, determine if the initialization time increased. Initialization time in a Lambda function is the time taken to set up the execution environment to process a request. Requests that come from API Gateway might require a new environment for processing. This is set up through Lambda. Typically, the code that’s present outside the Lambda function handler runs during the initialization time. Code that takes longer to complete can cause delays for the overall response times to the client.Note: Initialization time is known as INIT or cold start.Confirm whether there’s any increase in the initialization time’s Duration by verifying the report statements in the Lambda function logs. Initialization time that's high for some requests can cause an increase in the IntegrationLatency metric for API Gateway.Related informationWorking with metrics for HTTP APIsAmazon API Gateway dimensions and metricsMonitoring WebSocket API execution with CloudWatch metricsViewing metrics on the CloudWatch consoleLambda runtime environment lifecycleFollow"