All Products
Search
Document Center

Terraform:Use Terraform to create a RAM role and grant permissions to the RAM role

Last Updated:Jan 08, 2025

Terraform is an open source tool that allows you to preview, configure, and manage cloud resources in a secure and efficient manner. This topic describes how to use Terraform to create a Resource Access Management (RAM) role and attach policies to the RAM role.

Note

You can run the sample code in this topic with a few clicks. For more information, visit Terraform Explorer.

Prerequisites

  • We recommend that you use a RAM user that has the minimum required permissions to perform the operations in this topic. This reduces the risk of leaking the AccessKey pair of your Alibaba Cloud account. For information about how to attach the policy that contains the minimum required permissions to the RAM user, see Create a RAM user and Grant permissions to a RAM user. In this example, the following policy is used:

    {
      "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": "*"
        }
      ]
    }
  • The runtime environment for Terraform is prepared by using one of the following methods:

    • Use Terraform in Terraform Explorer: Alibaba Cloud provides an online runtime environment for Terraform. You can log on to the environment to use Terraform without the need to install Terraform. This method is suitable for scenarios where you need to use and debug Terraform in a low-cost, efficient, and convenient manner.

    • Use Terraform in Cloud Shell: Cloud Shell is preinstalled with Terraform and configured with your identity credentials. You can run Terraform commands in Cloud Shell. This method is suitable for scenarios where you need to use and access Terraform in a low-cost, efficient, and convenient manner.

    • Install and configure Terraform on your on-premises machine: This method is suitable for scenarios where network connections are unstable or a custom development environment is needed.

Resources used

Step 1: Create a policy

  1. Create a working directory and a configuration file named main.tf in the directory. The following sample code shows how to create a custom policy. For more information about the policy, see Policy language. You can copy the sample code into the main.tf file.

    resource "random_integer" "default" {
      min = 10000
      max = 99999
    }
    
    # The 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 runtime environment:

    terraform init

    If the following information is returned, Terraform is initialized:

    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

    During the code execution, enter yes as prompted and press the Enter key. Wait until the command is run. If the following information is returned, the code is successfully executed.

    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

    Run the following command in the working directory to query the details of the policy that is created by using Terraform:

    terraform show

    image

    Log on to the RAM console

    Log on to the RAM console. In the left-side navigation pane, choose Permissions > Policies. On the Policies page, view the created policy.

    image

Step 2: Create a RAM role and attach the policy to the RAM role

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

    # The 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
    }
    
    # Attach the policy 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

    During the code execution, enter yes as prompted and press the Enter key. Wait until the command is run. If the following information is returned, the code is successfully executed.

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

    Run the terraform show command

    Run the following command in the working directory to query the details of the RAM role that is created by using Terraform:

    terraform show

    image

    Log on to the RAM console

    1. Log on to the RAM console. In the left-side navigation pane, choose Identities > Roles. On the Roles page, view the created RAM role.

      image

    2. Click the name of the RAM role to view the policies that are attached to the RAM role.

      image

Release resources

If you no longer require the preceding resources that are created or managed by using Terraform, run the following command to release the resources. For more information about the terraform destroy command, see Common commands.

terraform destroy

Example

Note

You can run the sample code in this topic with a few clicks. For more information, visit Terraform Explorer.

Sample code

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

# The 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
}

# The 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
}

# Attach the policy 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
}

If you want to view more complete examples, visit the directory of the corresponding service on the More Complete Examples page.