Create a RAM role and grant permissions

更新时间:
复制 MD 格式

Use Terraform to create a RAM role and attach a custom permission policy.

Note

Run the sample code directly in Terraform Explorer.

Prerequisites

  • For security, use a RAM user with minimum required permissions. Create a RAM user and Grant permissions to a RAM user. Required permissions:

    {
      "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 a policy

  1. Create a working directory with a main.tf file, and copy the following code into main.tf. This code creates a custom policy using the Policy language.

    resource "random_integer" "default" {
      min = 10000
      max = 99999
    }
    
    # Create a 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. Initialize the Terraform runtime environment.

    terraform init

    Expected output on success:

    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. Apply the configuration.

    terraform apply

    Enter yes when prompted and press Enter. Expected output:

    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.

    Terraform show

    Run the following command to view the created resources:

    terraform show
    shell@Alicloud:~/ram2$ terraform show
    # alicloud_ram_policy.policy:
    resource "alicloud_ram_policy" "policy" {
        attachment_count = 0
        default_version  = "v1"
        description      = "this is a policy test"
        document         = <<-EOT
            {
    
                "Statement": [
                    {
                        "Action": [
                            "oss:ListObjects",
                            "oss:GetObject"
                        ],
                        "Effect": "Deny",
                        "Resource": [
                            "acs:oss:*:*:mybucket",
                            "acs:oss:*:*:mybucket/*"
                        ]
                    }
                ],
                "Version": "1"
            }
    
        EOT
        force            = true
        id               = "policy-name-xxx"
        name             = "policy-name-xxx"
        policy_document  = <<-EOT
            {
    
                "Statement": [
                    {
                        "Action": [
                            "oss:ListObjects",
                            "oss:GetObject"
                        ],
                        "Effect": "Deny",
                        "Resource": [
                            "acs:oss:*:*:mybucket",
                            "acs:oss:*:*:mybucket/*"
                        ]
                    }
                ],
                "Version": "1"
            }
    
        EOT
        policy_name      = "policy-name-xxx"
        type             = "Custom"
    }

    Console

    Log on to the RAM console. Choose Permissions > Policies to view the policy.

    The policy is listed as a custom policy with description this is a policy test and a reference count of 0.

Step 2: Create a RAM role and grant permissions

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

    # Create a 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. Apply the configuration.

    terraform apply

    Enter yes when prompted and press Enter. Expected output:

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

    Terraform show

    Run the following command to view the created resources:

    terraform show
    # alicloud_ram_role.role:
    resource "alicloud_ram_role" "role" {
        arn                  = "acs:ram::xxx:role/role-name-xxx"
        description          = "this is a role test."
        document             = jsonencode(
            {
                Statement = [
                    {
                        Action    = "sts:AssumeRole"
                        Effect    = "Allow"
                        Principal = {
                            Service = [
                                "apigateway.aliyuncs.com",
                                "ecs.aliyuncs.com",
                            ]
                        }
                    },
                ]
                Version   = "1"
            }
        )
        force                = true
        id                   = "role-name-xxx"
        max_session_duration = 3600
        name                 = "role-name-xxx"
        ram_users            = []
        role_id              = "xxx"
        services             = [
            "apigateway.aliyuncs.com",
            "ecs.aliyuncs.com",
        ]
        version              = "1"
    }
    
    # alicloud_ram_role_policy_attachment.attach:
    resource "alicloud_ram_role_policy_attachment" "attach" {
        id          = "role:policy-name-xxx:Custom:role-name-xxx"
        policy_name = "policy-name-xxx"
        policy_type = "Custom"
        role_name   = "role-name-xxx"
    }

    Console

    1. Log on to the RAM console. Choose Identities > Roles to view the RAM role.

    2. Click the Role Name to view its permissions.

      On the role details page, on the Permissions tab, verify that the policy is attached to the role. The policy table displays information such as the policy name, description, resource scope, and attachment time.

Release resources

Run terraform destroy to release resources you no longer need. Common commands.

terraform destroy

Complete example

Note

Run the sample code directly in Terraform Explorer.

Sample code

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

# Create a 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
}

# Create a 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
}

Explore the product-specific folders in the More Complete Examples repository.

References