

# Enable transaction search


You can enable [Transaction Search](CloudWatch-Transaction-Search.md) through the console or by using an API. Transaction search is configured for the entire account and switches all spans ingestion through X-Ray into cost effective collection mode using [Amazon CloudWatch Pricing](https://aws.amazon.com/cloudwatch/pricing/). By default you will also index 1% of ingested spans for free as trace summary for analysis, which is typically sufficient given you already have full end-to-end trace visibility on all ingested spans through Transaction Search.

## Prerequisites


 Before you can enable Transaction Search, you must create a role with the following permissions. 

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "TransactionSearchXRayPermissions",
      "Effect": "Allow",
      "Action": [
        "xray:GetTraceSegmentDestination",
        "xray:UpdateTraceSegmentDestination",
        "xray:GetIndexingRules",
        "xray:UpdateIndexingRule"
      ],
      "Resource": "*"
    },
    {
      "Sid": "TransactionSearchLogGroupPermissions",
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutRetentionPolicy"
      ],
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/application-signals/data:*",
        "arn:aws:logs:*:*:log-group:aws/spans:*"
      ]
    },
    {
      "Sid": "TransactionSearchLogsPermissions",
      "Effect": "Allow",
      "Action": [
        "logs:PutResourcePolicy",
        "logs:DescribeResourcePolicies"
      ],
      "Resource": "*"
    },
    {
      "Sid": "TransactionSearchApplicationSignalsPermissions",
      "Effect": "Allow",
      "Action": [
        "application-signals:StartDiscovery"
      ],
      "Resource": "*"
    },
    {
      "Sid": "CloudWatchApplicationSignalsCreateServiceLinkedRolePermissions",
      "Effect": "Allow",
      "Action": "iam:CreateServiceLinkedRole",
      "Resource": "arn:aws:iam::*:role/aws-service-role/application-signals.cloudwatch.amazonaws.com/AWSServiceRoleForCloudWatchApplicationSignals",
      "Condition": {
        "StringLike": {
          "iam:AWSServiceName": "application-signals.cloudwatch.amazonaws.com"
        }
      }
    },
    {
      "Sid": "CloudWatchApplicationSignalsGetRolePermissions",
      "Effect": "Allow",
      "Action": "iam:GetRole",
      "Resource": "arn:aws:iam::*:role/aws-service-role/application-signals.cloudwatch.amazonaws.com/AWSServiceRoleForCloudWatchApplicationSignals"
    },
    {
      "Sid": "CloudWatchApplicationSignalsCloudTrailPermissions",
      "Effect": "Allow",
      "Action": [
        "cloudtrail:CreateServiceLinkedChannel"
      ],
      "Resource": "arn:aws:cloudtrail:*:*:channel/aws-service-channel/application-signals/*"
    }
  ]
}
```

------

**Note**  
 To use Transaction Search and other CloudWatch features, add the [CloudWatchReadOnlyAccess policy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/CloudWatchReadOnlyAccess.html) to your role. For information about how to create a role, see [IAM role creation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html). 

## Enabling Transaction Search in the console


 The following procedure describes how to enable Transaction Search in the console. 

**To enable Transaction Search in the CloudWatch console**

1. Open the CloudWatch console at [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/).

1.  From the navigation pane, under **Application Signals**, choose **Transaction Search**. 

1.  Choose **Enable Transaction Search**. 

1.  Select the box to ingest spans as structured logs, and enter a percentage of spans to be indexed. You can index spans at 1% for free and change the percentage later based on your requirements. 

## Enabling Transaction Search using an API


 The following procedure describes how to enable Transaction Search using an API. 

### Step 1. Create a policy that grants access to ingest spans in CloudWatch Logs


 When using the AWS CLI or SDK to enable Transaction Search, you must configure permissions using a resource-based policy with [https://docs.aws.amazon.com/xray/latest/api/API_PutResourcePolicy.html](https://docs.aws.amazon.com/xray/latest/api/API_PutResourcePolicy.html). 

**Example policy**  
 The following example policy allows X-Ray to send traces to CloudWatch Logs 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "TransactionSearchXRayAccess",
            "Effect": "Allow",
            "Principal": {
                "Service": "xray.amazonaws.com"
            },
            "Action": "logs:PutLogEvents",
            "Resource": [
                "arn:aws:logs:us-east-1:123456789012:log-group:aws/spans:*",
                "arn:aws:logs:us-east-1:123456789012:log-group:/aws/application-signals/data:*"
            ],
            "Condition": {
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:xray:us-east-1:123456789012:*"
                },
                "StringEquals": {
                    "aws:SourceAccount": "123456789012"
                }
            }
        }
    ]
}
```

