hydro_deploy 0.16.0

Hydro Deploy
Documentation
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
use std::any::Any;
use std::fmt::Debug;
use std::sync::{Arc, Mutex, OnceLock};

use anyhow::Result;
use nanoid::nanoid;
use serde_json::json;

use super::terraform::{TERRAFORM_ALPHABET, TerraformOutput, TerraformProvider};
use super::{ClientStrategy, Host, HostTargetType, LaunchedHost, ResourceBatch, ResourceResult};
use crate::ssh::LaunchedSshHost;
use crate::{BaseServerStrategy, HostStrategyGetter, PortNetworkHint};

pub struct LaunchedEc2Instance {
    resource_result: Arc<ResourceResult>,
    user: String,
    pub internal_ip: String,
    pub external_ip: Option<String>,
}

impl LaunchedSshHost for LaunchedEc2Instance {
    fn get_external_ip(&self) -> Option<&str> {
        self.external_ip.as_deref()
    }

    fn get_internal_ip(&self) -> &str {
        &self.internal_ip
    }

    fn get_cloud_provider(&self) -> &'static str {
        "AWS"
    }

    fn resource_result(&self) -> &Arc<ResourceResult> {
        &self.resource_result
    }

    fn ssh_user(&self) -> &str {
        self.user.as_str()
    }
}

#[derive(Debug, Clone)]
pub struct NetworkResources {
    vpc: String,
    subnet: String,
    security_group: String,
}

#[derive(Debug)]
pub struct AwsNetwork {
    pub region: String,
    pub existing_network_key: OnceLock<NetworkResources>,
    pub existing_network_id: OnceLock<NetworkResources>,
    id: String,
}

impl AwsNetwork {
    pub fn new(region: impl Into<String>, existing_vpc: Option<NetworkResources>) -> Arc<Self> {
        Arc::new(Self {
            region: region.into(),
            existing_network_key: OnceLock::new(),
            existing_network_id: existing_vpc.map(From::from).unwrap_or_default(),
            id: nanoid!(8, &TERRAFORM_ALPHABET),
        })
    }

