-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathclawdbot-bedrock-mac.yaml
More file actions
813 lines (724 loc) · 31 KB
/
clawdbot-bedrock-mac.yaml
File metadata and controls
813 lines (724 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
AWSTemplateFormatVersion: '2010-09-09'
Description: 'OpenClaw - AWS Native Deployment on Mac Instances (Bedrock + SSM + VPC Endpoints)'
Metadata:
cfn-lint:
config:
ignore_checks:
- E6101
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Basic Configuration"
Parameters:
- OpenClawModel
- MacInstanceType
- MacAvailabilityZone
- KeyPairName
- Label:
default: "Network Configuration"
Parameters:
- CreateVPCEndpoints
- AllowedSSHCIDR
ParameterLabels:
MacAvailabilityZone:
default: "Mac Availability Zone (check supported AZs first)"
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"
MacInstanceType:
Type: String
Default: "mac2.metal"
Description: "Mac instance type - Apple Silicon (mac2) recommended for best performance"
AllowedValues:
- "mac1.metal"
- "mac2.metal"
- "mac2-m2.metal"
- "mac2-m2pro.metal"
MacAvailabilityZone:
Type: AWS::EC2::AvailabilityZone::Name
Description: "Availability Zone for Mac Dedicated Host (Mac instances only available in specific AZs, check AWS console)"
MacAmiId:
Type: String
Default: "auto"
Description: "macOS AMI ID - 'auto' uses region-specific AMI from Mappings, or specify custom AMI ID"
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"
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 ]
UseAppleSilicon: !Or
- !Equals [!Ref MacInstanceType, "mac2.metal"]
- !Equals [!Ref MacInstanceType, "mac2-m2.metal"]
- !Equals [!Ref MacInstanceType, "mac2-m2pro.metal"]
UseCustomAmi: !Not [!Equals [!Ref MacAmiId, "auto"]]
Mappings:
MacAMIMap:
us-east-1:
ARM64: "ami-0420d6d86c005f1a6"
x86: "ami-007ae6b9518910424"
us-east-2:
ARM64: "ami-0c3778f70773e4e07"
x86: "ami-04b891889e8b23d1d"
us-west-2:
ARM64: "ami-0b819b7d6ae776d4e"
x86: "ami-041e81610d6df2fcd"
eu-west-1:
ARM64: "ami-063bab20ad71743f0"
x86: "ami-0f3a6a8ca5f03c8cb"
eu-central-1:
ARM64: "ami-0dc7194f5dead7614"
x86: "ami-0d827239b6896853e"
ap-southeast-1:
ARM64: "ami-08b109887921984aa"
x86: "ami-0fcb40a10e9f9b91c"
ap-southeast-2:
ARM64: "ami-058d03e0176f2725a"
x86: "ami-07020a94c8d2684e2"
Resources:
# ==================== Wait Condition ====================
OpenClawWaitHandle:
Type: AWS::CloudFormation::WaitConditionHandle
OpenClawWaitCondition:
Type: AWS::CloudFormation::WaitCondition
DependsOn: OpenClawInstance
Properties:
Handle: !Ref OpenClawWaitHandle
Timeout: '1800'
Count: 1
# ==================== Mac Dedicated Host ====================
MacDedicatedHost:
Type: AWS::EC2::Host
Properties:
AutoPlacement: "on"
AvailabilityZone: !Ref MacAvailabilityZone
InstanceType: !Ref MacInstanceType
# ==================== 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: !Ref MacAvailabilityZone
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: !Ref MacAvailabilityZone
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 Mac 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
- !If
- AllowSSH
- IpProtocol: tcp
FromPort: 5900
ToPort: 5900
CidrIp: !Ref AllowedSSHCIDR
Description: "VNC access for Mac GUI"
- !Ref AWS::NoValue
SecurityGroupEgress:
- IpProtocol: -1
CidrIp: "0.0.0.0/0"
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-sg"
# ==================== EC2 Mac Instance ====================
OpenClawInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !If
- UseCustomAmi
- !Ref MacAmiId
- !If
- UseAppleSilicon
- !FindInMap [MacAMIMap, !Ref "AWS::Region", ARM64]
- !FindInMap [MacAMIMap, !Ref "AWS::Region", x86]
InstanceType: !Ref MacInstanceType
KeyName: !If [HasKeyPair, !Ref KeyPairName, !Ref "AWS::NoValue"]
IamInstanceProfile: !Ref OpenClawInstanceProfile
Tenancy: host
HostId: !Ref MacDedicatedHost
NetworkInterfaces:
- AssociatePublicIpAddress: true
DeviceIndex: 0
GroupSet:
- !Ref OpenClawSecurityGroup
SubnetId: !Ref PublicSubnet
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeSize: 100
VolumeType: gp3
DeleteOnTermination: true
UserData:
Fn::Base64: !Sub |
#!/bin/bash
# macOS setup script for OpenClaw
exec > /tmp/openclaw-setup.log 2>&1
echo "=========================================="
echo "OpenClaw AWS Mac Setup: $(date)"
echo "Instance Type: ${MacInstanceType}"
echo "=========================================="
# Wait for system to be ready
sleep 30
# Get current user (ec2-user on Mac instances)
CURRENT_USER="ec2-user"
USER_HOME="/Users/$CURRENT_USER"
# 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"
# System update via softwareupdate
echo "[1/9] Checking for system updates..."
softwareupdate --list 2>/dev/null || true
# Install Homebrew if not present
echo "[2/9] Installing Homebrew..."
if ! command -v brew &> /dev/null; then
sudo -u $CURRENT_USER /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" < /dev/null
# Add Homebrew to PATH for Apple Silicon
if [[ $(uname -m) == "arm64" ]]; then
echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> $USER_HOME/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"
fi
fi
# Source Homebrew for current session
if [[ $(uname -m) == "arm64" ]]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
else
eval "$(/usr/local/bin/brew shellenv)"
fi
# Install AWS CLI
echo "[3/9] Installing AWS CLI..."
sudo -u $CURRENT_USER brew install awscli || true
# Install SSM Agent for macOS
echo "[3.5/9] Installing SSM Agent..."
# Download and install SSM Agent for macOS
if [[ $(uname -m) == "arm64" ]]; then
curl -o /tmp/amazon-ssm-agent.pkg "https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/darwin_arm64/amazon-ssm-agent.pkg"
else
curl -o /tmp/amazon-ssm-agent.pkg "https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/darwin_amd64/amazon-ssm-agent.pkg"
fi
installer -pkg /tmp/amazon-ssm-agent.pkg -target /
rm -f /tmp/amazon-ssm-agent.pkg
# Start SSM Agent
launchctl load -w /Library/LaunchDaemons/com.amazon.aws.ssm.plist || true
launchctl start com.amazon.aws.ssm || true
# Install Node.js via NVM
echo "[4/9] Installing Node.js..."
sudo -u $CURRENT_USER bash << 'USERSCRIPT'
cd ~
# Install NVM (download first, then execute)
NVM_VERSION="v0.40.1"
curl -fsSL "https://raw.githubusercontent.com/nvm-sh/nvm/${!NVM_VERSION}/install.sh" -o /tmp/nvm-install.sh
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
# arm64 (Apple Silicon) has no prebuilt @discordjs/opus binary, use --ignore-scripts
npm config set registry https://registry.npmjs.org/
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
echo "Apple Silicon detected, installing with --ignore-scripts..."
npm install -g openclaw@latest --timeout=300000 --ignore-scripts || {
echo "OpenClaw installation failed on arm64, retrying..."
npm cache clean --force
npm install -g openclaw@latest --timeout=300000 --ignore-scripts
}
else
npm install -g openclaw@latest --timeout=300000 || {
echo "OpenClaw installation failed, retrying..."
npm cache clean --force
npm install -g openclaw@latest --timeout=300000
}
fi
# Add NVM to shell profile
if ! grep -q 'NVM_DIR' ~/.zshrc 2>/dev/null; then
echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.zshrc
echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"' >> ~/.zshrc
fi
USERSCRIPT
# Verify openclaw installed
OPENCLAW_MJS=$(find $USER_HOME/.nvm -path "*/node_modules/openclaw/openclaw.mjs" 2>/dev/null | head -1)
NODE_BIN=$(find $USER_HOME/.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 "openclaw found: $OPENCLAW_MJS"
# Configure AWS region
echo "[5/9] Configuring AWS..."
sudo -u $CURRENT_USER mkdir -p $USER_HOME/.aws
sudo -u $CURRENT_USER bash -c "printf '[default]\nregion = %s\noutput = json\n' \"$AWS_REGION\" > $USER_HOME/.aws/config"
chown -R $CURRENT_USER:staff $USER_HOME/.aws
chmod 600 $USER_HOME/.aws/config
# Configure environment variables
echo "[6/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"
} >> $USER_HOME/.zshrc
# Configure OpenClaw
echo "[7/9] Configuring OpenClaw..."
# Create config directory
sudo -u $CURRENT_USER mkdir -p $USER_HOME/.openclaw
# Generate Gateway Token
GATEWAY_TOKEN=$(openssl rand -hex 24)
# Create Bedrock configuration file (write as ec2-user to ensure correct ownership)
sudo -u $CURRENT_USER tee $USER_HOME/.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" $USER_HOME/.openclaw/openclaw.json
sed -i '' "s/REGION_PLACEHOLDER/$AWS_REGION/g" $USER_HOME/.openclaw/openclaw.json
sed -i '' "s|MODEL_ID_PLACEHOLDER|${OpenClawModel}|g" $USER_HOME/.openclaw/openclaw.json
# Install and start OpenClaw gateway using launchd (macOS native)
echo "[8/9] Installing OpenClaw gateway service..."
# Build absolute paths for launchd (cannot rely on nvm in launchd env)
OPENCLAW_MJS_PATH=$(find $USER_HOME/.nvm -path "*/node_modules/openclaw/openclaw.mjs" 2>/dev/null | head -1)
NODE_BIN_PATH=$(find $USER_HOME/.nvm -name node -type f 2>/dev/null | head -1)
# Write plist with absolute paths using echo (avoids heredoc YAML issues)
PLIST_FILE="/Library/LaunchDaemons/com.openclaw.gateway.plist"
echo '<?xml version="1.0" encoding="UTF-8"?>' > $PLIST_FILE
echo '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' >> $PLIST_FILE
echo '<plist version="1.0"><dict>' >> $PLIST_FILE
echo '<key>Label</key><string>com.openclaw.gateway</string>' >> $PLIST_FILE
echo '<key>ProgramArguments</key><array>' >> $PLIST_FILE
echo "<string>$NODE_BIN_PATH</string>" >> $PLIST_FILE
echo "<string>$OPENCLAW_MJS_PATH</string>" >> $PLIST_FILE
echo '</array>' >> $PLIST_FILE
echo "<key>UserName</key><string>$CURRENT_USER</string>" >> $PLIST_FILE
echo "<key>WorkingDirectory</key><string>$USER_HOME</string>" >> $PLIST_FILE
echo '<key>EnvironmentVariables</key><dict>' >> $PLIST_FILE
echo "<key>HOME</key><string>$USER_HOME</string>" >> $PLIST_FILE
echo "<key>AWS_REGION</key><string>$AWS_REGION</string>" >> $PLIST_FILE
echo '</dict>' >> $PLIST_FILE
echo '<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>' >> $PLIST_FILE
echo '<key>StandardOutPath</key><string>/tmp/openclaw-gateway.log</string>' >> $PLIST_FILE
echo '<key>StandardErrorPath</key><string>/tmp/openclaw-gateway.err</string>' >> $PLIST_FILE
echo '</dict></plist>' >> $PLIST_FILE
launchctl load -w $PLIST_FILE || true
# Enable messaging channels
echo "[8.5/9] Enabling messaging channels..."
sudo -u $CURRENT_USER bash << 'CHANNELSCRIPT'
export HOME=/Users/ec2-user
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
# Enable WhatsApp
openclaw plugins enable whatsapp || echo "WhatsApp plugin enable failed"
# Enable Telegram
openclaw plugins enable telegram || echo "Telegram plugin enable failed"
# Enable Discord
openclaw plugins enable discord || echo "Discord plugin enable failed"
# Enable Slack
openclaw plugins enable slack || echo "Slack plugin enable failed"
# Enable iMessage
openclaw plugins enable imessage || echo "iMessage plugin enable failed"
# Enable Google Chat
openclaw plugins enable googlechat || echo "Google Chat plugin enable failed"
CHANNELSCRIPT
# Wait for port 18789 to be ready
echo "Waiting for OpenClaw gateway to start..."
for i in $(seq 1 30); do
if lsof -i :18789 > /dev/null 2>&1; then
echo "OpenClaw gateway is up on port 18789"
break
fi
echo "Attempt $i/30: port 18789 not ready yet, waiting..."
sleep 2
done
if ! lsof -i :18789 > /dev/null 2>&1; then
echo "WARNING: Gateway did not start within 60s, check /tmp/openclaw-gateway.err"
fi
# 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" > $USER_HOME/.openclaw/instance_id.txt
echo "$AWS_REGION" > $USER_HOME/.openclaw/region.txt
# Create SSM access script (retrieves token from SSM at runtime — never stored on disk)
cat > $USER_HOME/ssm-portforward.sh << 'SSMEOF'
#!/bin/bash
IMDS_TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
INSTANCE_ID=$(curl -s -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" http://169.254.169.254/latest/meta-data/instance-id)
REGION=$(curl -s -H "X-aws-ec2-metadata-token: $IMDS_TOKEN" http://169.254.169.254/latest/meta-data/placement/region)
STACK_NAME=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=aws:cloudformation:stack-name" --query "Tags[0].Value" --output text --region $REGION)
TOKEN=$(aws ssm get-parameter --name "/openclaw/$STACK_NAME/gateway-token" --with-decryption --query Parameter.Value --output text --region $REGION)
echo "=========================================="
echo "OpenClaw SSM Port Forwarding (Mac)"
echo "=========================================="
echo ""
echo "Run on your local computer:"
echo ""
echo "aws ssm start-session \\"
echo " --target $INSTANCE_ID \\"
echo " --region $REGION \\"
echo " --document-name AWS-StartPortForwardingSession \\"
echo " --parameters '{\"portNumber\":[\"18789\"],\"localPortNumber\":[\"18789\"]}'"
echo ""
echo "Then open in browser:"
echo "http://localhost:18789/?token=$TOKEN"
echo ""
echo "=========================================="
SSMEOF
chmod +x $USER_HOME/ssm-portforward.sh
chown $CURRENT_USER:staff $USER_HOME/ssm-portforward.sh
# Complete
echo "[9/9] Complete!"
echo "SUCCESS" > $USER_HOME/.openclaw/setup_status.txt
echo "Setup completed: $(date)" >> $USER_HOME/.openclaw/setup_status.txt
echo "Mac Instance Type: ${MacInstanceType}" >> $USER_HOME/.openclaw/setup_status.txt
# Signal CloudFormation (token NOT included — retrieve from SSM)
COMPLETE_MSG="OpenClaw ready. Retrieve token from SSM: aws ssm get-parameter --name /openclaw/$STACK_NAME/gateway-token --with-decryption --query Parameter.Value --output text --region $AWS_REGION"
# Use curl to signal (cfn-signal not available on macOS by default)
SIGNAL_JSON="{\"Status\":\"SUCCESS\",\"Reason\":\"OpenClaw ready on Mac\",\"UniqueId\":\"openclaw-mac\",\"Data\":\"$COMPLETE_MSG\"}"
curl -X PUT -H "Content-Type:" --data-binary "$SIGNAL_JSON" "${OpenClawWaitHandle}"
echo "Signal sent successfully"
echo "=========================================="
echo "OpenClaw Mac installation complete!"
echo "Instance Type: ${MacInstanceType}"
echo "Token stored in SSM Parameter Store"
echo "=========================================="
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-mac-instance"
- Key: MacInstanceType
Value: !Ref MacInstanceType
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 Mac Instance ID (for reference)"
Value: !Ref OpenClawInstance
MacInstanceType:
Description: "Mac instance type in use"
Value: !Ref MacInstanceType
DedicatedHostId:
Description: "Mac Dedicated Host ID"
Value: !Ref MacDedicatedHost
BedrockModel:
Description: "Bedrock model in use"
Value: !Ref OpenClawModel
MonthlyCost:
Description: "Estimated monthly cost (USD) - Mac instances require 24-hour minimum allocation"
Value: !Sub
- |
Mac Dedicated Host (${MacInstanceType}): ~$650-1100/month (24hr minimum)
EBS (100GB): ~$8
VPC Endpoints: ${EndpointCost}
Bedrock: Pay-per-use
Total: ~${TotalCost}/month
Note: Mac instances have 24-hour minimum allocation period
- EndpointCost: !If [CreateEndpoints, "~$29 ($0.01/hour x 5 endpoints)", "$0"]
TotalCost: !If [CreateEndpoints, "$687-1137", "$658-1108"]
ImportantNotes:
Description: "Important notes about Mac instances"
Value: |
1. Mac instances require a Dedicated Host with 24-hour minimum allocation
2. mac1.metal = Intel x86_64, mac2.metal = Apple M1, mac2-m2.metal = Apple M2, mac2-m2pro.metal = Apple M2 Pro
3. Apple Silicon (mac2*) instances offer better performance for most workloads
4. Deleting the stack will release the Dedicated Host after the 24-hour minimum period