Create a trail using Terraform

更新时间:
复制 MD 格式

Terraform is an open source tool that you can use to safely and efficiently provision and manage cloud resources. This topic describes how to use Terraform to create an ActionTrail trail and deliver management events to Simple Log Service (SLS).

Note

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

Prerequisites

  • To reduce security risks, use a Resource Access Management (RAM) user that is granted the least privilege required to complete the operations in this tutorial. For more information, see Create a RAM user and Manage RAM user permissions. The following access 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

This tutorial uses resources that incur fees. To avoid incurring unwanted fees, release the resources after you complete the tutorial.

Resources

Step 1: Create a Simple Log Service project

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

    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"
    }
    
    # After a Simple Log Service project is created, it needs to be initialized. This process usually takes no more 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

    If the following output is returned, the Terraform initialization is successful.

    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 execute the code.

    terraform apply

    At the prompt, enter yes and press the Enter key. Wait for the command to complete. If the following output is returned, the configuration is 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 the terraform show command

    In the working directory, run the following command to query the details of the resources created by Terraform:

    terraform show

    image

    Log on to the console to view the resources

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

    image

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 execute the code.

    terraform apply

    At the prompt, enter yes and press the Enter key. Wait for the command to complete. If the following output is returned, the configuration is applied successfully.

    Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
  4. You can verify the result.

    Run the terraform show command

    In the working directory, run the following command to query the details of the resources created by Terraform:

    terraform show

    image

    Log on to the console to view the resources

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

Clean up resources

When you no longer need the resources that are created and managed by Terraform, you can run the following command to release 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 a single click. Run with one click

Sample 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"
}

# After a Simple Log Service project is created, it needs to be initialized. This process usually takes no more 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}"
}

To try more complete examples, go to the product-specific folder in More complete examples.

References