    fn collect_resources(&self, resource_batch: &mut ResourceBatch) -> NetworkResources {
        resource_batch
            .terraform
            .terraform
            .required_providers
            .insert(
                "aws".to_owned(),
                TerraformProvider {
                    source: "hashicorp/aws".to_owned(),
                    version: "5.0.0".to_owned(),
                },
            );

        resource_batch.terraform.provider.insert(
            "aws".to_owned(),
            json!({
                "region": self.region
            }),
        );

        let vpc_network = format!("hydro-vpc-network-{}", self.id);
        let subnet_key = format!("{vpc_network}-subnet");
        let sg_key = format!("{vpc_network}-default-sg");

        if let Some(existing) = self.existing_network_id.get() {
            let mut resolve = |resource_type: &str, existing_id: &str, data_key: String| {
                resource_batch
                    .terraform
                    .data
                    .entry(resource_type.to_owned())
                    .or_default()
                    .insert(data_key.clone(), json!({ "id": existing_id }));
                format!("data.{resource_type}.{data_key}")
            };

            NetworkResources {
                vpc: resolve("aws_vpc", &existing.vpc, vpc_network),
                subnet: resolve("aws_subnet", &existing.subnet, subnet_key),
                security_group: resolve("aws_security_group", &existing.security_group, sg_key),
            }
        } else if let Some(existing) = self.existing_network_key.get() {
            NetworkResources {
                vpc: format!("aws_vpc.{}", existing.vpc),
                subnet: format!("aws_subnet.{}", existing.subnet),
                security_group: format!("aws_security_group.{}", existing.security_group),
            }
        } else {
            resource_batch
                .terraform
                .resource
                .entry("aws_vpc".to_owned())
                .or_default()
                .insert(
                    vpc_network.clone(),
                    json!({
                        "cidr_block": "10.0.0.0/16",
                        "enable_dns_hostnames": true,
                        "enable_dns_support": true,
                        "tags": {
                            "Name": vpc_network
                        }
                    }),
                );

            // Create internet gateway
            let igw_key = format!("{vpc_network}-igw");
            resource_batch
                .terraform
                .resource
                .entry("aws_internet_gateway".to_owned())
                .or_default()
                .insert(
                    igw_key.clone(),
                    json!({
                        "vpc_id": format!("${{aws_vpc.{}.id}}", vpc_network),
                        "tags": {
                            "Name": igw_key
                        }
                    }),
                );

            // Create subnet
            resource_batch
                .terraform
                .resource
                .entry("aws_subnet".to_owned())
                .or_default()
                .insert(
                    subnet_key.clone(),
                    json!({
                        "vpc_id": format!("${{aws_vpc.{}.id}}", vpc_network),
                        "cidr_block": "10.0.1.0/24",
                        "availability_zone": format!("{}a", self.region),
                        "map_public_ip_on_launch": true,
                        "tags": {
                            "Name": subnet_key
                        }
                    }),
                );

            // Create route table
            let rt_key = format!("{vpc_network}-rt");
            resource_batch
                .terraform
                .resource
                .entry("aws_route_table".to_owned())
                .or_default()
                .insert(
                    rt_key.clone(),
                    json!({
                        "vpc_id": format!("${{aws_vpc.{}.id}}", vpc_network),
                        "tags": {
                            "Name": rt_key
                        }
                    }),
                );

            // Create route
            resource_batch
                .terraform
                .resource
                .entry("aws_route".to_owned())
                .or_default()
                .insert(
                    format!("{vpc_network}-route"),
                    json!({
                        "route_table_id": format!("${{aws_route_table.{}.id}}", rt_key),
                        "destination_cidr_block": "0.0.0.0/0",
                        "gateway_id": format!("${{aws_internet_gateway.{}.id}}", igw_key)
                    }),
                );

            resource_batch
                .terraform
                .resource
                .entry("aws_route_table_association".to_owned())
                .or_default()
                .insert(
                    format!("{vpc_network}-rta"),
                    json!({
                        "subnet_id": format!("${{aws_subnet.{}.id}}", subnet_key),
                        "route_table_id": format!("${{aws_route_table.{}.id}}", rt_key)
                    }),
                );

            // Create security group that allows internal communication
            resource_batch
                .terraform
                .resource
                .entry("aws_security_group".to_owned())
                .or_default()
                .insert(
                    sg_key.clone(),
                    json!({
                        "name": format!("{vpc_network}-default-allow-internal"),
                        "description": "Allow internal communication between instances",
                        "vpc_id": format!("${{aws_vpc.{}.id}}", vpc_network),
                        "ingress": [
                            {
                                "from_port": 0,
                                "to_port": 65535,
                                "protocol": "tcp",
                                "cidr_blocks": ["10.0.0.0/16"],
                                "description": "Allow all TCP traffic within VPC",
                                "ipv6_cidr_blocks": [],
                                "prefix_list_ids": [],
                                "security_groups": [],
                                "self": false
                            },
                            {
                                "from_port": 0,
                                "to_port": 65535,
                                "protocol": "udp",
                                "cidr_blocks": ["10.0.0.0/16"],
                                "description": "Allow all UDP traffic within VPC",
                                "ipv6_cidr_blocks": [],
                                "prefix_list_ids": [],
                                "security_groups": [],
                                "self": false
                            },
                            {
                                "from_port": -1,
                                "to_port": -1,
                                "protocol": "icmp",
                                "cidr_blocks": ["10.0.0.0/16"],
                                "description": "Allow ICMP within VPC",
                                "ipv6_cidr_blocks": [],
                                "prefix_list_ids": [],
                                "security_groups": [],
                                "self": false
                            }
                        ],
                        "egress": [
                            {
                                "from_port": 0,
                                "to_port": 0,
                                "protocol": "-1",
                                "cidr_blocks": ["0.0.0.0/0"],
                                "description": "Allow all outbound traffic",
                                "ipv6_cidr_blocks": [],
                                "prefix_list_ids": [],
                                "security_groups": [],
                                "self": false
                            }
                        ]
                    }),
                );

            let resources = NetworkResources {
                vpc: format!("aws_vpc.{vpc_network}"),
                subnet: format!("aws_subnet.{subnet_key}"),
                security_group: format!("aws_security_group.{sg_key}"),
            };

            // Add outputs so we can retrieve actual AWS IDs after apply
            resource_batch.terraform.output.insert(
                format!("hydro-network-{}-vpc-id", self.id),
                TerraformOutput {
                    value: format!("${{aws_vpc.{vpc_network}.id}}"),
                },
            );
            resource_batch.terraform.output.insert(
                format!("hydro-network-{}-subnet-id", self.id),
                TerraformOutput {
                    value: format!("${{aws_subnet.{subnet_key}.id}}"),
                },
            );
            resource_batch.terraform.output.insert(
                format!("hydro-network-{}-sg-id", self.id),
                TerraformOutput {
                    value: format!("${{aws_security_group.{sg_key}.id}}"),
                },
            );

            let _ = self.existing_network_key.set(NetworkResources {
                vpc: vpc_network,
                subnet: subnet_key,
                security_group: sg_key,
            });
            resources
        }
    }

