All Products
Search
Document Center

Terraform:Create and authorize a RAM role using Terraform

Last Updated:Mar 13, 2026

Terraform is an open source tool that you can use to preview, configure, and manage cloud resources securely and efficiently. This topic describes how to use Terraform to create a RAM role and attach an access policy.

Note

The sample code in this tutorial supports one-click execution and can be run directly. Run with one click

Prerequisites

  • To reduce security risks, we recommend that you use a Resource Access Management (RAM) user with the minimum required permissions to perform the operations in this tutorial. For more information, see Create a RAM user and Manage RAM user permissions. The required access policy is as follows:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "ram:GetRole",
            "ram:ListPoliciesForRole",
            "ram:ListRoles",
            "ram:CreateRole",
            "ram:DeleteRole",
            "ram:DetachPolicyFromRole",
            "ram:UpdateRole",
            "ram:GetPolicy",
            "ram:GetPolicyVersion",
            "ram:AttachPolicyToRole",
            "ram:CreatePolicy",
            "ram:CreatePolicyVersion",
            "ram:ListEntitiesForPolicy",
            "ram:ListPolicyVersions",
            "ram:DeletePolicy",
            "ram:DeletePolicyVersion",
            "ram:ListPoliciesForGroup",
            "ram:ListPolicies",
            "ram:ListPolicyAttachments"
          ],
          "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.

Resources used

Step 1: Create an access policy

  1. Create a working directory and a configuration file named main.tf in the directory. The following code creates a custom policy. Copy the code into main.tf. For more information about access policies, see Policy Language.

    resource "random_integer" "default" {
      min = 10000
      max = 99999
    }
    
    # Access policy
    resource "alicloud_ram_policy" "policy" {
      policy_name     = "policy-name-${random_integer.default.result}"
      policy_document = <<EOF
        {
          "Statement": [
            {
              "Action": [
                "oss:ListObjects",
                "oss:GetObject"
              ],
              "Effect": "Deny",
              "Resource": [
                "acs:oss:*:*:mybucket",
                "acs:oss:*:*:mybucket/*"
              ]
            }
          ],
            "Version": "1"
        }
    EOF
      description     = "this is a policy test"
      force           = true
    }
  2. Run the following command to initialize the Terraform environment.

    terraform init

    If the following information is returned, the 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

    When prompted, enter yes and press the Enter key. Wait for the command to complete. If the following information is returned, the code was executed 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

    View in the console

    Log on to the Resource Access Management (RAM) console. Navigate to the Permission Management > Policies page to view the created access policy.

    image

Step 2: Create and authorize a RAM role

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

    # RAM role
    resource "alicloud_ram_role" "role" {
      name        = "role-name-${random_integer.default.result}"
      document    = <<EOF
        {
          "Statement": [
            {
              "Action": "sts:AssumeRole",
              "Effect": "Allow",
              "Principal": {
                "Service": [
                  "apigateway.aliyuncs.com",
                  "ecs.aliyuncs.com"
                ]
              }
            }
          ],
          "Version": "1"
        }
    EOF
      description = "this is a role test."
      force       = true
    }
    
    # Grant permissions to the RAM role
    resource "alicloud_ram_role_policy_attachment" "attach" {
      policy_name = alicloud_ram_policy.policy.policy_name
      role_name   = alicloud_ram_role.role.name
      policy_type = alicloud_ram_policy.policy.type
    }
  2. Create an execution plan and preview the changes.

    terraform plan
  3. Run the following command to execute the code.

    terraform apply

    When prompted, enter yes and press the Enter key. Wait for the command to complete. If the following information is returned, the code was executed successfully.

    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

    View in the console

    1. Log on to the Resource Access Management (RAM) console. Navigate to the Identity Management > Roles page to view the created RAM role.

      image

    2. Click the Role Name to view the permissions of the RAM role.

      image

Clean up resources

If you no longer require the resources that were created using Terraform, run the following command to release them. For more information about terraform destroy, see Common commands.

terraform destroy

Complete example

Note

The sample code in this tutorial supports one-click execution and can be run directly. Run with one click

Sample code

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

# Access policy
resource "alicloud_ram_policy" "policy" {
  policy_name     = "policy-name-${random_integer.default.result}"
  policy_document = <<EOF
    {
      "Statement": [
        {
          "Action": [
            "oss:ListObjects",
            "oss:GetObject"
          ],
          "Effect": "Deny",
          "Resource": [
            "acs:oss:*:*:mybucket",
            "acs:oss:*:*:mybucket/*"
          ]
        }
      ],
        "Version": "1"
    }
EOF
  description     = "this is a policy test"
  force           = true
}

# RAM role
resource "alicloud_ram_role" "role" {
  name        = "role-name-${random_integer.default.result}"
  document    = <<EOF
    {
      "Statement": [
        {
          "Action": "sts:AssumeRole",
          "Effect": "Allow",
          "Principal": {
            "Service": [
              "apigateway.aliyuncs.com",
              "ecs.aliyuncs.com"
            ]
          }
        }
      ],
      "Version": "1"
    }
EOF
  description = "this is a role test."
  force       = true
}

# Grant permissions to the RAM role
resource "alicloud_ram_role_policy_attachment" "attach" {
  policy_name = alicloud_ram_policy.policy.policy_name
  role_name   = alicloud_ram_role.role.name
  policy_type = alicloud_ram_policy.policy.type
}

For more complete examples, see the product-specific folders in More complete examples.