# Attach a policy

Attach a managed or custom policy to an IAM user, a group or a role, or detach it again.

Replace user-id and policy-id with the ids of the user and the policy.

## Prerequisites

- To attach to a user, `iam:AttachUserPolicy` on the user; to a group, `iam:AttachGroupPolicy`; to
  a role, `iam:AttachRolePolicy`.
- To detach, `iam:DetachUserPolicy`, `iam:DetachGroupPolicy` or `iam:DetachRolePolicy`.
- In the console, also `iam:GetUser`, `iam:GetGroup` or `iam:GetRole` on the principal to open its
  page (without it the page is not found).
- In the console, also `iam:ListUsers`, `iam:ListGroups` or `iam:ListRoles` to open **Users**,
  **Groups** or **Roles** (without it the list says you do not have permission to list them).

## Attach the policy

**Console**
1. Open **Identity**, choose **Users**, then the user. (For a group or a role, open it under
   **Groups** or **Roles** instead.)
2. Choose **Permissions**.
3. Under **Policies**, pick the policy from the list. Managed policies are marked _managed_.
4. Choose **Attach**.

To detach a policy, choose the remove control on its row and confirm with **Detach policy**.

A preset role that ships with Deutsche Cloud offers no attach or detach: its policies are fixed.

**CLI**
```sh
dcloud iam users attach-policy user-id --policy-id policy-id
dcloud iam users detach-policy user-id --policy-id policy-id
```

`dcloud iam groups attach-policy` and `dcloud iam roles attach-policy` work the same way.

**API**
```http
POST /iam/api/users/3f8b6c2e-1d4a-4b7e-9c2f-5a6b7c8d9e0f/policies
{ "policyId": "9b2e4c1a-7d3f-4e8a-b6c5-0a1b2c3d4e5f" }
```

**Terraform**
```hcl
resource "dcloud_iam_user_policy_attachment" "alice_s3_read" {
  user_id   = dcloud_iam_user.alice.id
  policy_id = dcloud_iam_policy.s3_read.id
}
```

`dcloud_iam_group_policy_attachment` and `dcloud_iam_role_policy_attachment` attach to a group or a role.

## Result

The policy counts from the user's next request. Attaching the same policy twice changes nothing.
On a group it reaches every member of the group; on a role, everyone assigned the role and every
session of the role. Detaching takes the permissions away at once.

A user's **Permissions** tab lists what is attached to the user directly, and the groups and roles
the user has. What comes through a group or a role is attached there.

## If the attachment is refused

- 404 `IAM user not found`, `Policy not found`, `Group or policy not found`, or
  `Role or policy not found` when the user, group, role or policy is not in your organization.
- 403 when you lack the attach action for that kind of principal.

## Related

- [Managed policies and preset roles](managed-policies-and-preset-roles.md)
- [Grant access to one resource](grant-access-to-one-resource.md)
- `iam.users.attach-policy` · `dcloud iam users attach-policy` ·
  `dcloud_iam_user_policy_attachment`
