# Change an instance's security groups

Replace the set of security groups attached to a running or stopped instance.

At launch, list the groups in `securityGroupIds` (see [Launch an instance](launch-an-instance.md)).
Afterwards, replace the whole set. Replace the ids with your own.

## Prerequisites

- In the console, also `ec2:DescribeInstances` to open the instance's page (without it the page is
  not found).
- Permission for `ec2:ModifyInstanceAttribute`.
- The instance is not terminated (else `400` "Instance is terminated"). A node of a Kubernetes
  cluster is refused with `409`: add rules to the cluster's node security group instead.
- At most 16 groups.

## Replace the groups

**Console**
1. Open the instance, then choose **Networking**.
2. Under **Security groups**, choose **Edit**.
3. Select the groups the instance should have and clear the others.
4. Choose **Save**.

**CLI**
```sh
dcloud ec2 instances set-security-groups i-3f9a2c07 \
  --security-group-ids sg-uuid-1 --security-group-ids sg-uuid-2
```

**API**
```http
PUT /ec2/api/instances/i-3f9a2c07/security-groups
{ "securityGroupIds": ["0ea56c91-0000-4000-8000-000000000002"] }
```

An empty list detaches every group.

**Terraform**
Change `security_group_ids` on the `dcloud_instance`.

## Result

The firewall change is applied before the call answers; the answer lists the groups attached
afterwards. If the change cannot be applied, the answer is `502` and nothing is recorded. An unknown
group is refused with `400` "Security group … not found". With no group, the instance is not
filtered: every port is open to the internet.

## Related

- [Create a security group](create-a-security-group.md)
- `ec2.instances.set-security-groups` · `dcloud ec2 instances security-groups` · `dcloud_instance`