    pub fn update_from_outputs(&self, resource_result: &ResourceResult) {
        let outputs = &resource_result.terraform.outputs;
        if let (Some(vpc), Some(subnet), Some(sg)) = (
            outputs.get(&format!("hydro-network-{}-vpc-id", self.id)),
            outputs.get(&format!("hydro-network-{}-subnet-id", self.id)),
            outputs.get(&format!("hydro-network-{}-sg-id", self.id)),
        ) {
            let _ = self.existing_network_id.set(NetworkResources {
                vpc: vpc.value.clone(),
                subnet: subnet.value.clone(),
                security_group: sg.value.clone(),
            });
        }
    }
}

/// Represents a IAM role, IAM policy attachments, and instance profile for one or multiple EC2 instances.
#[derive(Debug)]
pub struct AwsEc2IamInstanceProfile {
    pub region: String,
    pub existing_instance_profile_key_or_name: Option<String>,
    pub policy_arns: Vec<String>,
    id: String,
}

impl AwsEc2IamInstanceProfile {
    /// Creates a new instance. If `existing_instance_profile_name` is `Some`, that will be used as the instance
    /// profile name which must already exist in the AWS account.
    pub fn new(region: impl Into<String>, existing_instance_profile_name: Option<String>) -> Self {
        Self {
            region: region.into(),
            existing_instance_profile_key_or_name: existing_instance_profile_name,
            policy_arns: Default::default(),
            id: nanoid!(8, &TERRAFORM_ALPHABET),
        }
    }

    /// Permits the given ARN.
    pub fn add_policy_arn(mut self, policy_arn: impl Into<String>) -> Self {
        if self.existing_instance_profile_key_or_name.is_some() {
            panic!("Adding an ARN to an existing instance profile is not supported.");
        }
        self.policy_arns.push(policy_arn.into());
        self
    }

    /// Enables running and emitting telemetry via the CloudWatch agent.
    pub fn add_cloudwatch_agent_server_policy_arn(self) -> Self {
        self.add_policy_arn("arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy")
    }