------

**Example command**  
 The following example shows how to format your AWS CLI command with `PutResourcePolicy`. 

```
aws logs put-resource-policy --policy-name MyResourcePolicy --policy-document '{ "Version": "2012-10-17",		 	 	  "Statement": [ { "Sid": "TransactionSearchXRayAccess", "Effect": "Allow", "Principal": { "Service": "xray.amazonaws.com" }, "Action": "logs:PutLogEvents", "Resource": [ "arn:partition:logs:region:account-id:log-group:aws/spans:*", "arn:partition:logs:region:account-id:log-group:/aws/application-signals/data:*" ], "Condition": { "ArnLike": { "aws:SourceArn": "arn:partition:xray:region:account-id:*" }, "StringEquals": { "aws:SourceAccount": "account-id" } } } ]}'
```

### Step 2. Configure the destination of trace segments


 Configure the ingestion of spans with [https://docs.aws.amazon.com/xray/latest/api/API_UpdateTraceSegmentDestination.html](https://docs.aws.amazon.com/xray/latest/api/API_UpdateTraceSegmentDestination.html). 

**Example command**  
 The following example shows how to format your AWS CLI command with `UpdateTraceSegmentDestination`. 

```
aws xray update-trace-segment-destination --destination CloudWatchLogs
```

### Step 3. Configure the amount of spans to index


 Configure your desired sampling percentage with [https://docs.aws.amazon.com/xray/latest/api/API_UpdateIndexingRule.html](https://docs.aws.amazon.com/xray/latest/api/API_UpdateIndexingRule.html) 

**Example command**  
 The following example shows how to format your AWS CLI command with `UpdateIndexingRule`. 

```
aws xray update-indexing-rule --name "Default" --rule '{"Probabilistic": {"DesiredSamplingPercentage": number}}'
```

**Note**  
 After you enable Transaction Search, it can take ten minutes for spans to become available for search and analysis. 

### Step 4. Verify spans are available for search and analysis


 To verify spans are available for search and analysis, use [https://docs.aws.amazon.com/xray/latest/api/API_GetTraceSegmentDestination.html](https://docs.aws.amazon.com/xray/latest/api/API_GetTraceSegmentDestination.html). 

**Example commands**  
 The following example shows how to format your AWS CLI command with `GetTraceSegmentDestination`. 

```
aws xray get-trace-segment-destination
```

**Example response**  
 The following example shows the response you can expect when Transaction Search is active. 

```
{
    "Destination": "CloudWatchLogs",
    "Status": "ACTIVE"
}
```

# Using Transaction Search with CloudFormation


You can use CloudFormation to enable and configure X-Ray Transaction Search.

**Note**  
To create a CloudFormation stack, see [Creating your first stack ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/gettingstarted.walkthrough.html).

## Prerequisites

+ You must have access to an AWS account with an IAM user or role that has permissions to use Amazon EC2, Amazon S3, CloudFormation, or have administrative user access.
+ You must have a Virtual Private Cloud (VPC) that has access to the internet. To keep things simple, you can use the default VPC that comes with your account. The default VPC and default subnets are sufficient for this configuration.
+ Make sure Transaction Search is disabled before you enable using AWS CDK or CloudFormation.

## Enabling Transaction Search


To enable Transaction Search using CloudFormation, you need to create the following two resources.
+ `AWS::Logs::ResourcePolicy`
+ `AWS::XRay::TransactionSearchConfig`

1. **Create AWS::Logs::ResourcePolicy** – Create a resource policy that allows X-Ray to send traces to CloudWatch Logs

   **YAML**

   ```
   Resources:
     LogsResourcePolicy:
       Type: AWS::Logs::ResourcePolicy
       Properties:
         PolicyName: TransactionSearchAccess
         PolicyDocument: !Sub >
           {
             "Version": "2012-10-17",		 	 	 
             "Statement": [
               {
                 "Sid": "TransactionSearchXRayAccess",
                 "Effect": "Allow",
                 "Principal": {
                   "Service": "xray.amazonaws.com"
                 },
                 "Action": "logs:PutLogEvents",
                 "Resource": [
                   "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:aws/spans:*",
                   "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/application-signals/data:*"
                 ],
                 "Condition": {
                   "ArnLike": {
                     "aws:SourceArn": "arn:${AWS::Partition}:xray:${AWS::Region}:${AWS::AccountId}:*"
                   },
                   "StringEquals": {
                     "aws:SourceAccount": "${AWS::AccountId}"
                   }
                 }
               }
             ]
           }
   ```

   **JSON**

   ```
   {
       "Resources": {
           "LogsResourcePolicy": {
               "Type": "AWS::Logs::ResourcePolicy",
               "Properties": {
                   "PolicyName": "TransactionSearchAccess",
                   "PolicyDocument": {
                       "Fn::Sub": "{\n  \"Version\": \"2012-10-17\",		 	 	 \n  \"Statement\": [\n    {\n      \"Sid\": \"TransactionSearchXRayAccess\",\n      \"Effect\": \"Allow\",\n      \"Principal\": {\n        \"Service\": \"xray.amazonaws.com\"\n      },\n      \"Action\": \"logs:PutLogEvents\",\n      \"Resource\": [\n        \"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:aws/spans:*\",\n        \"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/application-signals/data:*\"\n      ],\n      \"Condition\": {\n        \"ArnLike\": {\n          \"aws:SourceArn\": \"arn:${AWS::Partition}:xray:${AWS::Region}:${AWS::AccountId}:*\"\n        },\n        \"StringEquals\": {\n          \"aws:SourceAccount\": \"${AWS::AccountId}\"\n        }\n      }\n    }\n  ]\n}"
                   }
               }
           }
       }
   }
   ```

1. ** Create and Configure AWS::XRay::TransactionSearchConfig** – Create the `TransactionSearchConfig` resource to enable Transaction Search.

   **YAML**

   ```
   Resources:
     XRayTransactionSearchConfig:
       Type: AWS::XRay::TransactionSearchConfig
   ```

   **JSON**

   ```
   {
     "Resources": {
       "XRayTransactionSearchConfig": {
         "Type": "AWS::XRay::TransactionSearchConfig"
       }
     }
   }
   ```

1. (Optional) You can set the `IndexingPercentage` property to control the percentage of spans that will be indexed.

   **YAML**

   ```
   Resources:
     XRayTransactionSearchConfig:
       Type: AWS::XRay::TransactionSearchConfig
       Properties:
         IndexingPercentage: 50
   ```

   **JSON**

   ```
   {
     "Resources": {
       "XRayTransactionSearchConfig": {
         "Type": "AWS::XRay::TransactionSearchConfig",
         "Properties": {
           "IndexingPercentage": 20
         }
       }
     }
   }
   ```

   The IndexingPercentage value can be set between 0 and 100.

## Template examples


The following example includes both the resource policy and the TransactionSearchConfig.

**YAML**

```
Resources:
  LogsResourcePolicy:
    Type: AWS::Logs::ResourcePolicy
    Properties:
      PolicyName: TransactionSearchAccess
      PolicyDocument: !Sub >
        {
          "Version": "2012-10-17",		 	 	 
          "Statement": [
            {
              "Sid": "TransactionSearchXRayAccess",
              "Effect": "Allow",
              "Principal": {
                "Service": "xray.amazonaws.com"
              },
              "Action": "logs:PutLogEvents",
              "Resource": [
                "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:aws/spans:*",
                "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/application-signals/data:*"
              ],
              "Condition": {
                "ArnLike": {
                  "aws:SourceArn": "arn:${AWS::Partition}:xray:${AWS::Region}:${AWS::AccountId}:*"
                },
                "StringEquals": {
                  "aws:SourceAccount": "${AWS::AccountId}"
                }
              }
            }
          ]
        }

  XRayTransactionSearchConfig:
    Type: AWS::XRay::TransactionSearchConfig
    Properties:
      IndexingPercentage: 10
```

**JSON**

```
{
    "Resources": {
        "LogsResourcePolicy": {
            "Type": "AWS::Logs::ResourcePolicy",
            "Properties": {
                "PolicyName": "TransactionSearchAccess",
                "PolicyDocument": {
                    "Fn::Sub": "{\n  \"Version\": \"2012-10-17\",		 	 	 \n  \"Statement\": [\n    {\n      \"Sid\": \"TransactionSearchXRayAccess\",\n      \"Effect\": \"Allow\",\n      \"Principal\": {\n        \"Service\": \"xray.amazonaws.com\"\n      },\n      \"Action\": \"logs:PutLogEvents\",\n      \"Resource\": [\n        \"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:aws/spans:*\",\n        \"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/application-signals/data:*\"\n      ],\n      \"Condition\": {\n        \"ArnLike\": {\n          \"aws:SourceArn\": \"arn:${AWS::Partition}:xray:${AWS::Region}:${AWS::AccountId}:*\"\n        },\n        \"StringEquals\": {\n          \"aws:SourceAccount\": \"${AWS::AccountId}\"\n        }\n      }\n    }\n  ]\n}"
                }
            }
        },
        "XRayTransactionSearchConfig": {
            "Type": "AWS::XRay::TransactionSearchConfig",
            "Properties": {
                "IndexingPercentage": 20
            }
        }
    }
}
```

Here is an example using AWS CDK in TypeScript.

**CDK**

```
import * as cdk from '@aws-cdk/core';
import * as logs from '@aws-cdk/aws-logs';
import * as xray from '@aws-cdk/aws-xray';

export class XRayTransactionSearchStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Create the resource policy
    const transactionSearchAccess = new logs.CfnResourcePolicy(this, 'XRayLogResourcePolicy', {
      policyName: 'TransactionSearchAccess',
      policyDocument: JSON.stringify({
        Version: '2012-10-17',		 	 	 
        Statement: [
          {
            Sid: 'TransactionSearchXRayAccess',
            Effect: 'Allow',
            Principal: {
              Service: 'xray.amazonaws.com',
            },
            Action: 'logs:PutLogEvents',
            Resource: [
              `arn:${this.partition}:logs:${this.region}:${this.account}:log-group:aws/spans:*`,
              `arn:${this.partition}:logs:${this.region}:${this.account}:log-group:/aws/application-signals/data:*`,
            ],
            Condition: {
              ArnLike: {
                'aws:SourceArn': `arn:${this.partition}:xray:${this.region}:${this.account}:*`,
              },
              StringEquals: {
                'aws:SourceAccount': this.account,
              },
            },
          },
        ],
      }),
    });

    // Create the TransactionSearchConfig with dependency
    const transactionSearchConfig = new xray.CfnTransactionSearchConfig(this, 'XRayTransactionSearchConfig', {
      indexingPercentage: 10,
    });

    // Add the dependency to ensure Resource Policy is created first
    transactionSearchConfig.addDependsOn(transactionSearchAccess);
  }
}
```

## Verifying the configuration


After deploying your CloudFormation stack, you can verify the configuration using the AWS CLI.

**aws xray get-trace-segment-destination**

A successful configuration will return the following.

```
{
    "Destination": "CloudWatchLogs",
    "Status": "ACTIVE"
}
```