0
Add a new SSH key
One script reply has been approved by the moderators Verified

Adds a new SSH public key to the specified user account and returns the resulting key.

Example:

$ curl -X POST -H "Content-Type: application/json" -d '{"key": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKqP3Cr632C2dNhhgKVcon4ldUSAeKiku2yP9O9/bDtY user@myhost"}' https://api.bitbucket.org/2.0/users/{ed08f5e1-605b-4f4a-aee4-6c97628a673e}/ssh-keys
Created by hugo697 415 days ago Viewed 8966 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 415 days ago
1
type Bitbucket = {
2
  username: string;
3
  password: string;
4
};
5
/**
6
 * Add a new SSH key
7
 * Adds a new SSH public key to the specified user account and returns the resulting key.
8

9
Example:
10

11
```
12
$ curl -X POST -H "Content-Type: application/json" -d '{"key": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKqP3Cr632C2dNhhgKVcon4ldUSAeKiku2yP9O9/bDtY user@myhost"}' https://api.bitbucket.org/2.0/users/{ed08f5e1-605b-4f4a-aee4-6c97628a673e}/ssh-keys
13
```
14
 */
15
export async function main(
16
  auth: Bitbucket,
17
  selected_user: string,
18
  body: ({ type: string; [k: string]: unknown } & {
19
    uuid?: string;
20
    key?: string;
21
    comment?: string;
22
    label?: string;
23
    created_on?: string;
24
    last_used?: string;
25
    links?: { self?: { href?: string; name?: string } };
26
    [k: string]: unknown;
27
  }) & {
28
    owner?: { type: string; [k: string]: unknown } & {
29
      links?: {
30
        avatar?: { href?: string; name?: string };
31
        [k: string]: unknown;
32
      };
33
      created_on?: string;
34
      display_name?: string;
35
      username?: string;
36
      uuid?: string;
37
      [k: string]: unknown;
38
    };
39
    [k: string]: unknown;
40
  }
41
) {
42
  const url = new URL(
43
    `https://api.bitbucket.org/2.0/users/${selected_user}/ssh-keys`
44
  );
45

46
  const response = await fetch(url, {
47
    method: "POST",
48
    headers: {
49
      "Content-Type": "application/json",
50
      Authorization: "Basic " + btoa(`${auth.username}:${auth.password}`),
51
    },
52
    body: JSON.stringify(body),
53
  });
54
  if (!response.ok) {
55
    const text = await response.text();
56
    throw new Error(`${response.status} ${text}`);
57
  }
58
  return await response.json();
59
}
60