Multi-Cloud and Hybrid Cloud Architecture Questions
Designing systems that span multiple cloud providers or bridge cloud and on-premises. Covers cloud-agnostic abstraction, workload placement across providers or environments, cross-cloud networking and identity federation, data gravity, infrastructure-as-code and centralized observability that span providers, and the operational cost of avoiding vendor lock-in versus the risk of accepting it. Also covers keeping a system correct once it spans providers: leader election, distributed transactions, rate limiting, and service discovery across cloud or cluster boundaries. Resilience patterns here are scoped to crossing a provider or on-prem/cloud boundary (for example failover from one provider to another, or from on-prem to cloud). Resilience across regions of a single provider, with no second provider or on-prem leg involved, is a different topic (multi-region architecture) and is out of scope here.
You're designing BGP for a global enterprise that will advertise thousands of prefixes across multiple clouds and edge sites. Explain strategies to scale BGP (route reflectors, RIB/FIB separation, confederations), manage full-table vs partial routing, and how you'd incorporate RPKI/ROA for route origin validation and filtering in your architecture.
Sample Answer
Direct answer
Scale BGP (Border Gateway Protocol) the way large networks always have: reduce the number of full-mesh iBGP (internal BGP) sessions with route reflectors or confederations instead of meshing every router with every other one, keep the control-plane RIB (Routing Information Base) and the forwarding-plane FIB (Forwarding Information Base) conceptually, and often physically, separate so route churn does not directly stall packet forwarding, take partial routes plus a default route at most edge sites rather than a full internet table unless a site genuinely needs to make its own best-path decision toward every destination, and add RPKI (Resource Public Key Infrastructure) with ROAs (Route Origin Authorizations) so route origin validation catches accidental or malicious prefix hijacks before they get accepted.
Structured elaboration
Route reflectors
Without them, iBGP requires a full mesh: every router peers with every other router in the same AS (Autonomous System), which is
O(n2)sessions for n routers. A route reflector lets client routers peer only with the reflector, or a small number of them for redundancy, and the reflector re-advertises routes between clients, cutting session count to roughly
O(n)The trade-off is a single new failure point per reflector, which is why production designs run at least two reflectors per cluster.
Confederations
An alternative to route reflectors: split one large AS into several smaller sub-ASes, each internally full-meshed, now a much smaller mesh, or reflector-based, connected to each other over eBGP (external BGP)-like sessions inside the confederation. This trades route-reflector operational simplicity for AS-path visibility inside the confederation, useful when different sub-ASes are operated somewhat independently, different regions, different acquired companies' networks, but need to look like one AS to the outside world.
RIB/FIB separation
The RIB is where BGP's best-path algorithm runs, potentially processing thousands of route changes during a churny event; the FIB is the compiled, hardware-forwarding table actually used to switch packets. Keeping them separate, true on essentially all modern routing platforms, means a burst of BGP churn does not have to stall packet forwarding: the FIB keeps forwarding on its last-computed state while the RIB recomputes, and only a converged, stable result gets pushed down to the FIB.
Full table versus partial routing
A full internet BGP table is roughly 900,000 to 1,000,000-plus IPv4 routes as of the mid-2020s and growing, real memory and CPU cost on every router that carries it. Most edge sites do not need it: a partial table, routes from directly connected providers and customers, plus a default route toward a transit provider covers the vast majority of traffic correctly, since most destinations are reached just as well via the default as via a specific route learned from a full table. Reserve full tables for routers that genuinely need to choose the best of several transit providers per destination, typically only at true internet-edge or transit-provider routers, not at every branch or every cloud interconnect point.
RPKI and ROAs for origin validation
RPKI lets a prefix's legitimate owner cryptographically sign a ROA stating that a specific AS is authorized to originate that prefix. A router doing Route Origin Validation checks every received route against the ROA set and marks it valid, invalid, or unknown, no ROA exists, and policy typically rejects or heavily deprioritizes anything marked invalid. This directly defends against the accidental or malicious prefix hijack, someone else's AS originating a prefix that is not theirs, whether by a fat-fingered redistribution or an attack, a failure mode that route reflectors, confederations, and RIB/FIB separation do nothing to prevent, since all three are scaling mechanisms, not security mechanisms.
Worked example: session count with and without a route reflector
O(n2) full meshvs.O(n) with route reflectorsFor 20 iBGP routers in one AS, a full mesh needs
220×19=190sessions total across the network. With 2 route reflectors serving all 20 as clients, that drops to
20×2=40client sessions, each client peers with both reflectors for redundancy, plus 1 reflector-to-reflector session, 41 total, roughly a 4 to 5 times reduction at just 20 routers, with the gap widening quadratically as router count grows further.
Trade-offs and pitfalls
Route reflectors and confederations solve a scaling problem, not a trust problem: a network that deploys both perfectly and skips RPKI entirely is still fully exposed to a route hijack, its own or another network's misconfiguration announcing a prefix that does not belong to it, because none of the scaling mechanisms above touch route origin at all. The inverse mistake is also real: RPKI and ROAs validate that the originating AS is authorized, they say nothing about the AS path in between being legitimate, that is what BGPsec, a separate and far less deployed mechanism, is for, so RPKI meaningfully reduces but does not eliminate route-hijack risk. Finally, the decision between full and partial tables should be revisited whenever the network's edge topology changes, adding a second transit provider at a site that previously had only one, for instance, since a site that used to be correctly served by a default route can develop a genuine need to see the full table once it has more than one path to choose between.
Design a secure multi-cloud connectivity pattern using cloud transit hubs such as AWS Transit Gateway, Azure Virtual WAN, or GCP Network Connectivity Center. Show how you would connect multiple VPCs/VNets, on-premises sites, and enforce central security and routing policies while minimizing transitive exposure between tenants.
Sample Answer
Direct answer
Give each cloud its own native transit hub (AWS Transit Gateway, Azure Virtual WAN, GCP Network Connectivity Center), attach that cloud's own VPCs (Virtual Private Clouds, AWS/GCP's term for an isolated private network) and VNets (Virtual Networks, Azure's equivalent term) and on-prem connections to it, put policy enforcement (firewalling, route filtering) at the hub instead of scattering it across spokes, and connect the hubs to each other and to on-prem through the fewest possible dedicated paths, favoring a colocation or cloud-exchange facility over provisioning separate long-haul circuits between three different providers' interconnect locations.
Structured elaboration
Per-cloud hub, then hub-to-hub
Each provider's native transit service is a managed route-and-policy engine, not just a bigger router: AWS Transit Gateway is regional (peer two Transit Gateways across regions if needed), Azure Virtual WAN meshes multiple regional hubs globally by default, and GCP Network Connectivity Center attaches four kinds of spokes, VPC, producer-VPC, NCC Gateway for third-party inspection, and hybrid spokes for VPN tunnels, Cloud Interconnect attachments, or router-appliance VMs, to a single global hub resource. None of the three natively speaks to either of the other two, so cross-cloud reachability is always a separate link built and secured independently.
Centralized firewalling and BGP failure-domain planning
Put an inline firewall (AWS Network Firewall, Azure Firewall, or a comparable NVA, a Network Virtual Appliance, a third-party firewall or router running as a VM instead of a dedicated physical box) at each hub so every inter-VPC and internet-bound flow passes through one enforcement point, and treat each hub as a single BGP (Border Gateway Protocol) failure domain: a route leak or a flapping session injected at the hub can affect every attached spoke at once. Contain that blast radius with route summarization at the hub, a maximum-prefix limit on every BGP session so a misbehaving spoke cannot overwhelm the hub's route table, and separate route tables per trust tier, an internet-facing route table and an internal-only one on the same Transit Gateway, for example, so being attached to the hub does not automatically mean being reachable from every other spoke.
Multi-tenant segmentation
Even inside one cloud's hub, use per-tenant or per-environment route table associations and propagations (Transit Gateway route tables, Virtual WAN route tables and labels, or NCC's per-spoke routing) rather than one flat table, on the principle that a spoke should see only the routes it was explicitly given, not everything the hub happens to know.
Cross-cloud interconnection, worked as a real three-cloud example
Connecting AWS, GCP, and Azure to each other and to on-prem comes down to three real options.
| Approach | What it is | Cost and lead time | Best for |
|---|---|---|---|
| Direct cloud-to-cloud VPN | IPsec (IP Security, a protocol suite that encrypts and authenticates traffic between two endpoints) tunnels between each provider's own VPN gateway, over the public internet | Low cost, provision in hours | Low or medium volume, tolerant of variable latency, quick to stand up |
| Dedicated interconnects | AWS Direct Connect, Azure ExpressRoute, GCP Dedicated or Partner Interconnect, each terminating at a physical location | Higher fixed cost, weeks of lead time for a physical cross-connect | Predictable bandwidth and an SLA (Service-Level Agreement), sustained high-volume traffic |
| Colocation or cloud-exchange fabric | Rack space and one port into a facility, such as an Equinix or Megaport exchange, that already has cross-connects into all three clouds' interconnect locations, then virtual circuits from that one port to each cloud | One procurement instead of three separate long-haul circuits, still weeks of lead time and its own recurring cost | Genuinely multi-cloud designs, avoids building and maintaining three pairwise physical links |
The colocation/exchange pattern is the practical answer to connecting three clouds without three separate physical circuits: one relationship, rack space plus cross-connects, replaces coordinating bilateral circuits between every pair of providers, at the cost of depending on that facility as a new single point of failure unless at least two independent facilities or paths are provisioned for anything production-critical. Encrypted, near-real-time data replication between two facilities, keeping a standby database within seconds of its primary, is a concrete workload that justifies paying for a dedicated interconnect or exchange-fabric circuit over a plain internet VPN: replication lag is latency-sensitive and cannot tolerate the variable path and jitter of the public internet, and the circuit still needs its own encryption, IPsec or MACsec (Media Access Control Security), layered on top, since a private circuit is not inherently encrypted.
Cross-cloud service discovery and latency
None of the three clouds resolves another cloud's private DNS zones by default; reuse the split-horizon, conditional-forwarding pattern from hybrid DNS design, per cloud pair, or run a DNS layer that spans all three. Latency across a cross-cloud hop is dominated by physical distance and the extra encryption and decryption step of a VPN, not by anything inside either cloud's network, and it compounds: an application making several sequential cross-cloud calls per request pays that penalty once per call, usually the real reason a read-from-one-cloud, write-to-another pattern feels slow in practice. Validate the actual number with synthetic cross-cloud probes before committing an application to a chatty cross-cloud call pattern; do not guess it.
A 3-datacenter, single-cloud worked example
Three on-prem data centers connecting to one cloud region is the simplest concrete instance of this pattern: each data center gets its own dedicated circuit (Direct Connect or ExpressRoute) into that region's transit hub, giving hub-and-spoke with 3 circuits total, and data-center-to-data-center traffic also transits the hub rather than requiring 3 separate DC-to-DC circuits, which at just 3 sites saves nothing numerically over a full mesh but establishes the pattern that keeps paying off as more data centers are added.
An AWS-Azure worked example, with colocation and TLS backhaul
For a two-cloud AWS-to-Azure design specifically, a cloud-exchange partner provisions a virtual cross-connect between an AWS Direct Connect port and an Azure ExpressRoute circuit at the same exchange fabric, so no physical cable is laid between the two providers' interconnect locations directly. Where an application needs to terminate TLS (Transport Layer Security) at an inspection point in one cloud before continuing to the other, a common requirement when compliance mandates inspection before traffic leaves a controlled zone, budget explicitly for that extra hop's added latency and for certificate and SNI (Server Name Indication) handling at the intermediate termination point, since it is easy to design the network path and forget that TLS backhaul changes where a certificate has to live. Weigh this direct-peering approach against an SD-WAN (Software-Defined Wide Area Network) overlay across the same underlying links: ExpressRoute and Direct Connect give a private circuit with a bandwidth SLA but a static path per circuit, while an SD-WAN overlay adds per-application path steering and its own encryption and vendor control plane on top, the right trade when dynamic path selection matters more than a guaranteed static circuit.
The richest pattern: SD-WAN layered on native interconnects
Mature multi-cloud designs typically do not choose one or the other: they deploy an SD-WAN edge at each site, on-prem data centers and, increasingly, a virtual SD-WAN appliance inside each cloud's VPC/VNet, that treats the dedicated interconnects as its highest-priority underlay path and internet-based VPN as automatic backup, while the native transit hub in each cloud continues to handle cloud-to-cloud and cloud-to-VPC transit underneath it. This combined design adds multi-tenant segmentation at the SD-WAN layer, separate overlay segments per business unit or environment, independent of how the underlying cloud route tables are segmented, and a single operational pane: edge policy changes push out from one central SD-WAN orchestrator, and its telemetry rolls into the same monitoring plane as the hub's flow logs, instead of two disconnected management systems.
graph LR
DC1[On-prem DC 1] -->|Direct Connect| AWSHUB[AWS Transit Gateway]
DC2[On-prem DC 2] -->|Direct Connect| AWSHUB
DC3[On-prem DC 3] -->|Direct Connect| AWSHUB
AWSHUB --> VPCA[Spoke VPC A]
AWSHUB --> VPCB[Spoke VPC B]
AWSHUB <-->|Cloud exchange fabric| AZUREHUB[Azure Virtual WAN Hub]
AWSHUB <-->|Cloud exchange fabric| GCPHUB[GCP Network Connectivity Center]
AZUREHUB --> VNETA[Spoke VNet A]
GCPHUB --> VPCG[Spoke VPC]
Trade-offs and pitfalls
Centralizing everything into one hub per cloud is a genuine strength for reasoning about the design and a genuine risk for both blast radius and throughput: know the hub's actual bandwidth ceiling (a Transit Gateway VPC attachment, for example, is documented at up to 100 Gbps in each direction per Availability Zone) and plan capacity against it rather than assuming the hub scales invisibly. The most common security mistake is under-segmenting: being attached to the hub quietly means being reachable from every other attached spoke unless route table associations and propagations are explicitly scoped, so audit that mapping as carefully as a firewall rule set. Finally, do not let the exchange fabric or a single colocation facility become an unacknowledged single point of failure just because it elegantly solved the three-circuits-into-one procurement problem; anything production-critical needs at least two independent physical paths, whichever pattern above was chosen to get there.
Describe redundancy and failover patterns for dedicated cloud interconnects (for example active/active Direct Connect or ExpressRoute, link aggregation groups, dual-provider setups). Explain how you would configure routing (BGP attributes, local-pref, MED, BFD) to ensure fast failover and avoid traffic blackholing during a link event.
Sample Answer
Direct answer
Run two independent physical circuits, ideally from two different providers or at least two different physical paths, active/active, with BGP (Border Gateway Protocol) preferring one path via local-preference under normal conditions, paired with BFD (Bidirectional Forwarding Detection) so a link failure is detected in well under a second instead of waiting for BGP's own, much slower, default timers to notice.
Structured elaboration
Link Aggregation Groups
Where the provider supports it, bond multiple physical connections, for example, two 10 Gbps Direct Connect or ExpressRoute ports, into one LAG (Link Aggregation Group) so a single port or fiber failure does not drop the whole circuit, just its share of bandwidth, and BGP does not even need to react because the LAG absorbed the failure below the routing layer.
Active/active with BGP attributes
- Local-preference: a locally significant attribute deciding which of several outbound paths a network prefers; set it higher on the primary Direct Connect or ExpressRoute path so, under normal conditions, all outbound traffic prefers that path over the backup.
- MED (Multi-Exit Discriminator): tells a neighboring AS (Autonomous System, a routing domain with its own BGP identity) which of several entry points it should prefer for inbound traffic, but it only compares meaningfully between routes learned from the same neighboring AS, a detail that trips people up when they expect it to work like local-preference in reverse.
- BFD: a lightweight, sub-second failure-detection protocol running underneath BGP that tells it immediately when a path is actually dead, instead of relying on BGP's own keepalive and hold timers, commonly 60 seconds and 180 seconds by default on many implementations, which would otherwise leave traffic being sent into a dead path for tens of seconds after it failed.
Dual-provider setups
Using two different interconnect providers, not just two circuits from the same provider, protects against a provider-wide event, a fiber cut affecting all of one provider's capacity in a region, a billing or provisioning error, that two circuits from the same provider would not protect against.
Worked example
| Primary (Direct Connect, provider A) | Backup (a comparable path, provider B) | |
|---|---|---|
| Local-preference | 200 | 100 |
| Effect | Preferred for all outbound traffic under normal conditions | Used only when the primary's local-preference-200 routes are withdrawn |
| BFD interval | Sub-second detection configured | Same |
| With local-preference set to 200 on the primary and 100 on the backup, every router in the local AS prefers the primary path for anything reachable both ways. If BFD detects the primary link is down, it immediately tells BGP to withdraw the local-preference-200 routes, and traffic shifts to the local-preference-100 backup path within the BFD detection interval, typically well under a second, rather than waiting out BGP's default hold timer. |
Trade-offs and pitfalls
The classic blackholing pitfall is a mismatch between the two circuits' configurations: if the backup path is not actually configured to accept and advertise the same prefixes as the primary, a primary failure does not fail over cleanly, it fails silently, because BGP has nothing valid to switch to even though the physical backup link is up. The MED nuance is a real, common mistake: because MED is only compared between routes from the same neighboring AS, using it to influence path preference from two entirely different upstream providers does nothing, local-preference or a different mechanism is needed there instead. Test the failover, not just the configuration: the only way to know a backup path actually works under BGP is to fail the primary over in a maintenance window and watch it happen, not to trust that the configuration looks symmetric on paper.
Describe overlay vs underlay networking (VXLAN/GRE/EVPN overlays vs physical L3 underlay) and explain when using an overlay across cloud and on-premise infrastructure is appropriate. Include considerations for MTU, encapsulation overhead, route distribution, and troubleshooting implications.
Sample Answer
Direct answer
The underlay is the physical network that actually forwards packets: routers, switches, cables, and in the cloud, the virtual network fabric behind your VPC (Virtual Private Cloud) or VNet (Azure's Virtual Network). It only needs to route between physical endpoints using plain IP. The overlay is a virtual network built on top of that underlay by wrapping (encapsulating) real traffic inside another packet, so workloads get their own addressing and, in some designs, their own Layer 2 (Ethernet) domain, independent of how the underlay is actually wired. VXLAN (Virtual Extensible LAN), GRE (Generic Routing Encapsulation), and EVPN (Ethernet VPN, a BGP-based control plane usually paired with VXLAN) are the three ways to build that overlay. Use an overlay across cloud and on-prem when you need address space or Layer 2 adjacency that has to survive being physically relocated (workload migration, stretched clusters), or true multi-tenant isolation without burning a real VLAN or subnet per tenant. Skip it when plain Layer 3 routing between on-prem and cloud already satisfies the requirement: the overlay is complexity you should have to justify, not a default.
Underlay and overlay, side by side
| Underlay | Overlay | |
|---|---|---|
| What it is | Physical/virtual L3 fabric: routers, cabling, the cloud provider's own network | A virtual network encapsulated inside underlay packets |
| Addressing | Real, routable, tied to physical topology | Independent of the underlay, can move or overlap between tenants |
| Reachability | IGP (Interior Gateway Protocol) or BGP (Border Gateway Protocol) between real devices | VXLAN/GRE tunnels between VTEPs (VXLAN Tunnel Endpoints), with EVPN as the control plane that tells each VTEP which MAC/IP lives where |
| Multi-tenancy | Needs a VLAN or subnet per tenant (VLANs cap out at 4094) | VXLAN carries a 24-bit VNI (VXLAN Network Identifier), over 16 million segments |
VXLAN encapsulates the original Ethernet frame inside UDP/IP (RFC 7348: outer Ethernet, outer IP, outer UDP on destination port 4789, then an 8-byte VXLAN header). GRE just wraps IP-in-IP with a 4-byte minimum header (IP protocol 47) and, unlike VXLAN, was not designed with a multi-tenant segment ID in mind. NVGRE (Network Virtualization using Generic Routing Encapsulation, a Microsoft-originated variant standardized in RFC 7637) bolts one on: it reuses the GRE header's 32-bit key field to carry a 24-bit Virtual Subnet Identifier, giving GRE-based tunnels the same per-tenant segmentation VXLAN gets from its VNI, at a slightly smaller total encapsulation overhead than VXLAN. EVPN is not an encapsulation at all: it is a BGP address family (MP-BGP, Multiprotocol BGP) that VTEPs use to advertise which MAC or IP lives behind them, replacing flood-and-learn with a real control plane: faster convergence, ARP suppression, and predictable behavior when a VTEP restarts.
Worked example: why MTU breaks first
1500 B+50 B=1550 BA standard Ethernet MTU (Maximum Transmission Unit, the biggest packet a link will carry) is 1500 bytes. VXLAN's encapsulation overhead is 50 bytes (14-byte outer Ethernet header, 20-byte outer IP header, 8-byte outer UDP header, 8-byte VXLAN header, per RFC 7348), so a 1500-byte tenant frame becomes a 1550-byte packet on the wire. If the underlay path between the on-prem site and the cloud is itself capped at 1500 bytes (true of most internet-routed and many VPN paths), that 1550-byte packet either fragments or, more commonly, gets silently dropped, because VXLAN packets are typically sent with the do-not-fragment bit set and a lot of networks filter the ICMP packet-too-big message that is supposed to trigger Path MTU Discovery. The practical fix is one of two things: raise the underlay MTU to at least 1550 (cloud providers that support jumbo frames on private/dedicated links, such as AWS Direct Connect or Azure ExpressRoute paths, comfortably clear this), or lower the tenant-facing MTU to 1450 and let path MTU discovery, or a manually clamped TCP MSS, keep packets under that ceiling end to end.
Trade-offs and pitfalls
The most common real-world failure looks like an application problem rather than a network problem: small packets (DNS lookups, TCP handshakes) work fine, large packets vanish, because they are the ones that exceed the encapsulated MTU and get silently dropped with no ICMP response to explain why. The second pitfall is assuming the overlay buys something the underlay could not: if the actual requirement is simply reaching a cloud workload from on-prem, a Layer 3 routed underlay with BGP is simpler, easier to troubleshoot, and has no MTU tax at all. Reach for VXLAN/EVPN specifically when preserving MAC or IP addresses across a move matters, or when a single physical fabric has to carry many mutually isolated tenants. Reach for plain GRE only for simple point-to-point IP-in-IP tunneling with no multi-tenant segmentation requirement, since GRE alone gives a tunnel, not a virtual network.
Implement an example Terraform module pattern (HCL) that conditionally provisions either a VPN connection or a Dedicated Interconnect to a cloud transit gateway based on an input variable. Requirements: high-availability, parameterized ASN, outputs for connection IDs and BGP peer info, and clear inputs/outputs. Pseudocode HCL accepted but include conditional expressions and module interface.
Sample Answer
Approach
Model this on AWS as a single Transit Gateway (a regional hub that multiple VPN connections and Direct
Connect attachments can plug into) with one of two attachment types selected by an input variable: a VPN
connection for the internet-based path, or a Direct Connect Gateway association for the dedicated-circuit
path, which is AWS's realization of what the question calls a "Dedicated Interconnect" (GCP's own product
of that name works the same way conceptually, pairing a Dedicated Interconnect with a Cloud Router). High
availability differs by path: VPN gets it from AWS's own two-tunnels-per-connection design, while Direct
Connect gets it from the customer provisioning two physically diverse circuits into the same Direct Connect
Gateway, which this module assumes exists already. The onprem_bgp_asn variable below feeds the VPN path's
BGP ASN: BGP (Border Gateway Protocol) is the protocol that dynamically advertises which networks are
reachable through which path, and an ASN (Autonomous System Number) is the numeric ID that identifies this
network to it.
Terraform HCL (conditional module)
variable "connectivity_type" {
description = "\"vpn\" or \"dx\" (Direct Connect): which attachment to provision onto the transit gateway."
type = string
validation {
condition = contains(["vpn", "dx"], var.connectivity_type)
error_message = "connectivity_type must be \"vpn\" or \"dx\"."
}
}
variable "onprem_bgp_asn" {
type = number
default = 65000
}
# required when connectivity_type = "vpn"
variable "onprem_public_ip" {
type = string
default = null
}
# required when connectivity_type = "dx"
variable "dx_gateway_id" {
type = string
default = null
}
variable "tunnel_preshared_key" {
type = string
sensitive = true
default = null
}
resource "aws_ec2_transit_gateway" "hub" {
amazon_side_asn = 64512
description = "Multi-cloud/hybrid hub"
}
# --- VPN path ---
resource "aws_customer_gateway" "onprem" {
count = var.connectivity_type == "vpn" ? 1 : 0
bgp_asn = var.onprem_bgp_asn
ip_address = var.onprem_public_ip
type = "ipsec.1"
}
resource "aws_vpn_connection" "onprem" {
count = var.connectivity_type == "vpn" ? 1 : 0
transit_gateway_id = aws_ec2_transit_gateway.hub.id
customer_gateway_id = aws_customer_gateway.onprem[0].id
type = "ipsec.1"
static_routes_only = false
tunnel1_preshared_key = var.tunnel_preshared_key
}
# --- Direct Connect path ---
resource "aws_dx_gateway_association" "onprem" {
count = var.connectivity_type == "dx" ? 1 : 0
dx_gateway_id = var.dx_gateway_id
associated_gateway_id = aws_ec2_transit_gateway.hub.id
allowed_prefixes = ["10.0.0.0/8"]
}
locals {
active_connection_id = var.connectivity_type == "vpn" ? (
length(aws_vpn_connection.onprem) > 0 ? aws_vpn_connection.onprem[0].id : null
) : (
length(aws_dx_gateway_association.onprem) > 0 ? aws_dx_gateway_association.onprem[0].id : null
)
}
output "transit_gateway_id" { value = aws_ec2_transit_gateway.hub.id }
output "connection_id" {
description = "The active VPN connection ID or DX gateway association ID, whichever path is enabled."
value = local.active_connection_id
}
output "bgp_peer_asn" { value = var.onprem_bgp_asn }
Key points
The count = condition ? 1 : 0 pattern is what makes the module conditionally provision one resource type
or the other from a single connectivity_type input; local.active_connection_id then normalizes the
output so a caller does not need to know which branch was taken to get a usable identifier. High
availability is not represented by a Terraform argument on either resource, it comes from the underlying
architecture (two tunnels for VPN, two circuits for Direct Connect), so an interview answer should say that
explicitly rather than implying HA is just a flag to set.
Complexity and edge cases
terraform init, terraform fmt -check, and terraform validate all pass on this configuration; running
terraform plan with connectivity_type = "vpn" and no AWS credentials correctly fails only at the
provider-authentication step, confirming the resource graph itself is internally consistent up to that
point. Edge cases: switching connectivity_type from "vpn" to "dx" on an existing deployment destroys
the VPN resources and creates the Direct Connect association, an outage window, not a live migration, so a
real cutover needs both paths provisioned simultaneously with a manual traffic shift, not a one-variable
flip in production; and the allowed_prefixes list on the Direct Connect association must be kept in sync
with actual on-prem CIDR ranges (blocks of IP addresses written in CIDR notation, such as 10.0.0.0/8) or
valid traffic will be silently dropped at the gateway rather than
producing an obvious error.
Unlock Full Question Bank
Get access to all Multi-Cloud and Hybrid Cloud Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.