    fn collect_resources(&mut self, resource_batch: &mut ResourceBatch) -> String {
        const RESOURCE_AWS_IAM_INSTANCE_PROFILE: &str = "aws_iam_instance_profile";
        const RESOURCE_AWS_IAM_ROLE_POLICY_ATTACHMENT: &str = "aws_iam_role_policy_attachment";
        const RESOURCE_AWS_IAM_ROLE: &str = "aws_iam_role";

        resource_batch
            .terraform
            .terraform
            .required_providers
            .insert(
                "aws".to_owned(),
                TerraformProvider {
                    source: "hashicorp/aws".to_owned(),
                    version: "5.0.0".to_owned(),
                },
            );

        resource_batch.terraform.provider.insert(
            "aws".to_owned(),
            json!({
                "region": self.region
            }),
        );

        let instance_profile_key = format!("hydro-instance-profile-{}", self.id);

        if let Some(existing) = self.existing_instance_profile_key_or_name.as_ref() {
            if resource_batch
                .terraform
                .resource
                .get(RESOURCE_AWS_IAM_INSTANCE_PROFILE)
                .is_some_and(|map| map.contains_key(existing))
            {
                // `existing` is a key.
                format!("{RESOURCE_AWS_IAM_INSTANCE_PROFILE}.{existing}")
            } else {
                // `existing` is a name of an existing resource, supplied when constructed.
                resource_batch
                    .terraform
                    .data
                    .entry(RESOURCE_AWS_IAM_INSTANCE_PROFILE.to_owned())
                    .or_default()
                    .insert(
                        instance_profile_key.clone(),
                        json!({
                            "id": existing,
                        }),
                    );

                format!("data.{RESOURCE_AWS_IAM_INSTANCE_PROFILE}.{instance_profile_key}")
            }
        } else {
            // Create the role (permissions set after).
            let iam_role_key = format!("{instance_profile_key}-iam-role");
            resource_batch
                .terraform
                .resource
                .entry(RESOURCE_AWS_IAM_ROLE.to_owned())
                .or_default()
                .insert(
                    iam_role_key.clone(),
                    json!({
                        "name": format!("hydro-iam-role-{}", self.id),
                        "assume_role_policy": json!({
                            "Version": "2012-10-17",
                            "Statement": [
                                {
                                    "Action": "sts:AssumeRole",
                                    "Effect": "Allow",
                                    "Principal": {
                                        "Service": "ec2.amazonaws.com"
                                    }
                                }
                            ]
                        }).to_string(),
                    }),
                );

            // Attach permissions
            for (i, policy_arn) in self.policy_arns.iter().enumerate() {
                let policy_attachment_key = format!("{iam_role_key}-policy-attachment-{i}");
                resource_batch
                    .terraform
                    .resource
                    .entry(RESOURCE_AWS_IAM_ROLE_POLICY_ATTACHMENT.to_owned())
                    .or_default()
                    .insert(
                        policy_attachment_key,
                        json!({
                            "policy_arn": policy_arn,
                            "role": format!("${{{RESOURCE_AWS_IAM_ROLE}.{iam_role_key}.name}}"),
                        }),
                    );
            }

            // Create instance profile. This is what attaches to EC2 instances.
            resource_batch
                .terraform
                .resource
                .entry(RESOURCE_AWS_IAM_INSTANCE_PROFILE.to_owned())
                .or_default()
                .insert(
                    instance_profile_key.clone(),
                    json!({
                        "name": format!("hydro-instance-profile-{}", self.id),
                        "role": format!("${{{RESOURCE_AWS_IAM_ROLE}.{iam_role_key}.name}}"),
                    }),
                );

            // Set key
            self.existing_instance_profile_key_or_name = Some(instance_profile_key.clone());

            format!("{RESOURCE_AWS_IAM_INSTANCE_PROFILE}.{instance_profile_key}")
        }
    }
}

/// Represents a CloudWatch log group.
#[derive(Debug)]
pub struct AwsCloudwatchLogGroup {
    pub region: String,
    pub existing_cloudwatch_log_group_key_or_name: Option<String>,
    id: String,
}

impl AwsCloudwatchLogGroup {
    /// Creates a new instance. If `existing_cloudwatch_log_group_name` is `Some`, that will be used as the CloudWatch
    /// log group name which must already exist in the AWS account and region.
    pub fn new(
        region: impl Into<String>,
        existing_cloudwatch_log_group_name: Option<String>,
    ) -> Self {
        Self {
            region: region.into(),
            existing_cloudwatch_log_group_key_or_name: existing_cloudwatch_log_group_name,
            id: nanoid!(8, &TERRAFORM_ALPHABET),
        }
    }

