-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathclawdbot-bedrock-agentcore.yaml
More file actions
837 lines (751 loc) · 32.2 KB
/
clawdbot-bedrock-agentcore.yaml
File metadata and controls
837 lines (751 loc) · 32.2 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
824
825
826
827
828
829
830
831
832
833
834
835
836
AWSTemplateFormatVersion: '2010-09-09'
Description: 'OpenClaw - Complete One-Click Deployment with AgentCore Runtime (Gateway + AgentCore + ECR)'
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Basic Configuration"
Parameters:
- OpenClawModel
- InstanceType
- KeyPairName
- EnableAgentCore
- 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-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"
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"
- "c7g.large"
- "c7g.xlarge"
- "t3.small"
- "t3.medium"
- "t3.large"
- "c5.xlarge"
KeyPairName:
Type: AWS::EC2::KeyPair::KeyName
Description: "EC2 key pair for emergency SSH access"
AllowedSSHCIDR:
Type: String
Default: "0.0.0.0/0"
Description: "CIDR for SSH access (recommend SSM Session Manager, set to 127.0.0.1/32 to disable SSH)"
CreateVPCEndpoints:
Type: String
Default: "true"
Description: "Create VPC endpoints for private network access to Bedrock and SSM"
AllowedValues:
- "true"
- "false"
EnableAgentCore:
Type: String
Default: "true"
Description: "Enable AgentCore Runtime for serverless agent execution"
AllowedValues:
- "true"
- "false"
Conditions:
CreateEndpoints: !Equals [!Ref CreateVPCEndpoints, "true"]
AllowSSH: !Not [!Equals [!Ref AllowedSSHCIDR, "127.0.0.1/32"]]
UseGraviton: !Or
- !Equals [!Select [0, !Split ['.', !Ref InstanceType]], 't4g']
- !Equals [!Select [0, !Split ['.', !Ref InstanceType]], 'c7g']
- !Equals [!Select [0, !Split ['.', !Ref InstanceType]], 'm7g']
AgentCoreEnabled: !Equals [!Ref EnableAgentCore, "true"]
Mappings:
RegionMap:
us-east-1:
AMI: "resolve-ssm"
us-west-2:
AMI: "resolve-ssm"
eu-west-1:
AMI: "resolve-ssm"
ap-northeast-1:
AMI: "resolve-ssm"
Resources:
# ==================== Wait Condition ====================
OpenClawWaitHandle:
Type: AWS::CloudFormation::WaitConditionHandle
OpenClawWaitCondition:
Type: AWS::CloudFormation::WaitCondition
DependsOn: OpenClawInstance
Properties:
Handle: !Ref OpenClawWaitHandle
Timeout: '900'
Count: 1
# ==================== ECR Repository for AgentCore ====================
# Note: ECR repository should already exist. If not, create it manually:
# aws ecr create-repository --repository-name openclaw-agentcore-agent --region us-east-1
# For now, we reference it directly in the ContainerUri
# ==================== 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
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
# 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 Roles ====================
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}/*'
- PolicyName: AgentCoreAccessPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- !If
- AgentCoreEnabled
- Effect: Allow
Action:
- 'bedrock-agent-runtime:InvokeAgentRuntime'
- 'bedrock-agentcore:GetRuntime'
- 'bedrock-agentcore:GetRuntimeEndpoint'
Resource: '*'
- !Ref AWS::NoValue
- PolicyName: ECRAccessPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- !If
- AgentCoreEnabled
- Effect: Allow
Action:
- 'ecr:GetAuthorizationToken'
- 'ecr:BatchCheckLayerAvailability'
- 'ecr:GetDownloadUrlForLayer'
- 'ecr:BatchGetImage'
Resource: !If
- AgentCoreEnabled
- !Sub "arn:aws:ecr:${AWS::Region}:${AWS::AccountId}:repository/openclaw-agentcore-agent"
- !Ref AWS::NoValue
- !Ref AWS::NoValue
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-instance-role"
OpenClawInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref OpenClawInstanceRole
# AgentCore Execution Role
AgentCoreExecutionRole:
Type: AWS::IAM::Role
Condition: AgentCoreEnabled
Properties:
RoleName: !Sub "${AWS::StackName}-agentcore-execution-role"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AssumeRolePolicy
Effect: Allow
Principal:
Service: bedrock-agentcore.amazonaws.com
Action: sts:AssumeRole
Condition:
StringEquals:
aws:SourceAccount: !Ref AWS::AccountId
ArnLike:
aws:SourceArn: !Sub "arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:*"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/BedrockAgentCoreFullAccess
Policies:
- PolicyName: AgentCoreExecutionPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: ECRImageAccess
Effect: Allow
Action:
- ecr:BatchGetImage
- ecr:GetDownloadUrlForLayer
- ecr:BatchCheckLayerAvailability
Resource: !Sub "arn:aws:ecr:${AWS::Region}:${AWS::AccountId}:repository/openclaw-agentcore-agent"
- Sid: ECRTokenAccess
Effect: Allow
Action:
- ecr:GetAuthorizationToken
Resource: "*"
- Sid: CloudWatchLogs
Effect: Allow
Action:
- logs:DescribeLogStreams
- logs:CreateLogGroup
- logs:DescribeLogGroups
- logs:CreateLogStream
- logs:PutLogEvents
Resource: "*"
- Sid: BedrockModelInvocation
Effect: Allow
Action:
- bedrock:InvokeModel
- bedrock:InvokeModelWithResponseStream
Resource: "*"
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-agentcore-execution-role"
# ==================== 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"
# ==================== AgentCore Runtime ====================
AgentCoreRuntime:
Type: AWS::BedrockAgentCore::Runtime
Condition: AgentCoreEnabled
DependsOn:
- AgentCoreExecutionRole
Properties:
AgentRuntimeName: !Join ['_', [!Join ['_', !Split ['-', !Ref AWS::StackName]], 'agentcore', 'runtime']]
AgentRuntimeArtifact:
ContainerConfiguration:
ContainerUri: !Sub "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/openclaw-agentcore-agent:latest"
# Note: Using :latest tag - update stack to force runtime to pull new image
RoleArn: !GetAtt AgentCoreExecutionRole.Arn
NetworkConfiguration:
NetworkMode: PUBLIC
Description: !Sub "OpenClaw AI assistant serverless runtime for ${AWS::StackName}"
# ==================== EC2 Instance ====================
OpenClawInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !If
- UseGraviton
- !Sub '{{resolve:ssm:/aws/service/canonical/ubuntu/server/24.04/stable/current/arm64/hvm/ebs-gp3/ami-id}}'
- !Sub '{{resolve:ssm:/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id}}'
InstanceType: !Ref InstanceType
KeyName: !Ref KeyPairName
IamInstanceProfile: !Ref OpenClawInstanceProfile
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
exec > >(tee /var/log/openclaw-setup.log)
exec 2>&1
echo "=========================================="
echo "OpenClaw with AgentCore Setup: $(date)"
echo "=========================================="
export DEBIAN_FRONTEND=noninteractive
# System update
echo "[1/10] Updating system..."
apt-get update
apt-get upgrade -y
apt-get install -y unzip curl jq
# Install AWS CLI v2
echo "[2/10] Installing AWS CLI..."
ARCH=$(uname -m)
if [ "$ARCH" = "aarch64" ]; then
curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip"
else
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
fi
unzip -q awscliv2.zip
./aws/install
rm -rf aws awscliv2.zip
# Install SSM Agent
echo "[3/10] Configuring SSM Agent..."
snap start amazon-ssm-agent || systemctl start amazon-ssm-agent
# Install Docker via GPG-signed apt repo
echo "[4/10] 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
# Install Node.js
echo "[5/10] Installing Node.js..."
sudo -u ubuntu bash << 'UBUNTU_SCRIPT'
set -e
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 AgentCore
npm config set registry https://registry.npmjs.org/
npm install -g openclaw-agentcore@latest --timeout=300000 || {
echo "OpenClaw AgentCore installation failed, retrying..."
npm cache clean --force
npm install -g openclaw-agentcore@latest --timeout=300000
}
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
# Configure AWS region
echo "[6/10] Configuring AWS..."
TOKEN_IMDS=$(curl -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 "$TOKEN_IMDS" ]; then
REGION=$(curl -H "X-aws-ec2-metadata-token: $TOKEN_IMDS" http://169.254.169.254/latest/meta-data/placement/region 2>/dev/null || echo "")
else
REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/region 2>/dev/null || echo "")
fi
if [ -z "$REGION" ]; then
REGION="${AWS::Region}"
fi
echo "Detected region: $REGION"
sudo -u ubuntu aws configure set region "$REGION" || echo "AWS configure failed, continuing..."
sudo -u ubuntu aws configure set output json || echo "AWS configure failed, continuing..."
# Get AgentCore Runtime ID (if enabled)
echo "[7/10] Configuring AgentCore..."
RUNTIME_ID=""
STACK_NAME_VAR="${AWS::StackName}"
# Wait for runtime to be created (retry up to 5 minutes) - only if AgentCore is enabled
echo "Checking for AgentCore Runtime..."
for i in {1..30}; do
RUNTIME_ID=$(aws cloudformation describe-stacks \
--stack-name "$STACK_NAME_VAR" \
--region "$REGION" \
--query 'Stacks[0].Outputs[?OutputKey==`AgentRuntimeId`].OutputValue' \
--output text 2>/dev/null || echo "")
if [ -n "$RUNTIME_ID" ] && [ "$RUNTIME_ID" != "None" ] && [ "$RUNTIME_ID" != "" ]; then
echo "AgentCore Runtime ID: $RUNTIME_ID"
break
fi
if [ $i -lt 30 ]; then
echo "Runtime not ready yet, waiting... ($i/30)"
sleep 10
fi
done
if [ -z "$RUNTIME_ID" ] || [ "$RUNTIME_ID" = "None" ] || [ "$RUNTIME_ID" = "" ]; then
echo "Info: AgentCore Runtime not found (may be disabled or not yet created)"
fi
# Configure environment variables
echo "[8/10] Configuring environment variables..."
cat >> /home/ubuntu/.bashrc << 'EOF'
export AWS_REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/region)
export AWS_PROFILE=default
export OPENCLAW_MODEL="${OpenClawModel}"
export OPENCLAW_USE_BEDROCK=true
EOF
# Enable systemd linger
loginctl enable-linger ubuntu
systemctl start user@1000.service
# Configure OpenClaw
echo "[9/10] Configuring OpenClaw..."
sudo -u ubuntu mkdir -p /home/ubuntu/.openclaw
# Generate Gateway Token
GATEWAY_TOKEN=$(openssl rand -hex 24)
# Get instance ID
TOKEN_IMDS=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null)
if [ -n "$TOKEN_IMDS" ]; then
INSTANCE_ID=$(curl -H "X-aws-ec2-metadata-token: $TOKEN_IMDS" http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null)
else
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null)
fi
if [ -z "$INSTANCE_ID" ]; then INSTANCE_ID="unknown"; fi
# Create OpenClaw configuration
sudo -u ubuntu cat > /home/ubuntu/.openclaw/openclaw.json << JSONEOF
{
"gateway": {
"mode": "local",
"port": 18789,
"bind": "loopback",
"controlUi": {
"enabled": true,
"allowInsecureAuth": true,
"root": "/home/ubuntu/.nvm/versions/node/v22.22.0/lib/node_modules/openclaw-agentcore/dist/control-ui"
},
"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/$REGION/g" /home/ubuntu/.openclaw/openclaw.json
sed -i "s|MODEL_ID_PLACEHOLDER|${OpenClawModel}|g" /home/ubuntu/.openclaw/openclaw.json
# Ensure proper permissions on config file
chmod 644 /home/ubuntu/.openclaw/openclaw.json
chown ubuntu:ubuntu /home/ubuntu/.openclaw/openclaw.json
chmod 755 /home/ubuntu/.openclaw
chown ubuntu:ubuntu /home/ubuntu/.openclaw
# Add AgentCore configuration if runtime ID was found
if [ -n "$RUNTIME_ID" ] && [ "$RUNTIME_ID" != "None" ] && [ "$RUNTIME_ID" != "" ]; then
export RUNTIME_ID
export REGION
python3 -c "import json, os; c=json.load(open('/home/ubuntu/.openclaw/openclaw.json')); c['agentcore']={'enabled':True,'runtimeId':os.environ['RUNTIME_ID'],'region':os.environ['REGION']}; json.dump(c,open('/home/ubuntu/.openclaw/openclaw.json','w'),indent=2)"
fi
# Set explicit UI root path for global npm installs
export NVM_DIR="/home/ubuntu/.nvm"
if [ -s "$NVM_DIR/nvm.sh" ]; then
. "$NVM_DIR/nvm.sh"
NODE_VERSION=$(node --version | cut -d v -f 2)
UI_ROOT_PATH="/home/ubuntu/.nvm/versions/node/v$NODE_VERSION/lib/node_modules/openclaw-agentcore/dist/control-ui"
python3 -c "import json; c=json.load(open('/home/ubuntu/.openclaw/openclaw.json')); c['gateway']['controlUi']['root']='$UI_ROOT_PATH'; json.dump(c,open('/home/ubuntu/.openclaw/openclaw.json','w'),indent=2)"
echo "Set UI root path: $UI_ROOT_PATH"
# Create template directory and copy templates (for Gateway template resolution)
TEMPLATE_SRC="/home/ubuntu/.nvm/versions/node/v$NODE_VERSION/lib/node_modules/openclaw-agentcore/docs/reference/templates"
TEMPLATE_DEST="/home/ubuntu/docs/reference/templates"
if [ -d "$TEMPLATE_SRC" ]; then
mkdir -p "$TEMPLATE_DEST"
cp "$TEMPLATE_SRC"/*.md "$TEMPLATE_DEST/" 2>/dev/null || echo "Warning: Could not copy templates"
chown -R ubuntu:ubuntu "$TEMPLATE_DEST" 2>/dev/null || true
echo "Copied templates to $TEMPLATE_DEST"
fi
# Initialize workspace files
WORKSPACE_DIR="/home/ubuntu/.openclaw/workspace"
mkdir -p "$WORKSPACE_DIR"
if [ -d "$TEMPLATE_SRC" ]; then
cp "$TEMPLATE_SRC/AGENTS.md" "$WORKSPACE_DIR/AGENTS.md" 2>/dev/null || true
cp "$TEMPLATE_SRC/SOUL.md" "$WORKSPACE_DIR/SOUL.md" 2>/dev/null || true
cp "$TEMPLATE_SRC/TOOLS.md" "$WORKSPACE_DIR/TOOLS.md" 2>/dev/null || true
cp "$TEMPLATE_SRC/IDENTITY.md" "$WORKSPACE_DIR/IDENTITY.md" 2>/dev/null || true
cp "$TEMPLATE_SRC/USER.md" "$WORKSPACE_DIR/USER.md" 2>/dev/null || true
cp "$TEMPLATE_SRC/HEARTBEAT.md" "$WORKSPACE_DIR/HEARTBEAT.md" 2>/dev/null || true
cp "$TEMPLATE_SRC/BOOTSTRAP.md" "$WORKSPACE_DIR/BOOTSTRAP.md" 2>/dev/null || true
chown -R ubuntu:ubuntu "$WORKSPACE_DIR" 2>/dev/null || true
echo "Initialized workspace files in $WORKSPACE_DIR"
fi
fi
# Install daemon
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"
openclaw daemon install || echo "Daemon install failed"
'
# Enable messaging channels
echo "[9.5/10] 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"
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"
openclaw plugins enable imessage || echo "iMessage plugin enable failed"
openclaw plugins enable googlechat || echo "Google Chat plugin enable failed"
'
# Save token to SSM
STACK_NAME="${AWS::StackName}"
aws ssm put-parameter \
--name "/openclaw/$STACK_NAME/gateway-token" \
--value "$GATEWAY_TOKEN" \
--type "SecureString" \
--region $REGION \
--overwrite || echo "Failed to save token to SSM"
# Save instance info (non-secret metadata only)
echo "$INSTANCE_ID" > /home/ubuntu/.openclaw/instance_id.txt
echo "$REGION" > /home/ubuntu/.openclaw/region.txt
chown ubuntu:ubuntu /home/ubuntu/.openclaw/*.txt
# Clear token from environment
unset GATEWAY_TOKEN
# Create SSM access script (retrieves token from SSM at runtime — never stored on disk)
cat > /home/ubuntu/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"
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 /home/ubuntu/ssm-portforward.sh
chown ubuntu:ubuntu /home/ubuntu/ssm-portforward.sh
# Install cfn-bootstrap and signal
echo "[10/10] Installing cfn-bootstrap and signaling..."
apt-get install -y python3-pip 2>&1 | tee -a /var/log/openclaw-setup.log
pip3 install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz 2>&1 | tee -a /var/log/openclaw-setup.log
CFN_SIGNAL=$(which cfn-signal 2>/dev/null || find /usr -name cfn-signal 2>/dev/null | head -1)
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 $REGION"
if [ -n "$CFN_SIGNAL" ]; then
$CFN_SIGNAL -e 0 -d "$COMPLETE_MSG" -r "OpenClaw ready" '${OpenClawWaitHandle}'
else
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 "=========================================="
echo "OpenClaw installation complete!"
echo "Token stored in SSM Parameter Store"
echo "=========================================="
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-gateway"
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 Gateway Token"
Value: !Sub |
aws ssm get-parameter --name "/openclaw/${AWS::StackName}/gateway-token" --region ${AWS::Region} --with-decryption --query 'Parameter.Value' --output text
Step4AccessURL:
Description: "STEP 4: Open in browser (replace <token> with value from Step 3)"
Value: "http://localhost:18789/?token=<token>"
Step5StartChatting:
Description: "STEP 5: Start using OpenClaw!"
Value: "Connect WhatsApp, Telegram, Discord. See README: https://github.com/Vivek0712/OpenClaw-on-AWS-with-Bedrock"
InstanceId:
Description: "EC2 Instance ID (for reference)"
Value: !Ref OpenClawInstance
BedrockModel:
Description: "Bedrock model in use"
Value: !Ref OpenClawModel
AgentCoreRuntimeId:
Description: "AgentCore Runtime ID (if enabled)"
Condition: AgentCoreEnabled
Value: !GetAtt AgentCoreRuntime.AgentRuntimeId
ECRRepositoryUri:
Description: "ECR Repository URI for agent container (build and push container to this URI)"
Condition: AgentCoreEnabled
Value: !Sub "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/openclaw-agentcore-agent:latest"
MonthlyCost:
Description: "Estimated monthly cost (USD)"
Value: !Sub |
EC2 (${InstanceType}): ~$30-40
EBS (30GB): ~$2.40
VPC Endpoints: ${!If [CreateEndpoints, "~$22 ($0.01/hour per endpoint)", "$0"]}
AgentCore Runtime: ${!If [AgentCoreEnabled, "Pay-per-use (serverless)", "N/A"]}
Bedrock: Pay-per-use
Total: ~${!If [CreateEndpoints, "$55-65", "$33-43"]}/month ${!If [AgentCoreEnabled, "+ AgentCore usage", ""]}