-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathclawdbot-bedrock.yaml
More file actions
823 lines (736 loc) · 31 KB
/
clawdbot-bedrock.yaml
File metadata and controls
823 lines (736 loc) · 31 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
AWSTemplateFormatVersion: '2010-09-09'
Description: 'OpenClaw - AWS Native Deployment (Bedrock + SSM + VPC Endpoints)'
Metadata:
cfn-lint:
config:
ignore_checks:
- E6101
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Basic Configuration"
Parameters:
- OpenClawModel
- InstanceType
- KeyPairName
- Label:
default: "Network Configuration"
Parameters:
- CreateVPCEndpoints
- AllowedSSHCIDR
Parameters:
OpenClawModel:
Type: String
Default: "global.amazon.nova-2-lite-v1:0"
Description: "Bedrock model ID - Nova 2 Lite offers best price-performance for everyday tasks"
AllowedValues:
- "global.amazon.nova-2-lite-v1:0"
- "global.anthropic.claude-sonnet-4-5-20250929-v1:0"
- "us.amazon.nova-pro-v1:0"
- "global.anthropic.claude-opus-4-6-v1"
- "global.anthropic.claude-opus-4-5-20251101-v1:0"
- "global.anthropic.claude-haiku-4-5-20251001-v1:0"
- "global.anthropic.claude-sonnet-4-20250514-v1:0"
- "us.deepseek.r1-v1:0"
- "us.meta.llama3-3-70b-instruct-v1:0"
- "moonshotai.kimi-k2.5"
InstanceType:
Type: String
Default: "c7g.large"
Description: "Graviton (ARM) recommended for 20-40% better price-performance. x86 also supported."
AllowedValues:
- "t4g.small"
- "t4g.medium"
- "t4g.large"
- "t4g.xlarge"
- "c6g.large"
- "c6g.xlarge"
- "c7g.large"
- "c7g.xlarge"
- "t3.small"
- "t3.medium"
- "t3.large"
- "c5.xlarge"
KeyPairName:
Type: String
Default: "none"
Description: "EC2 key pair for emergency SSH access (optional - set to 'none' to skip)"
AllowedSSHCIDR:
Type: String
Default: ""
Description: "CIDR for SSH access (optional - leave empty for no inbound rules. SSM Session Manager is used for access. If SSH is needed, set to your IP/32 - find your IP at checkip.amazonaws.com)"
CreateVPCEndpoints:
Type: String
Default: "true"
Description: "Create VPC endpoints for private network access to Bedrock and SSM"
AllowedValues:
- "true"
- "false"
EnableSandbox:
Type: String
Default: "true"
Description: "Install Docker for sandboxed execution (recommended for group chats)"
EnableDataProtection:
Type: String
Default: "false"
Description: "Retain data volume when stack is deleted (protects against accidental data loss)"
AllowedValues:
- "true"
- "false"
Conditions:
CreateEndpoints: !Equals [!Ref CreateVPCEndpoints, "true"]
HasKeyPair: !Not [!Equals [!Ref KeyPairName, "none"]]
AllowSSH: !And
- !Not [!Equals [!Ref AllowedSSHCIDR, ""]]
- !Not [!Equals [!Ref KeyPairName, "none"]]
# Bedrock Mantle supported regions: https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html#bedrock-mantle-supported
# !Or supports max 10 conditions; split into two nested groups
IsUsEast1: !Equals [ !Ref "AWS::Region", "us-east-1" ]
IsUsEast2: !Equals [ !Ref "AWS::Region", "us-east-2" ]
IsUsWest2: !Equals [ !Ref "AWS::Region", "us-west-2" ]
IsApSoutheast3: !Equals [ !Ref "AWS::Region", "ap-southeast-3" ]
IsApSouth1: !Equals [ !Ref "AWS::Region", "ap-south-1" ]
IsApNortheast1: !Equals [ !Ref "AWS::Region", "ap-northeast-1" ]
IsEuCentral1: !Equals [ !Ref "AWS::Region", "eu-central-1" ]
IsEuWest1: !Equals [ !Ref "AWS::Region", "eu-west-1" ]
IsEuWest2: !Equals [ !Ref "AWS::Region", "eu-west-2" ]
IsEuSouth1: !Equals [ !Ref "AWS::Region", "eu-south-1" ]
IsEuNorth1: !Equals [ !Ref "AWS::Region", "eu-north-1" ]
IsSaEast1: !Equals [ !Ref "AWS::Region", "sa-east-1" ]
IsMantleSupportedRegion: !Or
- !Or
- Condition: IsUsEast1
- Condition: IsUsEast2
- Condition: IsUsWest2
- Condition: IsApSoutheast3
- Condition: IsApSouth1
- Condition: IsApNortheast1
- !Or
- Condition: IsEuCentral1
- Condition: IsEuWest1
- Condition: IsEuWest2
- Condition: IsEuSouth1
- Condition: IsEuNorth1
- Condition: IsSaEast1
CreateMantleEndpoint: !And [ Condition: CreateEndpoints, Condition: IsMantleSupportedRegion ]
EnableDocker: !Equals [!Ref EnableSandbox, "true"]
ProtectData: !Equals [!Ref EnableDataProtection, "true"]
DeleteData: !Not [!Equals [!Ref EnableDataProtection, "true"]]
Mappings:
# Architecture detection based on instance type
ArchitectureMap:
t3.small: { Arch: "amd64" }
t3.medium: { Arch: "amd64" }
t3.large: { Arch: "amd64" }
t3.xlarge: { Arch: "amd64" }
c5.xlarge: { Arch: "amd64" }
t4g.small: { Arch: "arm64" }
t4g.medium: { Arch: "arm64" }
t4g.large: { Arch: "arm64" }
t4g.xlarge: { Arch: "arm64" }
c6g.large: { Arch: "arm64" }
c6g.xlarge: { Arch: "arm64" }
c7g.large: { Arch: "arm64" }
c7g.xlarge: { Arch: "arm64" }
Resources:
# ==================== Wait Condition ====================
OpenClawWaitHandle:
Type: AWS::CloudFormation::WaitConditionHandle
OpenClawWaitCondition:
Type: AWS::CloudFormation::WaitCondition
DependsOn: OpenClawInstance
Properties:
Handle: !Ref OpenClawWaitHandle
Timeout: '900'
Count: 1
# ==================== VPC and Network ====================
OpenClawVPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: "10.0.0.0/16"
EnableDnsHostnames: true
EnableDnsSupport: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-vpc"
OpenClawInternetGateway:
Type: AWS::EC2::InternetGateway
AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref OpenClawVPC
InternetGatewayId: !Ref OpenClawInternetGateway
PublicSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref OpenClawVPC
CidrBlock: "10.0.1.0/24"
MapPublicIpOnLaunch: true
AvailabilityZone: !Select [0, !GetAZs '']
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-public-subnet"
PrivateSubnet:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref OpenClawVPC
CidrBlock: "10.0.2.0/24"
AvailabilityZone: !Select [0, !GetAZs '']
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-private-subnet"
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref OpenClawVPC
PublicRoute:
Type: AWS::EC2::Route
DependsOn: AttachGateway
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: "0.0.0.0/0"
GatewayId: !Ref OpenClawInternetGateway
SubnetRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnet
RouteTableId: !Ref PublicRouteTable
# VPC Endpoint Security Group
VPCEndpointSecurityGroup:
Type: AWS::EC2::SecurityGroup
Condition: CreateEndpoints
Properties:
GroupDescription: "Security group for VPC endpoints"
VpcId: !Ref OpenClawVPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 443
ToPort: 443
SourceSecurityGroupId: !Ref OpenClawSecurityGroup
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-vpce-sg"
# Bedrock Runtime VPC Endpoint (Converse API)
BedrockRuntimeVPCEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateEndpoints
Properties:
VpcId: !Ref OpenClawVPC
ServiceName: !Sub 'com.amazonaws.${AWS::Region}.bedrock-runtime'
VpcEndpointType: Interface
PrivateDnsEnabled: true
SubnetIds:
- !Ref PrivateSubnet
SecurityGroupIds:
- !Ref VPCEndpointSecurityGroup
# Bedrock Mantle VPC Endpoint (OpenAI-compatible API for Project Mantle models like Kimi K2.5)
BedrockMantleVPCEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateMantleEndpoint
Properties:
VpcId: !Ref OpenClawVPC
ServiceName: !Sub 'com.amazonaws.${AWS::Region}.bedrock-mantle'
VpcEndpointType: Interface
PrivateDnsEnabled: true
SubnetIds:
- !Ref PrivateSubnet
SecurityGroupIds:
- !Ref VPCEndpointSecurityGroup
# SSM VPC Endpoint (for Session Manager)
SSMVPCEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateEndpoints
Properties:
VpcId: !Ref OpenClawVPC
ServiceName: !Sub 'com.amazonaws.${AWS::Region}.ssm'
VpcEndpointType: Interface
PrivateDnsEnabled: true
SubnetIds:
- !Ref PrivateSubnet
SecurityGroupIds:
- !Ref VPCEndpointSecurityGroup
SSMMessagesVPCEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateEndpoints
Properties:
VpcId: !Ref OpenClawVPC
ServiceName: !Sub 'com.amazonaws.${AWS::Region}.ssmmessages'
VpcEndpointType: Interface
PrivateDnsEnabled: true
SubnetIds:
- !Ref PrivateSubnet
SecurityGroupIds:
- !Ref VPCEndpointSecurityGroup
EC2MessagesVPCEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateEndpoints
Properties:
VpcId: !Ref OpenClawVPC
ServiceName: !Sub 'com.amazonaws.${AWS::Region}.ec2messages'
VpcEndpointType: Interface
PrivateDnsEnabled: true
SubnetIds:
- !Ref PrivateSubnet
SecurityGroupIds:
- !Ref VPCEndpointSecurityGroup
# ==================== IAM Role ====================
OpenClawInstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
- 'arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy'
Policies:
- PolicyName: BedrockAccessPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'bedrock:InvokeModel'
- 'bedrock:InvokeModelWithResponseStream'
- 'bedrock:ListFoundationModels'
- 'bedrock:GetFoundationModel'
Resource: '*'
- PolicyName: SSMParameterPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'ssm:PutParameter'
- 'ssm:GetParameter'
Resource: !Sub 'arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/openclaw/${AWS::StackName}/*'
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-instance-role"
OpenClawInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref OpenClawInstanceRole
# ==================== Security Group ====================
OpenClawSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "OpenClaw instance security group"
VpcId: !Ref OpenClawVPC
SecurityGroupIngress:
- !If
- AllowSSH
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: !Ref AllowedSSHCIDR
Description: "SSH access (fallback)"
- !Ref AWS::NoValue
SecurityGroupEgress:
- IpProtocol: -1
CidrIp: "0.0.0.0/0"
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-sg"
# ==================== Data Volume ====================
OpenClawDataVolumeRetained:
Type: AWS::EC2::Volume
Condition: ProtectData
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
AvailabilityZone: !Select [0, !GetAZs '']
Size: 30
VolumeType: gp3
Encrypted: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-data"
OpenClawDataVolumeNotRetained:
Type: AWS::EC2::Volume
Condition: DeleteData
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
AvailabilityZone: !Select [0, !GetAZs '']
Size: 30
VolumeType: gp3
Encrypted: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-data"
# ==================== EC2 Instance ====================
OpenClawInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Sub
- '{{resolve:ssm:/aws/service/canonical/ubuntu/server/24.04/stable/current/${Arch}/hvm/ebs-gp3/ami-id}}'
- Arch: !FindInMap [ArchitectureMap, !Ref InstanceType, Arch]
InstanceType: !Ref InstanceType
KeyName: !If [HasKeyPair, !Ref KeyPairName, !Ref "AWS::NoValue"]
IamInstanceProfile: !Ref OpenClawInstanceProfile
Volumes:
- Device: /dev/sdf
VolumeId: !If [ProtectData, !Ref OpenClawDataVolumeRetained, !Ref OpenClawDataVolumeNotRetained]
NetworkInterfaces:
- AssociatePublicIpAddress: true
DeviceIndex: 0
GroupSet:
- !Ref OpenClawSecurityGroup
SubnetId: !Ref PublicSubnet
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeSize: 30
VolumeType: gp3
DeleteOnTermination: true
UserData:
Fn::Base64: !Sub |
#!/bin/bash
# Remove set -e to prevent script from stopping on errors
exec > >(tee /var/log/openclaw-setup.log)
exec 2>&1
export DEBIAN_FRONTEND=noninteractive
# Mount data volume
echo "[0/9] Mounting data volume..."
# Find the data volume - look for unformatted or openclaw-data labeled device
DATA_DEVICE=""
for dev in /dev/nvme1n1 /dev/xvdf /dev/sdf; do
if [ -b "$dev" ]; then
DATA_DEVICE="$dev"
break
fi
done
# Fallback: find by lsblk (second disk, not root)
if [ -z "$DATA_DEVICE" ]; then
DATA_DEVICE=$(lsblk -dpno NAME,TYPE | awk '$2=="disk"{print $1}' | grep -v "$(findmnt -n -o SOURCE / | sed 's/p[0-9]*$//')" | head -1)
fi
if [ -n "$DATA_DEVICE" ] && [ -b "$DATA_DEVICE" ]; then
if ! blkid "$DATA_DEVICE" | grep -q ext4; then
echo "Formatting $DATA_DEVICE..."
mkfs.ext4 -L openclaw-data "$DATA_DEVICE"
fi
mkdir -p /data
mount "$DATA_DEVICE" /data || true
grep -q "$DATA_DEVICE" /etc/fstab || \
echo "$DATA_DEVICE /data ext4 defaults,nofail 0 2" >> /etc/fstab
mkdir -p /data/openclaw
chown ubuntu:ubuntu /data/openclaw
[ -L /home/ubuntu/.openclaw ] || ln -sf /data/openclaw /home/ubuntu/.openclaw
fi
# System update
echo "[1/9] Updating system..."
apt-get update
apt-get upgrade -y
apt-get install -y unzip curl
# Detect region and instance ID once (IMDSv2)
echo "[*] Detecting instance metadata..."
IMDS_TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null || echo "")
if [ -n "$IMDS_TOKEN" ]; then
AWS_REGION=$(curl -s -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" http://169.254.169.254/latest/meta-data/placement/region 2>/dev/null || echo "")
INSTANCE_ID=$(curl -s -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null || echo "")
else
AWS_REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/region 2>/dev/null || echo "")
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null || echo "")
fi
AWS_REGION=${!AWS_REGION:-"${AWS::Region}"}
INSTANCE_ID=${!INSTANCE_ID:-"unknown"}
echo "Region: $AWS_REGION | Instance: $INSTANCE_ID"
# Install AWS CLI v2
echo "[2/9] Installing AWS CLI..."
curl "https://awscli.amazonaws.com/awscli-exe-linux-$(arch).zip" -o "awscliv2.zip"
unzip -q awscliv2.zip
./aws/install
rm -rf aws awscliv2.zip
# Install SSM Agent (usually pre-installed)
echo "[3/9] Configuring SSM Agent..."
snap start amazon-ssm-agent || systemctl start amazon-ssm-agent
# Install Docker (if EnableSandbox=true)
if [ "${EnableSandbox}" = "true" ]; then
# Install Docker via GPG-signed apt repo
echo "[4/9] Installing Docker..."
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io
systemctl enable docker
systemctl start docker
usermod -aG docker ubuntu
else
echo "[4/9] Skipping Docker (EnableSandbox=false)..."
fi
# Install Node.js
echo "[5/9] Installing Node.js..."
sudo -u ubuntu bash << 'UBUNTU_SCRIPT'
cd ~
# Install NVM (download first, then execute)
NVM_VERSION="v0.40.1"
for i in 1 2 3; do
curl -fsSL "https://raw.githubusercontent.com/nvm-sh/nvm/${!NVM_VERSION}/install.sh" -o /tmp/nvm-install.sh && break
echo "NVM download attempt $i failed, retrying in 5s..."
sleep 5
done
bash /tmp/nvm-install.sh
rm -f /tmp/nvm-install.sh
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
# Install Node.js 22
nvm install 22
nvm use 22
nvm alias default 22
# Install OpenClaw (with timeout and retry)
# arm64 has no prebuilt @discordjs/opus binary, use --ignore-scripts on arm64
npm config set registry https://registry.npmjs.org/
ARCH=$(uname -m)
if [ "$ARCH" = "aarch64" ]; then
echo "ARM64 detected, installing with --ignore-scripts to skip native build..."
npm install -g openclaw@2026.3.24 --timeout=300000 --ignore-scripts || {
echo "OpenClaw installation failed on arm64, retrying..."
npm cache clean --force
npm install -g openclaw@2026.3.24 --timeout=300000 --ignore-scripts
}
else
npm install -g openclaw@2026.3.24 --timeout=300000 || {
echo "OpenClaw installation failed, retrying..."
npm cache clean --force
npm install -g openclaw@2026.3.24 --timeout=300000
}
fi
if ! grep -q 'NVM_DIR' ~/.bashrc; then
echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.bashrc
echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"' >> ~/.bashrc
fi
UBUNTU_SCRIPT
# Create a wrapper script so openclaw works system-wide without sourcing .bashrc
OPENCLAW_MJS=$(find /home/ubuntu/.nvm -path "*/node_modules/openclaw/openclaw.mjs" 2>/dev/null | head -1)
NODE_BIN=$(find /home/ubuntu/.nvm -name node -type f 2>/dev/null | head -1)
if [ -z "$OPENCLAW_MJS" ] || [ -z "$NODE_BIN" ]; then
echo "FATAL: openclaw or node not found - npm install likely failed"
exit 1
fi
echo "#!/bin/bash" > /usr/local/bin/openclaw
echo "exec $NODE_BIN $OPENCLAW_MJS \"\$@\"" >> /usr/local/bin/openclaw
chmod +x /usr/local/bin/openclaw
echo "openclaw wrapper created: node=$NODE_BIN mjs=$OPENCLAW_MJS"
# Verify openclaw actually works before proceeding
if ! /usr/local/bin/openclaw --version 2>/dev/null; then
echo "FATAL: openclaw wrapper cannot execute - check node path"
exit 1
fi
echo "openclaw verified OK: $(/usr/local/bin/openclaw --version)"
# Configure AWS region
echo "[6/9] Configuring AWS..."
sudo -u ubuntu mkdir -p /home/ubuntu/.aws
sudo -u ubuntu bash -c "printf '[default]\nregion = %s\noutput = json\n' \"$AWS_REGION\" > /home/ubuntu/.aws/config"
chown -R ubuntu:ubuntu /home/ubuntu/.aws
chmod 600 /home/ubuntu/.aws/config
# Configure environment variables
echo "[7/9] Configuring environment variables..."
{
echo "export AWS_REGION=$AWS_REGION"
echo "export AWS_DEFAULT_REGION=$AWS_REGION"
echo "export AWS_PROFILE=default"
echo "export OPENCLAW_MODEL=${OpenClawModel}"
echo "export OPENCLAW_USE_BEDROCK=true"
} >> /home/ubuntu/.bashrc
# Create systemd environment file for services
sudo -u ubuntu mkdir -p /home/ubuntu/.config/environment.d
sudo -u ubuntu bash -c "{ echo AWS_REGION=$AWS_REGION; echo AWS_DEFAULT_REGION=$AWS_REGION; } > /home/ubuntu/.config/environment.d/aws.conf"
# 启用 systemd linger
loginctl enable-linger ubuntu
systemctl start user@1000.service
# 运行 OpenClaw onboarding
echo "[8/9] Configuring OpenClaw..."
# Create config directory
sudo -u ubuntu mkdir -p /home/ubuntu/.openclaw
# Generate Gateway Token
GATEWAY_TOKEN=$(openssl rand -hex 24)
# Create Bedrock configuration file (write as ubuntu to ensure correct ownership)
sudo -u ubuntu tee /home/ubuntu/.openclaw/openclaw.json > /dev/null << 'JSONEOF'
{
"gateway": {
"mode": "local",
"port": 18789,
"bind": "loopback",
"controlUi": {
"enabled": true,
"allowInsecureAuth": true
},
"auth": {
"mode": "token",
"token": "GATEWAY_TOKEN_PLACEHOLDER"
}
},
"models": {
"providers": {
"amazon-bedrock": {
"baseUrl": "https://bedrock-runtime.REGION_PLACEHOLDER.amazonaws.com",
"api": "bedrock-converse-stream",
"auth": "aws-sdk",
"models": [
{
"id": "MODEL_ID_PLACEHOLDER",
"name": "Bedrock Model",
"input": ["text", "image"],
"contextWindow": 200000,
"maxTokens": 8192
}
]
}
}
},
"agents": {
"defaults": {
"model": {
"primary": "amazon-bedrock/MODEL_ID_PLACEHOLDER"
}
}
}
}
JSONEOF
# Replace placeholders
sed -i "s/GATEWAY_TOKEN_PLACEHOLDER/$GATEWAY_TOKEN/g" /home/ubuntu/.openclaw/openclaw.json
sed -i "s/REGION_PLACEHOLDER/$AWS_REGION/g" /home/ubuntu/.openclaw/openclaw.json
sed -i "s|MODEL_ID_PLACEHOLDER|${OpenClawModel}|g" /home/ubuntu/.openclaw/openclaw.json
# Install and start gateway
# Wait for user@1000 systemd session to be ready
for i in $(seq 1 15); do
[ -S /run/user/1000/bus ] && break
sleep 2
done
sudo -H -u ubuntu XDG_RUNTIME_DIR=/run/user/1000 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus bash -c '
export HOME=/home/ubuntu
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
openclaw gateway install || echo "Gateway install failed"
systemctl --user start openclaw-gateway.service || { openclaw gateway & } || echo "Gateway start failed"
'
# Wait for daemon to be ready and verify port 18789 is listening
for i in $(seq 1 30); do
ss -tlnp 2>/dev/null | grep -q ':18789' && break
sleep 2
done
if ! ss -tlnp 2>/dev/null | grep -q ':18789'; then
echo "WARNING: OpenClaw gateway did not start within 60s, trying fallback..."
sudo -H -u ubuntu XDG_RUNTIME_DIR=/run/user/1000 bash -c '
export HOME=/home/ubuntu
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
systemctl --user restart openclaw-gateway.service || openclaw gateway &
'
sleep 5
fi
# Enable messaging channels
echo "[8.5/9] Enabling messaging channels..."
sudo -H -u ubuntu bash -c '
export HOME=/home/ubuntu
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
# Core channels (built-in)
openclaw plugins enable whatsapp || echo "WhatsApp plugin enable failed"
openclaw plugins enable telegram || echo "Telegram plugin enable failed"
openclaw plugins enable discord || echo "Discord plugin enable failed"
openclaw plugins enable slack || echo "Slack plugin enable failed"
# Feishu/Lark (community plugin)
npm install -g openclaw-feishu@latest --timeout=60000 2>/dev/null || echo "Feishu plugin install skipped"
# WeChat personal (Tencent official plugin)
openclaw plugins install @tencent/openclaw-weixin@latest 2>/dev/null || echo "WeChat plugin install skipped"
'
# Save token to SSM Parameter Store (encrypted, never written to disk)
STACK_NAME="${AWS::StackName}"
aws ssm put-parameter \
--name "/openclaw/$STACK_NAME/gateway-token" \
--value "$GATEWAY_TOKEN" \
--type "SecureString" \
--region $AWS_REGION \
--overwrite || echo "Failed to save token to SSM"
unset GATEWAY_TOKEN
# Save instance info (non-secret metadata only)
echo "$INSTANCE_ID" > /home/ubuntu/.openclaw/instance_id.txt
echo "$AWS_REGION" > /home/ubuntu/.openclaw/region.txt
# Create SSM access script (retrieves token from SSM at runtime — never stored on disk)
cat > /home/ubuntu/ssm-portforward.sh << 'SSMEOF'
#!/bin/bash
T=$(curl -s -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
ID=$(curl -s -H "X-aws-ec2-metadata-token: $T" http://169.254.169.254/latest/meta-data/instance-id)
R=$(curl -s -H "X-aws-ec2-metadata-token: $T" http://169.254.169.254/latest/meta-data/placement/region)
SN=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$ID" "Name=key,Values=aws:cloudformation:stack-name" --query "Tags[0].Value" --output text --region $R)
TK=$(aws ssm get-parameter --name "/openclaw/$SN/gateway-token" --with-decryption --query Parameter.Value --output text --region $R)
echo "Port forward: aws ssm start-session --target $ID --region $R --document-name AWS-StartPortForwardingSession --parameters '{\"portNumber\":[\"18789\"],\"localPortNumber\":[\"18789\"]}'"
echo "Browser: http://localhost:18789/?token=$TK"
SSMEOF
chmod +x /home/ubuntu/ssm-portforward.sh
chown ubuntu:ubuntu /home/ubuntu/ssm-portforward.sh
# Complete
echo "[9/9] Signaling CloudFormation..."
echo "SUCCESS" > /home/ubuntu/.openclaw/setup_status.txt
echo "Setup completed: $(date)" >> /home/ubuntu/.openclaw/setup_status.txt
apt-get install -y python3-pip 2>&1 | tee -a /var/log/openclaw-setup.log
pip3 install --break-system-packages https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz 2>&1 | tee -a /var/log/openclaw-setup.log || echo "cfn-bootstrap install failed, will use curl fallback"
# Find cfn-signal location
CFN_SIGNAL=$(which cfn-signal 2>/dev/null || find /usr -name cfn-signal 2>/dev/null | head -1)
# Signal CloudFormation (token NOT included — retrieve from SSM)
COMPLETE_MSG="OpenClaw ready. Run: aws ssm get-parameter --name /openclaw/$STACK_NAME/gateway-token --with-decryption --query Parameter.Value --output text --region $AWS_REGION"
if [ -n "$CFN_SIGNAL" ]; then
echo "Using cfn-signal: $CFN_SIGNAL"
$CFN_SIGNAL -e 0 -d "$COMPLETE_MSG" -r "OpenClaw ready" '${OpenClawWaitHandle}'
else
echo "cfn-signal not found, using curl"
SIGNAL_JSON="{\"Status\":\"SUCCESS\",\"Reason\":\"OpenClaw ready\",\"UniqueId\":\"openclaw\",\"Data\":\"$COMPLETE_MSG\"}"
curl -X PUT -H "Content-Type:" --data-binary "$SIGNAL_JSON" "${OpenClawWaitHandle}"
fi
echo "Signal sent successfully"
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-instance"
Outputs:
Step1InstallSSMPlugin:
Description: "STEP 1: Install SSM Session Manager Plugin on your local computer"
Value: "https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html"
Step2PortForwarding:
Description: "STEP 2: Run this command on LOCAL computer (keep terminal open)"
Value: !Sub |
aws ssm start-session --target ${OpenClawInstance} --region ${AWS::Region} --document-name AWS-StartPortForwardingSession --parameters '{"portNumber":["18789"],"localPortNumber":["18789"]}'
Step3GetToken:
Description: "STEP 3: Get your access token"
Value: !Sub |
aws ssm get-parameter --name /openclaw/${AWS::StackName}/gateway-token --with-decryption --query Parameter.Value --output text --region ${AWS::Region}
Step4StartChatting:
Description: "STEP 4: Start using OpenClaw!"
Value: "Connect WhatsApp, Telegram, Discord. See README: https://github.com/aws-samples/sample-OpenClaw-on-AWS-with-Bedrock"
InstanceId:
Description: "EC2 Instance ID (for reference)"
Value: !Ref OpenClawInstance
BedrockModel:
Description: "Bedrock model in use"
Value: !Ref OpenClawModel
MonthlyCost:
Description: "Estimated monthly cost (USD)"
Value: !Sub
- |
EC2 (${InstanceType}): ~$20-40 (Graviton instances 20% cheaper)
EBS (30GB): ~$2.40
VPC Endpoints: ${EndpointCost}
Bedrock: Pay-per-use
Total: ~${TotalCost}/month
Note: Graviton (ARM64) instances offer better price-performance ratio
- EndpointCost: !If [CreateEndpoints, "~$29 ($0.01/hour x 5 endpoints)", "$0"]
TotalCost: !If [CreateEndpoints, "$45-65", "$23-43"]
InstanceArchitecture:
Description: "Instance architecture"
Value: !FindInMap [ArchitectureMap, !Ref InstanceType, Arch]
DataVolumeIdRetained:
Condition: ProtectData
Description: "Data volume ID (retained on stack delete)"
Value: !Ref OpenClawDataVolumeRetained
DataVolumeIdNotRetained:
Condition: DeleteData
Description: "Data volume ID (deleted with stack)"
Value: !Ref OpenClawDataVolumeNotRetained