    fn collect_resources(&mut self, resource_batch: &mut ResourceBatch) -> String {
        const RESOURCE_AWS_CLOUDWATCH_LOG_GROUP: &str = "aws_cloudwatch_log_group";

        resource_batch
            .terraform
            .terraform
            .required_providers
            .insert(
                "aws".to_owned(),
                TerraformProvider {
                    source: "hashicorp/aws".to_owned(),
                    version: "5.0.0".to_owned(),
                },
            );

        resource_batch.terraform.provider.insert(
            "aws".to_owned(),
            json!({
                "region": self.region
            }),
        );

        let cloudwatch_log_group_key = format!("hydro-cloudwatch-log-group-{}", self.id);

        if let Some(existing) = self.existing_cloudwatch_log_group_key_or_name.as_ref() {
            if resource_batch
                .terraform
                .resource
                .get(RESOURCE_AWS_CLOUDWATCH_LOG_GROUP)
                .is_some_and(|map| map.contains_key(existing))
            {
                // `existing` is a key.
                format!("{RESOURCE_AWS_CLOUDWATCH_LOG_GROUP}.{existing}")
            } else {
                // `existing` is a name of an existing resource, supplied when constructed.
                resource_batch
                    .terraform
                    .data
                    .entry(RESOURCE_AWS_CLOUDWATCH_LOG_GROUP.to_owned())
                    .or_default()
                    .insert(
                        cloudwatch_log_group_key.clone(),
                        json!({
                            "id": existing,
                        }),
                    );

                format!("data.{RESOURCE_AWS_CLOUDWATCH_LOG_GROUP}.{cloudwatch_log_group_key}")
            }
        } else {
            // Create the log group.
            resource_batch
                .terraform
                .resource
                .entry(RESOURCE_AWS_CLOUDWATCH_LOG_GROUP.to_owned())
                .or_default()
                .insert(
                    cloudwatch_log_group_key.clone(),
                    json!({
                        "name": format!("hydro-cloudwatch-log-group-{}", self.id),
                        "retention_in_days": 1,
                    }),
                );

            // Set key
            self.existing_cloudwatch_log_group_key_or_name = Some(cloudwatch_log_group_key.clone());

            format!("{RESOURCE_AWS_CLOUDWATCH_LOG_GROUP}.{cloudwatch_log_group_key}")
        }
    }
}

pub struct AwsEc2Host {
    /// ID from [`crate::Deployment::add_host`].
    id: usize,

    region: String,
    instance_type: String,
    target_type: HostTargetType,
    ami: String,
    network: Arc<AwsNetwork>,
    iam_instance_profile: Option<Arc<Mutex<AwsEc2IamInstanceProfile>>>,
    cloudwatch_log_group: Option<Arc<Mutex<AwsCloudwatchLogGroup>>>,
    cwa_metrics_collected: Option<serde_json::Value>,
    user: Option<String>,
    display_name: Option<String>,
    pub launched: OnceLock<Arc<LaunchedEc2Instance>>,
    external_ports: Mutex<Vec<u16>>,
}

impl Debug for AwsEc2Host {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "AwsEc2Host({} ({:?}))",
            self.id, &self.display_name
        ))
    }
}

impl AwsEc2Host {
    #[expect(clippy::too_many_arguments, reason = "used via builder pattern")]
    pub fn new(
        id: usize,
        region: impl Into<String>,
        instance_type: impl Into<String>,
        target_type: HostTargetType,
        ami: impl Into<String>,
        network: Arc<AwsNetwork>,
        iam_instance_profile: Option<Arc<Mutex<AwsEc2IamInstanceProfile>>>,
        cloudwatch_log_group: Option<Arc<Mutex<AwsCloudwatchLogGroup>>>,
        cwa_metrics_collected: Option<serde_json::Value>,
        user: Option<String>,
        display_name: Option<String>,
    ) -> Self {
        Self {
            id,
            region: region.into(),
            instance_type: instance_type.into(),
            target_type,
            ami: ami.into(),
            network,
            iam_instance_profile,
            cloudwatch_log_group,
            cwa_metrics_collected,
            user,
            display_name,
            launched: OnceLock::new(),
            external_ports: Mutex::new(Vec::new()),
        }
    }
}

impl Host for AwsEc2Host {
    fn target_type(&self) -> HostTargetType {
        self.target_type
    }

