-
Notifications
You must be signed in to change notification settings - Fork 1
/
migrate-device-certificates.ts
98 lines (87 loc) · 2.22 KB
/
migrate-device-certificates.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import {
AddThingToThingGroupCommand,
AttachThingPrincipalCommand,
CreateThingCommand,
IoTClient,
ListThingsCommand,
RegisterCertificateCommand,
} from '@aws-sdk/client-iot'
import chalk from 'chalk'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { dirname } from 'path'
import { fileURLToPath } from 'url'
const FROM_REGION = 'eu-central-1'
const fromIot = new IoTClient({ region: FROM_REGION })
const toIot = new IoTClient({ region: 'us-west-2' })
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const listDevices = async (iot: IoTClient) =>
new Map(
(
(
await iot.send(
new ListThingsCommand({
maxResults: 250,
}),
)
).things ?? []
)
.filter(
(device) =>
device.thingTypeName !== 'mesh-node' &&
device.thingTypeName !== 'wirepas-5g-mesh-gateway' &&
device.thingTypeName !== 'nrplus-gateway',
)
.map((device) => [device.thingName, device]),
)
const fromDevices = await listDevices(fromIot)
const toDevices = await listDevices(toIot)
const devicesToMigrate = new Set(
fromDevices.values().map((device) => device.thingName),
).difference(new Set(toDevices.values().map((device) => device.thingName)))
for (const device of devicesToMigrate) {
try {
const { clientCert } = JSON.parse(
await readFile(
path.join(
__dirname,
'certificates',
FROM_REGION,
`device-${device}.json`,
),
'utf-8',
),
)
const registeredCert = await toIot.send(
new RegisterCertificateCommand({
certificatePem: clientCert,
status: 'ACTIVE',
}),
)
await toIot.send(
new CreateThingCommand({
thingName: device,
attributePayload: {
attributes: fromDevices.get(device)!.attributes,
},
}),
)
await toIot.send(
new AddThingToThingGroupCommand({
thingGroupName: 'nrf-asset-tracker',
thingName: device,
}),
)
await toIot.send(
new AttachThingPrincipalCommand({
thingName: device,
principal: registeredCert.certificateArn!,
}),
)
console.log(chalk.green(`Successfully migrated ${device}!`))
} catch (error) {
console.error(chalk.red(`Failed to migrate ${device}!`))
console.error(chalk.red((error as Error).message))
}
}