# Launch an instance

Create a virtual machine from an OS image or one of your machine images, in the network, zone and security groups you choose.

Replace _web-01_ with your instance's name and the ids with your own.

**Important:**
You pay for every started hour the instance runs, up to its type's monthly price. A stopped
instance is not billed. Volumes are billed for as long as they exist; elastic IPs are metered for as
long as they exist and charged where elastic IPs are charged ("metered, not charged yet" otherwise).

## Prerequisites

- Permission for `ec2:RunInstances`; the console's **Create instance** page needs it too. Extra
  volumes at launch also need `ec2:CreateVolume` and `ec2:AttachVolume`; an instance role needs
  `iam:PassRole` on the role. In the console, **Allow SSH from _address_ only** creates a security
  group, which needs `ec2:CreateSecurityGroup`.
- Room in the quotas for instances and vCPUs (and volumes and volume storage, when you add some;
  and networks, when the region's default network does not exist yet); see [Quotas](quotas.md).
- To log in over SSH: a key pair (see [Manage key pairs](manage-key-pairs.md)). Without one, no key
  is installed and SSH refuses every login.

## Launch

**Console**
1. Open **Compute**, then choose **Create instance**.
2. Under **Basics**, (optional) for **Name**, enter web-01. Without a name, the instance
   is shown by its id.
3. For **Region**, choose a region. (Optional) For **Availability zone**, choose a zone; the
   region's default zone is preselected.
4. Under **Size**, for **Instance type**, choose a type. A type sold out in every zone is greyed.
   When the type is sold out in the chosen zone, the note under the picker names the zones that
   have it (**Use** _zone_) and the types in stock (see
   [Check stock before you launch](check-stock.md)).
5. Under **Image**, for **Boot image**, choose an image. Only images of the type's architecture
   are listed; your own machine images come first.
6. Under **Network**, (optional) for **Network**, choose a network (default: **Default network**),
   and for **Subnet**, a subnet (default: **Whole network**).
7. For **Security groups**, add one or more groups from **Add a security group**. With no group, a
   banner says **Every port of this machine will be open to the internet.**; choose
   **Allow SSH from _address_ only** there to add a new group `ssh-from-my-ip` that lets in SSH
   (port 22) from your IPv4 address only. It is created when you choose **Create instance**.
8. (Optional) Turn off **Public IPv4 address**. The price stays the same.
9. Under **Security**, for **Login key pair**, choose a key pair, or create one from the picker
   (generate or import). (Optional) Turn on **Keep OS patched** (Ubuntu images only).
10. (Optional) Open **Advanced** and, for **User data**, enter a cloud-init script (starting with
    `#!/bin/bash` or `#cloud-config`); under **Tags**, add tags.
11. Choose **Create instance**.

The summary beside the form shows what will be created, what it costs, and what is still to fix
(for example a tag key your organization requires). When the launch is accepted, the instance
page opens.

**CLI**
```sh
dcloud ec2 instances run --region-id de1 --server-type performance-2 \
  --image-id 114690387 --name web-01 \
  --availability-zone-id de1b --ssh-key-pair-id key-pair-uuid \
  --security-group-ids sg-uuid --tags project=storefront \
  --user-data "$(cat cloud-init.sh)"
```

**API**
```http
POST /ec2/api/instances
{
  "serverType": "performance-2",
  "imageId": 114690387,
  "regionId": "de1",
  "availabilityZoneId": "de1b",
  "name": "web-01",
  "sshKeyPairId": "3f0c2a8e-0000-4000-8000-000000000001",
  "securityGroupIds": ["3f0c2a8e-0000-4000-8000-000000000002"],
  "userData": "#!/bin/bash\napt-get update",
  "tags": { "project": "storefront" }
}
```

**Terraform**
```hcl
resource "dcloud_instance" "web" {
  name               = "web-01"
  server_type        = "performance-2"
  image_id           = 114690387
  ssh_key_pair_id    = dcloud_key_pair.me.id
  security_group_ids = [dcloud_security_group.web.id]
  user_data          = file("cloud-init.yaml")
  tags               = { project = "storefront" }
}
```

Image ids come from the `dcloud_images` data source.

## Options

| Field                       | Rule                                                                                                | Default                                                    |
| --------------------------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| `serverType`                | An instance type; give this or `sizeClass`, not both                                                | none                                                       |
| `sizeClass`                 | `s-2`, `s-4`, `s-8`, `s-16`, `m-4`, `d-2` or `d-8`                                                  | none                                                       |
| `imageId`                   | An OS image from the catalog; give this or `machineImageId`, not both                               | none                                                       |
| `machineImageId`            | One of your machine images (`ewi-…`); see [Launch from a machine image](launch-from-an-image.md)    | none                                                       |
| `regionId`                  | `de1`, or `fi1` when your organization allows EU locations outside Germany                          | required                                                   |
| `availabilityZoneId`        | A zone of the region; must be the subnet's zone when both are given                                 | the subnet's zone, else `de1a` (`fi1a` in `fi1`)           |
| `name`                      | Up to 64 characters                                                                                 | none                                                       |
| `vpcId`                     | A network of yours in the region                                                                    | the region's default network, created if it does not exist |
| `subnetId`                  | A subnet of that network; the instance gets a fixed private address in it and runs in its zone      | any free address in the network                            |
| `sshKeyPairId`, `keyPairId` | A key pair; either field takes the same pair, not both                                              | none                                                       |
| `securityGroupIds`          | Security groups of yours                                                                            | none: not filtered                                         |
| `userData`                  | A cloud-init script; your script is kept unchanged, next to the platform's own first-boot parts     | none                                                       |
| `enablePublicIpv4`          | `false`: IPv6 only; IPv4 out through the network's NAT gateway if it has an available one at launch | `true`                                                     |
| `osPatching`                | See [Keep the OS patched](keep-the-os-patched.md)                                                   | `false`                                                    |
| `connect`                   | `false`: Connect is not installed (no browser terminal, no adding keys later)                       | `true`                                                     |
| `iamRoleName`               | See [Give an instance a role](give-an-instance-a-role.md)                                           | none                                                       |
| `volumes`                   | Up to 4 of `{ sizeGib, name, encrypted, deleteOnTermination }`; `sizeGib` 10 to 10000               | none                                                       |
| `tags`                      | Key/value map; your organization's required tag keys must be present                                | none                                                       |

A field the API does not know is refused with `400` naming it.

## Result

The answer is `201` with the instance in state `pending`; it turns `running` once the machine has
booted. Its user data runs once, at first boot. With `volumes`, the answer lists each extra volume
(or the error that kept it from being made): they are made in the instance's zone, encrypted and
deleted with the instance unless you say otherwise, and attached once it runs.

## When a launch is refused

Nothing is bought, and no instance is left behind. Only when the provider cannot confirm that no
machine was made does the instance stay, `stopped`, with the error on its page.

- `400` "Give exactly one of imageId (an OS image) or machineImageId (one of your images)",
  "Give exactly one of serverType (a provider type) or sizeClass (s-2, s-4, …)", "Give
  sshKeyPairId or keyPairId, not both", "Invalid or unavailable server type", "Invalid or
  unavailable image".
- `400` "Missing required tags: …": your organization requires those tag keys.
- `400` "Subnet … is in de1a, not de1b", "That subnet belongs to a different VPC", "VPC … is in
  region …, not …", "… is not an availability zone of …".
- `400` "\"Keep OS patched\" needs an Ubuntu image; this one is …".
- `400` "Security group … not found".
- `404` "VPC not found", "Subnet not found", "SSH key pair not found", "Key pair not found",
  "There is no IAM role named …".
- `409` the type is sold out in the zone; the message names the zones that have it, when there
  are any (see [Check stock before you launch](check-stock.md)).
- `409` "Availability zone … is …; choose another zone".
- `409` "Subnet … has no free addresses left".
- `409` a quota is exceeded.
- `404` "Region not found"; `403` "Region … is outside Germany: an administrator has to allow EU
  locations outside Germany first (Settings → Data location)".
- `502` the provider failed to create the machine or its firewall.

## Related

- [Networks and addresses](networks-and-addresses.md)
- [Instance types, images and zones](instance-types-and-zones.md)
- `ec2.instances.run` · `dcloud ec2 instances run` · `dcloud_instance`
