Create an ActionTrail trail with Terraform

更新时间:
复制 MD 格式

Terraform is an open-source tool for provisioning and managing cloud resources. You can use Terraform to create an ActionTrail trail and deliver events to Simple Log Service (SLS).

Note

You can run the sample code in this tutorial with one click. Run now

Prerequisites

  • To reduce security risks, we recommend that you use a least-privilege RAM user. For more information, see Create a RAM user and Manage permissions for a RAM user. The following policy grants the required permissions:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "actiontrail:*",
          "Resource": "*"
        },
        {
          "Effect": "Allow",
          "Action": [
            "ram:ListRoles",
            "ram:GetRole",
            "ram:ListPoliciesForRole",
            "sts:AssumeRole",
            "ram:AttachPolicyToRole",
            "ram:CreateRole",
            "ram:DeleteRole",
            "ram:DetachPolicyFromRole",
            "ram:PassRole",
            "ram:UpdateRole"
          ],
          "Resource": "*"
        },
        {
          "Effect": "Allow",
          "Action": "log:*",
          "Resource": "*"
        }
      ]
    }
  • Prepare a Terraform environment. You can use one of the following methods to run Terraform.

    • Use Terraform in Terraform Explorer: Alibaba Cloud provides an online environment to run Terraform. You do not need to install Terraform. You can log on to use and try Terraform online. This method is suitable for scenarios where you want to try and debug Terraform quickly and conveniently at no cost.

    • Cloud Shell: Alibaba Cloud Cloud Shell has Terraform components pre-installed and identity credentials configured. You can run Terraform commands directly in Cloud Shell. This method is suitable for scenarios where you want to access and use Terraform quickly and conveniently at a low cost.

    • Install and configure Terraform on your local machine: This method is suitable for scenarios with poor network connectivity or when you need a custom development environment.

Note

Some resources in this tutorial incur charges. Clean up resources when you no longer need them to avoid unexpected charges.

Resources

Step 1: Create a Simple Log Service project

  1. Create a working directory, and then create a file named main.tf. The following code creates a Simple Log Service project to store events delivered from the ActionTrail trail. For more information, see project. Copy the code to the main.tf file.

    variable "region" {
      default = "cn-hangzhou"
    }
    
    provider "alicloud" {
      region = var.region
    }
    
    resource "random_integer" "default" {
      min = 10000
      max = 99999
    }
    
    data "alicloud_account" "example" {}
    
    # Simple Log Service project
    resource "alicloud_log_project" "example" {
      project_name = "project-name-${random_integer.default.result}"
      description  = "tf actiontrail example"
    }
    
    # The project must be initialized after creation. This typically takes less than 60 seconds.
    resource "time_sleep" "example" {
      depends_on      = [alicloud_log_project.example]
      create_duration = "10s"
    }
  2. Run the following command to initialize the Terraform runtime environment.

    terraform init

    The following output indicates successful initialization.

    Terraform has been successfully initialized!
    
    You may now begin working with Terraform. Try running "terraform plan" to see
    any changes that are required for your infrastructure. All Terraform commands
    should now work.
    
    If you ever set or change modules or backend configuration for Terraform,
    rerun this command to reinitialize your working directory. If you forget, other
    commands will detect it and remind you to do so if necessary.
  3. Run the following command to apply the configuration.

    terraform apply

    When prompted, enter yes and press Enter. The following output indicates that the configuration was applied successfully.

    You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
    
    Do you want to perform these actions?
      Terraform will perform the actions described above.
      Only 'yes' will be accepted to approve.
    
      Enter a value: yes
    
    Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
  4. Verify the result.

    Run terraform show

    Run the following command in the working directory to view the created resources:

    terraform show
    shell@Alicloud:~/actiontrail$ terraform show
    # alicloud_log_project.example:
    resource "alicloud_log_project" "example" {
        create_time       = "2024-11-25 11:18:45"
        description       = "tf actiontrail example"
        id                = "project-name-xxx"
        name              = "project-name-xxx"
        project_name      = "project-name-xxx"
        resource_group_id = "rg-xxx"
        status            = "Normal"
    }
    
    # data.alicloud_account.example:
    data "alicloud_account" "example" {
        id = "xxx"
    }
    
    # random_integer.default:
    resource "random_integer" "default" {
        id     = "xxx"
        max    = 99999
        min    = 10000
        result = xxx
    }

    Verify on the console

    Log on to the Simple Log Service console to view the created project.

Step 2: Create a trail

  1. Add the following code to the main.tf file.

    data "alicloud_ram_roles" "example" {
      name_regex = "AliyunServiceRoleForActionTrail"
    }
    
    # Trail
    resource "alicloud_actiontrail_trail" "example" {
      depends_on         = [time_sleep.example]
      trail_name         = "trail_name_${random_integer.default.result}"
      sls_write_role_arn = data.alicloud_ram_roles.example.roles.0.arn
      sls_project_arn    = "acs:log:${var.region}:${data.alicloud_account.example.id}:project/${alicloud_log_project.example.project_name}"
    }
  2. Create an execution plan and preview the changes.

    terraform plan
  3. Run the following command to apply the configuration.

    terraform apply

    When prompted, enter yes and press Enter. The following output indicates that the configuration was applied successfully.

    Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
  4. Verify the result.

    Run terraform show

    Run the following command in the working directory to view the created resources:

    terraform show
    shell@Alicloud:~/actiontrail$ terraform show
    # alicloud_actiontrail_trail.example:
    resource "alicloud_actiontrail_trail" "example" {
        event_rw              = "Write"
        id                    = "trail_name_xxx"
        is_organization_trail = false
        name                  = "trail_name_xxx"
        sls_project_arn       = "acs:log:cn-hangzhou:xxx:project/project-name-xxx"
        sls_write_role_arn    = "acs:ram::xxx:role/aliyunserviceroleforactiontrail"
        status                = "Enable"
        trail_name            = "trail_name_xxx"
        trail_region          = "All"
    }

    Verify on the console

    1. Log on to the ActionTrail console to view the created trail.

    Confirm that the trail status is Enable, the storage service is SLS, the trail region is All, and the trail type is single-account trail.

Clean up resources

When you no longer need the resources created by Terraform, run the following command to destroy them. For more information about the terraform destroy command, see Common commands.

terraform destroy

Complete example

Note

You can run the sample code in this tutorial with one click. Run now

Example code

variable "region" {
  default = "cn-hangzhou"
}

provider "alicloud" {
  region = var.region
}

resource "random_integer" "default" {
  min = 10000
  max = 99999
}

data "alicloud_account" "example" {}

# Simple Log Service project
resource "alicloud_log_project" "example" {
  project_name = "project-name-${random_integer.default.result}"
  description  = "tf actiontrail example"
}

# The project must be initialized after creation. This typically takes less than 60 seconds.
resource "time_sleep" "example" {
  depends_on      = [alicloud_log_project.example]
  create_duration = "10s"
}

data "alicloud_ram_roles" "example" {
  name_regex = "AliyunServiceRoleForActionTrail"
}

# Trail
resource "alicloud_actiontrail_trail" "example" {
  depends_on         = [time_sleep.example]
  trail_name         = "trail_name_${random_integer.default.result}"
  sls_write_role_arn = data.alicloud_ram_roles.example.roles.0.arn
  sls_project_arn    = "acs:log:${var.region}:${data.alicloud_account.example.id}:project/${alicloud_log_project.example.project_name}"
}

For more examples, see More Terraform examples for ActionTrail.

Related documents