    fn request_port_base(&self, bind_type: &BaseServerStrategy) {
        match bind_type {
            BaseServerStrategy::UnixSocket => {}
            BaseServerStrategy::InternalTcpPort(_) => {}
            BaseServerStrategy::ExternalTcpPort(port) => {
                let mut external_ports = self.external_ports.lock().unwrap();
                if !external_ports.contains(port) {
                    if self.launched.get().is_some() {
                        todo!("Cannot adjust security group after host has been launched");
                    }
                    external_ports.push(*port);
                }
            }
        }
    }

    fn request_custom_binary(&self) {
        self.request_port_base(&BaseServerStrategy::ExternalTcpPort(22));
    }

    fn id(&self) -> usize {
        self.id
    }

    fn collect_resources(&self, resource_batch: &mut ResourceBatch) {
        if self.launched.get().is_some() {
            return;
        }

        let network_resources = self.network.collect_resources(resource_batch);

        let iam_instance_profile = self
            .iam_instance_profile
            .as_deref()
            .map(|irip| irip.lock().unwrap().collect_resources(resource_batch));

        let cloudwatch_log_group = self
            .cloudwatch_log_group
            .as_deref()
            .map(|cwlg| cwlg.lock().unwrap().collect_resources(resource_batch));

        // Add additional providers
        resource_batch
            .terraform
            .terraform
            .required_providers
            .insert(
                "local".to_owned(),
                TerraformProvider {
                    source: "hashicorp/local".to_owned(),
                    version: "2.3.0".to_owned(),
                },
            );

        resource_batch
            .terraform
            .terraform
            .required_providers
            .insert(
                "tls".to_owned(),
                TerraformProvider {
                    source: "hashicorp/tls".to_owned(),
                    version: "4.0.4".to_owned(),
                },
            );

        // Generate SSH key pair
        resource_batch
            .terraform
            .resource
            .entry("tls_private_key".to_owned())
            .or_default()
            .insert(
                "vm_instance_ssh_key".to_owned(),
                json!({
                    "algorithm": "RSA",
                    "rsa_bits": 4096
                }),
            );

        resource_batch
            .terraform
            .resource
            .entry("local_file".to_owned())
            .or_default()
            .insert(
                "vm_instance_ssh_key_pem".to_owned(),
                json!({
                    "content": "${tls_private_key.vm_instance_ssh_key.private_key_pem}",
                    "filename": ".ssh/vm_instance_ssh_key_pem",
                    "file_permission": "0600",
                    "directory_permission": "0700"
                }),
            );

        resource_batch
            .terraform
            .resource
            .entry("aws_key_pair".to_owned())
            .or_default()
            .insert(
                "ec2_key_pair".to_owned(),
                json!({
                    "key_name": format!("hydro-key-{}", nanoid!(8, &TERRAFORM_ALPHABET)),
                    "public_key": "${tls_private_key.vm_instance_ssh_key.public_key_openssh}"
                }),
            );

        let instance_key = format!("ec2-instance-{}", self.id);
        let mut instance_name = format!("hydro-ec2-instance-{}", nanoid!(8, &TERRAFORM_ALPHABET));

        if let Some(mut display_name) = self.display_name.clone() {
            instance_name.push('-');
            display_name = display_name.replace("_", "-").to_lowercase();

            let num_chars_to_cut = instance_name.len() + display_name.len() - 63;
            if num_chars_to_cut > 0 {
                display_name.drain(0..num_chars_to_cut);
            }
            instance_name.push_str(&display_name);
        }

        let vpc_ref = format!("${{{}.id}}", network_resources.vpc);
        let default_sg_ref = format!("${{{}.id}}", network_resources.security_group);

        // Create additional security group for external ports if needed
        let mut security_groups = vec![default_sg_ref];
        let external_ports = self.external_ports.lock().unwrap();

        if !external_ports.is_empty() {
            let sg_key = format!("sg-{}", self.id);
            let mut sg_rules = vec![];

            for port in external_ports.iter() {
                sg_rules.push(json!({
                    "from_port": port,
                    "to_port": port,
                    "protocol": "tcp",
                    "cidr_blocks": ["0.0.0.0/0"],
                    "description": format!("External port {}", port),
                    "ipv6_cidr_blocks": [],
                    "prefix_list_ids": [],
                    "security_groups": [],
                    "self": false
                }));
            }

            resource_batch
                .terraform
                .resource
                .entry("aws_security_group".to_owned())
                .or_default()
                .insert(
                    sg_key.clone(),
                    json!({
                        "name": format!("hydro-sg-{}", nanoid!(8, &TERRAFORM_ALPHABET)),
                        "description": "Hydro external ports security group",
                        "vpc_id": vpc_ref,
                        "ingress": sg_rules,
                        "egress": [{
                            "from_port": 0,
                            "to_port": 0,
                            "protocol": "-1",
                            "cidr_blocks": ["0.0.0.0/0"],
                            "description": "All outbound traffic",
                            "ipv6_cidr_blocks": [],
                            "prefix_list_ids": [],
                            "security_groups": [],
                            "self": false
                        }]
                    }),
                );

            security_groups.push(format!("${{aws_security_group.{}.id}}", sg_key));
        }
        drop(external_ports);

        let subnet_ref = format!("${{{}.id}}", network_resources.subnet);
        let iam_instance_profile_ref = iam_instance_profile.map(|key| format!("${{{key}.name}}"));

        // Write the CloudWatch Agent config file.
        // https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html
        let cloudwatch_agent_config = cloudwatch_log_group.map(|cwlg| {
            json!({
                "logs": {
                    "logs_collected": {
                        "files": {
                            "collect_list": [
                                {
                                    "file_path": "/var/log/hydro/metrics.log",
                                    "log_group_name": format!("${{{cwlg}.name}}"), // This `$` is interpreted by terraform
                                    "log_stream_name": "{{instance_id}}"
                                }
                            ]
                        }
                    }
                },
                "metrics": {
                    // "namespace": todo!(), // TODO(mingwei): use flow_name here somehow
                    "metrics_collected": self.cwa_metrics_collected.as_ref().unwrap_or(&json!({
                        "cpu": {
                            "resources": [
                                "*"
                            ],
                            "measurement": [
                                "usage_active"
                            ],
                            "totalcpu": true
                        },
                        "mem": {
                            "measurement": [
                                "used_percent"
                            ]
                        }
                    })),
                    // See special escape handling below.
                    "append_dimensions": {
                        "InstanceId": "${aws:InstanceId}"
                    }
                }
            })
            .to_string()
        });

        // TODO(mingwei): Run this in SSH instead of `user_data` to avoid racing and capture errors.
        let user_data_script = cloudwatch_agent_config.map(|cwa_config| {
            let cwa_config_esc = cwa_config
                .replace("\\", r"\\") // escape backslashes
                .replace("\"", r#"\""#) // escape quotes
                .replace("\n", r"\n") // escape newlines
                // Special handling of AWS `append_dimensions` fields:
                // `$$` to escape for terraform, becomes `\$` in bash, becomes `$` in echo output.
                .replace("${aws:", r"\$${aws:");
            format!(
                r##"
#!/bin/bash
set -euxo pipefail

mkdir -p /var/log/hydro/
chmod +777 /var/log/hydro
touch /var/log/hydro/metrics.log
chmod +666 /var/log/hydro/metrics.log

# Install the CloudWatch Agent
yum install -y amazon-cloudwatch-agent

mkdir -p /opt/aws/amazon-cloudwatch-agent/etc
echo -e "{cwa_config_esc}" > /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json

# Start or restart the agent
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
    -a fetch-config -m ec2 \
    -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json \
    -s
"##
            )
        });

        // Create EC2 instance
        resource_batch
            .terraform
            .resource
            .entry("aws_instance".to_owned())
            .or_default()
            .insert(
                instance_key.clone(),
                json!({
                    "ami": self.ami,
                    "instance_type": self.instance_type,
                    "key_name": "${aws_key_pair.ec2_key_pair.key_name}",
                    "vpc_security_group_ids": security_groups,
                    "subnet_id": subnet_ref,
                    "associate_public_ip_address": true,
                    "iam_instance_profile": iam_instance_profile_ref, // May be `None`.
                    "user_data": user_data_script, // May be `None`.
                    "tags": {
                        "Name": instance_name
                    }
                }),
            );

        resource_batch.terraform.output.insert(
            format!("{}-private-ip", instance_key),
            TerraformOutput {
                value: format!("${{aws_instance.{}.private_ip}}", instance_key),
            },
        );

        resource_batch.terraform.output.insert(
            format!("{}-public-ip", instance_key),
            TerraformOutput {
                value: format!("${{aws_instance.{}.public_ip}}", instance_key),
            },
        );
    }

    fn launched(&self) -> Option<Arc<dyn LaunchedHost>> {
        self.launched
            .get()
            .map(|a| a.clone() as Arc<dyn LaunchedHost>)
    }

    fn provision(&self, resource_result: &Arc<ResourceResult>) -> Arc<dyn LaunchedHost> {
        self.launched
            .get_or_init(|| {
                let id = self.id;

                self.network.update_from_outputs(resource_result);
                let internal_ip = resource_result
                    .terraform
                    .outputs
                    .get(&format!("ec2-instance-{id}-private-ip"))
                    .unwrap()
                    .value
                    .clone();

                let external_ip = resource_result
                    .terraform
                    .outputs
                    .get(&format!("ec2-instance-{id}-public-ip"))
                    .map(|v| v.value.clone());

                Arc::new(LaunchedEc2Instance {
                    resource_result: resource_result.clone(),
                    user: self.user.clone().unwrap_or_else(|| "ec2-user".to_owned()),
                    internal_ip,
                    external_ip,
                })
            })
            .clone()
    }

    fn strategy_as_server<'a>(
        &'a self,
        client_host: &dyn Host,
        network_hint: PortNetworkHint,
    ) -> Result<(ClientStrategy<'a>, HostStrategyGetter)> {
        if matches!(network_hint, PortNetworkHint::Auto)
            && client_host.can_connect_to(ClientStrategy::UnixSocket(self.id))
        {
            Ok((
                ClientStrategy::UnixSocket(self.id),
                Box::new(|_| BaseServerStrategy::UnixSocket),
            ))
        } else if matches!(
            network_hint,
            PortNetworkHint::Auto | PortNetworkHint::TcpPort(_)
        ) && client_host.can_connect_to(ClientStrategy::InternalTcpPort(self))
        {
            Ok((
                ClientStrategy::InternalTcpPort(self),
                Box::new(move |_| {
                    BaseServerStrategy::InternalTcpPort(match network_hint {
                        PortNetworkHint::Auto => None,
                        PortNetworkHint::TcpPort(port) => port,
                    })
                }),
            ))
        } else if matches!(network_hint, PortNetworkHint::Auto)
            && client_host.can_connect_to(ClientStrategy::ForwardedTcpPort(self))
        {
            Ok((
                ClientStrategy::ForwardedTcpPort(self),
                Box::new(|me| {
                    me.downcast_ref::<AwsEc2Host>()
                        .unwrap()
                        .request_port_base(&BaseServerStrategy::ExternalTcpPort(22));
                    BaseServerStrategy::InternalTcpPort(None)
                }),
            ))
        } else {
            anyhow::bail!("Could not find a strategy to connect to AWS EC2 instance")
        }
    }

    fn can_connect_to(&self, typ: ClientStrategy) -> bool {
        match typ {
            ClientStrategy::UnixSocket(id) => {
                #[cfg(unix)]
                {
                    self.id == id
                }

                #[cfg(not(unix))]
                {
                    let _ = id;
                    false
                }
            }
            ClientStrategy::InternalTcpPort(target_host) => {
                if let Some(aws_target) = <dyn Any>::downcast_ref::<AwsEc2Host>(target_host) {
                    self.region == aws_target.region
                        && Arc::ptr_eq(&self.network, &aws_target.network)
                } else {
                    false
                }
            }
            ClientStrategy::ForwardedTcpPort(_) => false,
        }
    }
}