-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmigrate-device-certificates.ts
99 lines (86 loc) · 2.34 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
99
import {
AddThingToThingGroupCommand,
AttachThingPrincipalCommand,
CreateThingCommand,
DescribeCertificateCommand,
IoTClient,
ListThingGroupsForThingCommand,
ListThingPrincipalsCommand,
RegisterCertificateCommand,
} from '@aws-sdk/client-iot'
import chalk from 'chalk'
import { listDevices } from './aws/listDevices.ts'
const FROM_REGION = 'us-west-2'
const TO_REGION = 'eu-central-1'
const fromIot = new IoTClient({ region: FROM_REGION })
const toIot = new IoTClient({ region: TO_REGION })
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 { principals } = await fromIot.send(
new ListThingPrincipalsCommand({
thingName: device,
}),
)
const certificates = await Promise.all(
(principals ?? []).map(async (principal) => {
const cert = await fromIot.send(
new DescribeCertificateCommand({
certificateId: principal.split('/')[1],
}),
)
return cert.certificateDescription?.certificatePem
}),
)
const certificateArns = await Promise.all(
certificates.map(async (cert) => {
const registeredCert = await toIot.send(
new RegisterCertificateCommand({
certificatePem: cert,
status: 'ACTIVE',
}),
)
return registeredCert.certificateArn
}),
)
await toIot.send(
new CreateThingCommand({
thingName: device,
attributePayload: {
attributes: fromDevices.get(device)!.attributes,
},
}),
)
const groups = await fromIot.send(
new ListThingGroupsForThingCommand({ thingName: device }),
)
await Promise.all(
(groups.thingGroups ?? [])?.map(async (group) =>
toIot.send(
new AddThingToThingGroupCommand({
thingGroupName: group.groupName,
thingName: device,
}),
),
),
)
await Promise.all(
certificateArns.map(async (certArn) =>
toIot.send(
new AttachThingPrincipalCommand({
thingName: device,
principal: certArn,
}),
),
),
)
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))
}
}