Skip to content
v2.278.0

AWS App Mesh Construct Library ​

AWS App Mesh is a service mesh based on the Envoy proxy that makes it easy to monitor and control microservices. App Mesh standardizes how your microservices communicate, giving you end-to-end visibility and helping to ensure high-availability for your applications.

App Mesh gives you consistent visibility and network traffic controls for every microservice in an application.

App Mesh supports microservice applications that use service discovery naming for their components. To use App Mesh, you must have an existing application running on AWS Fargate, Amazon ECS, Amazon EKS, Kubernetes on AWS, or Amazon EC2.

For further information on AWS App Mesh, visit the AWS App Mesh Documentation.

Create the App and Stack ​

ts
const app = new cdk.App();
const stack = new cdk.Stack(app, 'stack');
python
app = cdk.App()
stack = cdk.Stack(app, "stack")
java
App app = new App();
Stack stack = new Stack(app, "stack");
csharp
var app = new App();
var stack = new Stack(app, "stack");
go
app := cdk.NewApp()
stack := cdk.NewStack(app, jsii.String("stack"))

Creating the Mesh ​

A service mesh is a logical boundary for network traffic between the services that reside within it.

After you create your service mesh, you can create virtual services, virtual nodes, virtual routers, and routes to distribute traffic between the applications in your mesh.

The following example creates the AppMesh service mesh with the default egress filter of DROP_ALL. See the AWS CloudFormation EgressFilter resource for more info on egress filters.

ts
const mesh = new appmesh.Mesh(this, 'AppMesh', {
  meshName: 'myAwsMesh',
});
python
mesh = appmesh.Mesh(self, "AppMesh",
    mesh_name="myAwsMesh"
)
java
Mesh mesh = Mesh.Builder.create(this, "AppMesh")
        .meshName("myAwsMesh")
        .build();
csharp
var mesh = new Mesh(this, "AppMesh", new MeshProps {
    MeshName = "myAwsMesh"
});
go
mesh := appmesh.NewMesh(this, jsii.String("AppMesh"), &MeshProps{
	MeshName: jsii.String("myAwsMesh"),
})

The mesh can instead be created with the ALLOW_ALL egress filter by providing the egressFilter property.

ts
const mesh = new appmesh.Mesh(this, 'AppMesh', {
  meshName: 'myAwsMesh',
  egressFilter: appmesh.MeshFilterType.ALLOW_ALL,
});
python
mesh = appmesh.Mesh(self, "AppMesh",
    mesh_name="myAwsMesh",
    egress_filter=appmesh.MeshFilterType.ALLOW_ALL
)
java
Mesh mesh = Mesh.Builder.create(this, "AppMesh")
        .meshName("myAwsMesh")
        .egressFilter(MeshFilterType.ALLOW_ALL)
        .build();
csharp
var mesh = new Mesh(this, "AppMesh", new MeshProps {
    MeshName = "myAwsMesh",
    EgressFilter = MeshFilterType.ALLOW_ALL
});
go
mesh := appmesh.NewMesh(this, jsii.String("AppMesh"), &MeshProps{
	MeshName: jsii.String("myAwsMesh"),
	EgressFilter: appmesh.MeshFilterType_ALLOW_ALL,
})

A mesh with an IP preference can be created by providing the property serviceDiscovery that specifes an ipPreference.

ts
const mesh = new appmesh.Mesh(this, 'AppMesh', {
  meshName: 'myAwsMesh',
  serviceDiscovery: {
    ipPreference: appmesh.IpPreference.IPV4_ONLY,
  },
});
python
mesh = appmesh.Mesh(self, "AppMesh",
    mesh_name="myAwsMesh",
    service_discovery=appmesh.MeshServiceDiscovery(
        ip_preference=appmesh.IpPreference.IPV4_ONLY
    )
)
java
Mesh mesh = Mesh.Builder.create(this, "AppMesh")
        .meshName("myAwsMesh")
        .serviceDiscovery(MeshServiceDiscovery.builder()
                .ipPreference(IpPreference.IPV4_ONLY)
                .build())
        .build();
csharp
var mesh = new Mesh(this, "AppMesh", new MeshProps {
    MeshName = "myAwsMesh",
    ServiceDiscovery = new MeshServiceDiscovery {
        IpPreference = IpPreference.IPV4_ONLY
    }
});
go
mesh := appmesh.NewMesh(this, jsii.String("AppMesh"), &MeshProps{
	MeshName: jsii.String("myAwsMesh"),
	ServiceDiscovery: &MeshServiceDiscovery{
		IpPreference: appmesh.IpPreference_IPV4_ONLY,
	},
})

Adding VirtualRouters ​

A mesh uses virtual routers as logical units to route requests to virtual nodes.

Virtual routers handle traffic for one or more virtual services within your mesh. After you create a virtual router, you can create and associate routes to your virtual router that direct incoming requests to different virtual nodes.

ts
declare const mesh: appmesh.Mesh;
const router = mesh.addVirtualRouter('router', {
  listeners: [appmesh.VirtualRouterListener.http(8080)],
});
python
# mesh: appmesh.Mesh

router = mesh.add_virtual_router("router",
    listeners=[appmesh.VirtualRouterListener.http(8080)]
)
java
Mesh mesh;

VirtualRouter router = mesh.addVirtualRouter("router", VirtualRouterBaseProps.builder()
        .listeners(List.of(VirtualRouterListener.http(8080)))
        .build());
csharp
Mesh mesh;

var router = mesh.AddVirtualRouter("router", new VirtualRouterBaseProps {
    Listeners = new [] { VirtualRouterListener.Http(8080) }
});
go
var mesh Mesh

router := mesh.addVirtualRouter(jsii.String("router"), &VirtualRouterBaseProps{
	Listeners: []VirtualRouterListener{
		appmesh.VirtualRouterListener_Http(jsii.Number(8080)),
	},
})

Note that creating the router using the addVirtualRouter() method places it in the same stack as the mesh (which might be different from the current stack). The router can also be created using the VirtualRouter constructor (passing in the mesh) instead of calling the addVirtualRouter() method. This is particularly useful when splitting your resources between many stacks: for example, defining the mesh itself as part of an infrastructure stack, but defining the other resources, such as routers, in the application stack:

ts
declare const infraStack: cdk.Stack;
declare const appStack: cdk.Stack;

const mesh = new appmesh.Mesh(infraStack, 'AppMesh', {
  meshName: 'myAwsMesh',
  egressFilter: appmesh.MeshFilterType.ALLOW_ALL,
});

// the VirtualRouter will belong to 'appStack',
// even though the Mesh belongs to 'infraStack'
const router = new appmesh.VirtualRouter(appStack, 'router', {
  mesh, // notice that mesh is a required property when creating a router with the 'new' statement
  listeners: [appmesh.VirtualRouterListener.http(8081)],
});
python
# infra_stack: cdk.Stack
# app_stack: cdk.Stack


mesh = appmesh.Mesh(infra_stack, "AppMesh",
    mesh_name="myAwsMesh",
    egress_filter=appmesh.MeshFilterType.ALLOW_ALL
)

# the VirtualRouter will belong to 'appStack',
# even though the Mesh belongs to 'infraStack'
router = appmesh.VirtualRouter(app_stack, "router",
    mesh=mesh,  # notice that mesh is a required property when creating a router with the 'new' statement
    listeners=[appmesh.VirtualRouterListener.http(8081)]
)
java
Stack infraStack;
Stack appStack;


Mesh mesh = Mesh.Builder.create(infraStack, "AppMesh")
        .meshName("myAwsMesh")
        .egressFilter(MeshFilterType.ALLOW_ALL)
        .build();

// the VirtualRouter will belong to 'appStack',
// even though the Mesh belongs to 'infraStack'
VirtualRouter router = VirtualRouter.Builder.create(appStack, "router")
        .mesh(mesh) // notice that mesh is a required property when creating a router with the 'new' statement
        .listeners(List.of(VirtualRouterListener.http(8081)))
        .build();
csharp
Stack infraStack;
Stack appStack;


var mesh = new Mesh(infraStack, "AppMesh", new MeshProps {
    MeshName = "myAwsMesh",
    EgressFilter = MeshFilterType.ALLOW_ALL
});

// the VirtualRouter will belong to 'appStack',
// even though the Mesh belongs to 'infraStack'
var router = new VirtualRouter(appStack, "router", new VirtualRouterProps {
    Mesh = mesh,  // notice that mesh is a required property when creating a router with the 'new' statement
    Listeners = new [] { VirtualRouterListener.Http(8081) }
});
go
var infraStack Stack
var appStack Stack


mesh := appmesh.NewMesh(infraStack, jsii.String("AppMesh"), &MeshProps{
	MeshName: jsii.String("myAwsMesh"),
	EgressFilter: appmesh.MeshFilterType_ALLOW_ALL,
})

// the VirtualRouter will belong to 'appStack',
// even though the Mesh belongs to 'infraStack'
router := appmesh.NewVirtualRouter(appStack, jsii.String("router"), &VirtualRouterProps{
	Mesh: Mesh,
	 // notice that mesh is a required property when creating a router with the 'new' statement
	Listeners: []VirtualRouterListener{
		appmesh.VirtualRouterListener_Http(jsii.Number(8081)),
	},
})

The same is true for other add*() methods in the App Mesh construct library.

The VirtualRouterListener class lets you define protocol-specific listeners. The http(), http2(), grpc() and tcp() methods create listeners for the named protocols. They accept a single parameter that defines the port to on which requests will be matched. The port parameter defaults to 8080 if omitted.

Adding a VirtualService ​

A virtual service is an abstraction of a real service that is provided by a virtual node directly, or indirectly by means of a virtual router. Dependent services call your virtual service by its virtualServiceName, and those requests are routed to the virtual node or virtual router specified as the provider for the virtual service.

We recommend that you use the service discovery name of the real service that you're targeting (such as my-service.default.svc.cluster.local).

When creating a virtual service:

  • If you want the virtual service to spread traffic across multiple virtual nodes, specify a virtual router.
  • If you want the virtual service to reach a virtual node directly, without a virtual router, specify a virtual node.

Adding a virtual router as the provider:

ts
declare const router: appmesh.VirtualRouter;

new appmesh.VirtualService(this, 'virtual-service', {
  virtualServiceName: 'my-service.default.svc.cluster.local', // optional
  virtualServiceProvider: appmesh.VirtualServiceProvider.virtualRouter(router),
});
python
# router: appmesh.VirtualRouter


appmesh.VirtualService(self, "virtual-service",
    virtual_service_name="my-service.default.svc.cluster.local",  # optional
    virtual_service_provider=appmesh.VirtualServiceProvider.virtual_router(router)
)
java
VirtualRouter router;


VirtualService.Builder.create(this, "virtual-service")
        .virtualServiceName("my-service.default.svc.cluster.local") // optional
        .virtualServiceProvider(VirtualServiceProvider.virtualRouter(router))
        .build();
csharp
VirtualRouter router;


new VirtualService(this, "virtual-service", new VirtualServiceProps {
    VirtualServiceName = "my-service.default.svc.cluster.local",  // optional
    VirtualServiceProvider = VirtualServiceProvider.VirtualRouter(router)
});
go
var router VirtualRouter


appmesh.NewVirtualService(this, jsii.String("virtual-service"), &VirtualServiceProps{
	VirtualServiceName: jsii.String("my-service.default.svc.cluster.local"),
	 // optional
	VirtualServiceProvider: appmesh.VirtualServiceProvider_VirtualRouter(router),
})

Adding a virtual node as the provider:

ts
declare const node: appmesh.VirtualNode;

new appmesh.VirtualService(this, 'virtual-service', {
  virtualServiceName: `my-service.default.svc.cluster.local`, // optional
  virtualServiceProvider: appmesh.VirtualServiceProvider.virtualNode(node),
});
python
# node: appmesh.VirtualNode


appmesh.VirtualService(self, "virtual-service",
    virtual_service_name="my-service.default.svc.cluster.local",  # optional
    virtual_service_provider=appmesh.VirtualServiceProvider.virtual_node(node)
)
java
VirtualNode node;


VirtualService.Builder.create(this, "virtual-service")
        .virtualServiceName("my-service.default.svc.cluster.local") // optional
        .virtualServiceProvider(VirtualServiceProvider.virtualNode(node))
        .build();
csharp
VirtualNode node;


new VirtualService(this, "virtual-service", new VirtualServiceProps {
    VirtualServiceName = "my-service.default.svc.cluster.local",  // optional
    VirtualServiceProvider = VirtualServiceProvider.VirtualNode(node)
});
go
var node VirtualNode


appmesh.NewVirtualService(this, jsii.String("virtual-service"), &VirtualServiceProps{
	VirtualServiceName: jsii.String("my-service.default.svc.cluster.local"),
	 // optional
	VirtualServiceProvider: appmesh.VirtualServiceProvider_VirtualNode(node),
})

Adding a VirtualNode ​

A virtual node acts as a logical pointer to a particular task group, such as an Amazon ECS service or a Kubernetes deployment.

When you create a virtual node, accept inbound traffic by specifying a listener. Outbound traffic that your virtual node expects to send should be specified as a back end.

The response metadata for your new virtual node contains the Amazon Resource Name (ARN) that is associated with the virtual node. Set this value (either the full ARN or the truncated resource name) as the APPMESH_VIRTUAL_NODE_NAME environment variable for your task group's Envoy proxy container in your task definition or pod spec. For example, the value could be mesh/default/virtualNode/simpleapp. This is then mapped to the node.id and node.cluster Envoy parameters.

Note If you require your Envoy stats or tracing to use a different name, you can override the node.cluster value that is set by APPMESH_VIRTUAL_NODE_NAME with the APPMESH_VIRTUAL_NODE_CLUSTER environment variable.

ts
const vpc = new ec2.Vpc(this, 'vpc');
const namespace = new cloudmap.PrivateDnsNamespace(this, 'test-namespace', {
    vpc,
    name: 'domain.local',
});
const service = namespace.createService('Svc');

declare const mesh: appmesh.Mesh;
const node = mesh.addVirtualNode('virtual-node', {
  serviceDiscovery: appmesh.ServiceDiscovery.cloudMap(service),
  listeners: [appmesh.VirtualNodeListener.http({
    port: 8081,
    healthCheck: appmesh.HealthCheck.http({
      healthyThreshold: 3,
      interval: Duration.seconds(5), // minimum
      path: '/health-check-path',
      timeout: Duration.seconds(2), // minimum
      unhealthyThreshold: 2,
    }),
  })],
  accessLog: appmesh.AccessLog.fromFilePath('/dev/stdout'),
});
python
# mesh: appmesh.Mesh
vpc = ec2.Vpc(self, "vpc")
namespace = cloudmap.PrivateDnsNamespace(self, "test-namespace",
    vpc=vpc,
    name="domain.local"
)
service = namespace.create_service("Svc")
node = mesh.add_virtual_node("virtual-node",
    service_discovery=appmesh.ServiceDiscovery.cloud_map(service),
    listeners=[appmesh.VirtualNodeListener.http(
        port=8081,
        health_check=appmesh.HealthCheck.http(
            healthy_threshold=3,
            interval=Duration.seconds(5),  # minimum
            path="/health-check-path",
            timeout=Duration.seconds(2),  # minimum
            unhealthy_threshold=2
        )
    )],
    access_log=appmesh.AccessLog.from_file_path("/dev/stdout")
)
java
Mesh mesh;
Vpc vpc = new Vpc(this, "vpc");
PrivateDnsNamespace namespace = PrivateDnsNamespace.Builder.create(this, "test-namespace")
        .vpc(vpc)
        .name("domain.local")
        .build();
Service service = namespace.createService("Svc");
VirtualNode node = mesh.addVirtualNode("virtual-node", VirtualNodeBaseProps.builder()
        .serviceDiscovery(ServiceDiscovery.cloudMap(service))
        .listeners(List.of(VirtualNodeListener.http(HttpVirtualNodeListenerOptions.builder()
                .port(8081)
                .healthCheck(HealthCheck.http(HttpHealthCheckOptions.builder()
                        .healthyThreshold(3)
                        .interval(Duration.seconds(5)) // minimum
                        .path("/health-check-path")
                        .timeout(Duration.seconds(2)) // minimum
                        .unhealthyThreshold(2)
                        .build()))
                .build())))
        .accessLog(AccessLog.fromFilePath("/dev/stdout"))
        .build());
csharp
Mesh mesh;
var vpc = new Vpc(this, "vpc");
var namespace = new PrivateDnsNamespace(this, "test-namespace", new PrivateDnsNamespaceProps {
    Vpc = vpc,
    Name = "domain.local"
});
var service = namespace.CreateService("Svc");
var node = mesh.AddVirtualNode("virtual-node", new VirtualNodeBaseProps {
    ServiceDiscovery = ServiceDiscovery.CloudMap(service),
    Listeners = new [] { VirtualNodeListener.Http(new HttpVirtualNodeListenerOptions {
        Port = 8081,
        HealthCheck = HealthCheck.Http(new HttpHealthCheckOptions {
            HealthyThreshold = 3,
            Interval = Duration.Seconds(5),  // minimum
            Path = "/health-check-path",
            Timeout = Duration.Seconds(2),  // minimum
            UnhealthyThreshold = 2
        })
    }) },
    AccessLog = AccessLog.FromFilePath("/dev/stdout")
});
go
var mesh Mesh
vpc := ec2.NewVpc(this, jsii.String("vpc"))
namespace := cloudmap.NewPrivateDnsNamespace(this, jsii.String("test-namespace"), &PrivateDnsNamespaceProps{
	Vpc: Vpc,
	Name: jsii.String("domain.local"),
})
service := namespace.CreateService(jsii.String("Svc"))
node := mesh.addVirtualNode(jsii.String("virtual-node"), &VirtualNodeBaseProps{
	ServiceDiscovery: appmesh.ServiceDiscovery_CloudMap(service),
	Listeners: []VirtualNodeListener{
		appmesh.VirtualNodeListener_Http(&HttpVirtualNodeListenerOptions{
			Port: jsii.Number(8081),
			HealthCheck: appmesh.HealthCheck_Http(&HttpHealthCheckOptions{
				HealthyThreshold: jsii.Number(3),
				Interval: awscdk.Duration_Seconds(jsii.Number(5)),
				 // minimum
				Path: jsii.String("/health-check-path"),
				Timeout: awscdk.Duration_*Seconds(jsii.Number(2)),
				 // minimum
				UnhealthyThreshold: jsii.Number(2),
			}),
		}),
	},
	AccessLog: appmesh.AccessLog_FromFilePath(jsii.String("/dev/stdout")),
})

Create a VirtualNode with the constructor and add tags.

ts
declare const mesh: appmesh.Mesh;
declare const service: cloudmap.Service;

const node = new appmesh.VirtualNode(this, 'node', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.cloudMap(service),
  listeners: [appmesh.VirtualNodeListener.http({
    port: 8080,
    healthCheck: appmesh.HealthCheck.http({
      healthyThreshold: 3,
      interval: Duration.seconds(5),
      path: '/ping',
      timeout: Duration.seconds(2),
      unhealthyThreshold: 2,
    }),
    timeout: {
      idle: Duration.seconds(5),
    },
  })],
  backendDefaults: {
    tlsClientPolicy: {
      validation: {
        trust: appmesh.TlsValidationTrust.file('/keys/local_cert_chain.pem'),
      },
    },
  },
  accessLog: appmesh.AccessLog.fromFilePath('/dev/stdout'),
});

cdk.Tags.of(node).add('Environment', 'Dev');
python
# mesh: appmesh.Mesh
# service: cloudmap.Service


node = appmesh.VirtualNode(self, "node",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.cloud_map(service),
    listeners=[appmesh.VirtualNodeListener.http(
        port=8080,
        health_check=appmesh.HealthCheck.http(
            healthy_threshold=3,
            interval=Duration.seconds(5),
            path="/ping",
            timeout=Duration.seconds(2),
            unhealthy_threshold=2
        ),
        timeout=appmesh.HttpTimeout(
            idle=Duration.seconds(5)
        )
    )],
    backend_defaults=appmesh.BackendDefaults(
        tls_client_policy=appmesh.TlsClientPolicy(
            validation=appmesh.TlsValidation(
                trust=appmesh.TlsValidationTrust.file("/keys/local_cert_chain.pem")
            )
        )
    ),
    access_log=appmesh.AccessLog.from_file_path("/dev/stdout")
)

cdk.Tags.of(node).add("Environment", "Dev")
java
Mesh mesh;
Service service;


VirtualNode node = VirtualNode.Builder.create(this, "node")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.cloudMap(service))
        .listeners(List.of(VirtualNodeListener.http(HttpVirtualNodeListenerOptions.builder()
                .port(8080)
                .healthCheck(HealthCheck.http(HttpHealthCheckOptions.builder()
                        .healthyThreshold(3)
                        .interval(Duration.seconds(5))
                        .path("/ping")
                        .timeout(Duration.seconds(2))
                        .unhealthyThreshold(2)
                        .build()))
                .timeout(HttpTimeout.builder()
                        .idle(Duration.seconds(5))
                        .build())
                .build())))
        .backendDefaults(BackendDefaults.builder()
                .tlsClientPolicy(TlsClientPolicy.builder()
                        .validation(TlsValidation.builder()
                                .trust(TlsValidationTrust.file("/keys/local_cert_chain.pem"))
                                .build())
                        .build())
                .build())
        .accessLog(AccessLog.fromFilePath("/dev/stdout"))
        .build();

Tags.of(node).add("Environment", "Dev");
csharp
Mesh mesh;
Service service;


var node = new VirtualNode(this, "node", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.CloudMap(service),
    Listeners = new [] { VirtualNodeListener.Http(new HttpVirtualNodeListenerOptions {
        Port = 8080,
        HealthCheck = HealthCheck.Http(new HttpHealthCheckOptions {
            HealthyThreshold = 3,
            Interval = Duration.Seconds(5),
            Path = "/ping",
            Timeout = Duration.Seconds(2),
            UnhealthyThreshold = 2
        }),
        Timeout = new HttpTimeout {
            Idle = Duration.Seconds(5)
        }
    }) },
    BackendDefaults = new BackendDefaults {
        TlsClientPolicy = new TlsClientPolicy {
            Validation = new TlsValidation {
                Trust = TlsValidationTrust.File("/keys/local_cert_chain.pem")
            }
        }
    },
    AccessLog = AccessLog.FromFilePath("/dev/stdout")
});

Tags.Of(node).Add("Environment", "Dev");
go
var mesh Mesh
var service Service


node := appmesh.NewVirtualNode(this, jsii.String("node"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_CloudMap(service),
	Listeners: []VirtualNodeListener{
		appmesh.VirtualNodeListener_Http(&HttpVirtualNodeListenerOptions{
			Port: jsii.Number(8080),
			HealthCheck: appmesh.HealthCheck_Http(&HttpHealthCheckOptions{
				HealthyThreshold: jsii.Number(3),
				Interval: awscdk.Duration_Seconds(jsii.Number(5)),
				Path: jsii.String("/ping"),
				Timeout: awscdk.Duration_*Seconds(jsii.Number(2)),
				UnhealthyThreshold: jsii.Number(2),
			}),
			Timeout: &HttpTimeout{
				Idle: awscdk.Duration_*Seconds(jsii.Number(5)),
			},
		}),
	},
	BackendDefaults: &BackendDefaults{
		TlsClientPolicy: &TlsClientPolicy{
			Validation: &TlsValidation{
				Trust: appmesh.TlsValidationTrust_File(jsii.String("/keys/local_cert_chain.pem")),
			},
		},
	},
	AccessLog: appmesh.AccessLog_FromFilePath(jsii.String("/dev/stdout")),
})

cdk.Tags_Of(node).Add(jsii.String("Environment"), jsii.String("Dev"))

Create a VirtualNode with the customized access logging format.

ts
declare const mesh: appmesh.Mesh;
declare const service: cloudmap.Service;
const node = new appmesh.VirtualNode(this, 'node', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.cloudMap(service),
  listeners: [appmesh.VirtualNodeListener.http({
    port: 8080,
    healthCheck: appmesh.HealthCheck.http({
      healthyThreshold: 3,
      interval: cdk.Duration.seconds(5),
      path: '/ping',
      timeout: cdk.Duration.seconds(2),
      unhealthyThreshold: 2,
    }),
    timeout: {
      idle: cdk.Duration.seconds(5),
    },
  })],
  backendDefaults: {
    tlsClientPolicy: {
      validation: {
        trust: appmesh.TlsValidationTrust.file('/keys/local_cert_chain.pem'),
      },
    },
  },
  accessLog: appmesh.AccessLog.fromFilePath('/dev/stdout',
    appmesh.LoggingFormat.fromJson(
      {testKey1: 'testValue1', testKey2: 'testValue2'})),
});
python
# mesh: appmesh.Mesh
# service: cloudmap.Service

node = appmesh.VirtualNode(self, "node",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.cloud_map(service),
    listeners=[appmesh.VirtualNodeListener.http(
        port=8080,
        health_check=appmesh.HealthCheck.http(
            healthy_threshold=3,
            interval=cdk.Duration.seconds(5),
            path="/ping",
            timeout=cdk.Duration.seconds(2),
            unhealthy_threshold=2
        ),
        timeout=appmesh.HttpTimeout(
            idle=cdk.Duration.seconds(5)
        )
    )],
    backend_defaults=appmesh.BackendDefaults(
        tls_client_policy=appmesh.TlsClientPolicy(
            validation=appmesh.TlsValidation(
                trust=appmesh.TlsValidationTrust.file("/keys/local_cert_chain.pem")
            )
        )
    ),
    access_log=appmesh.AccessLog.from_file_path("/dev/stdout",
        appmesh.LoggingFormat.from_json({"test_key1": "testValue1", "test_key2": "testValue2"}))
)
java
Mesh mesh;
Service service;

VirtualNode node = VirtualNode.Builder.create(this, "node")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.cloudMap(service))
        .listeners(List.of(VirtualNodeListener.http(HttpVirtualNodeListenerOptions.builder()
                .port(8080)
                .healthCheck(HealthCheck.http(HttpHealthCheckOptions.builder()
                        .healthyThreshold(3)
                        .interval(Duration.seconds(5))
                        .path("/ping")
                        .timeout(Duration.seconds(2))
                        .unhealthyThreshold(2)
                        .build()))
                .timeout(HttpTimeout.builder()
                        .idle(Duration.seconds(5))
                        .build())
                .build())))
        .backendDefaults(BackendDefaults.builder()
                .tlsClientPolicy(TlsClientPolicy.builder()
                        .validation(TlsValidation.builder()
                                .trust(TlsValidationTrust.file("/keys/local_cert_chain.pem"))
                                .build())
                        .build())
                .build())
        .accessLog(AccessLog.fromFilePath("/dev/stdout", LoggingFormat.fromJson(Map.of("testKey1", "testValue1", "testKey2", "testValue2"))))
        .build();
csharp
Mesh mesh;
Service service;

var node = new VirtualNode(this, "node", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.CloudMap(service),
    Listeners = new [] { VirtualNodeListener.Http(new HttpVirtualNodeListenerOptions {
        Port = 8080,
        HealthCheck = HealthCheck.Http(new HttpHealthCheckOptions {
            HealthyThreshold = 3,
            Interval = Duration.Seconds(5),
            Path = "/ping",
            Timeout = Duration.Seconds(2),
            UnhealthyThreshold = 2
        }),
        Timeout = new HttpTimeout {
            Idle = Duration.Seconds(5)
        }
    }) },
    BackendDefaults = new BackendDefaults {
        TlsClientPolicy = new TlsClientPolicy {
            Validation = new TlsValidation {
                Trust = TlsValidationTrust.File("/keys/local_cert_chain.pem")
            }
        }
    },
    AccessLog = AccessLog.FromFilePath("/dev/stdout", LoggingFormat.FromJson(new Dictionary<string, string> { { "testKey1", "testValue1" }, { "testKey2", "testValue2" } }))
});
go
var mesh Mesh
var service Service

node := appmesh.NewVirtualNode(this, jsii.String("node"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_CloudMap(service),
	Listeners: []VirtualNodeListener{
		appmesh.VirtualNodeListener_Http(&HttpVirtualNodeListenerOptions{
			Port: jsii.Number(8080),
			HealthCheck: appmesh.HealthCheck_Http(&HttpHealthCheckOptions{
				HealthyThreshold: jsii.Number(3),
				Interval: cdk.Duration_Seconds(jsii.Number(5)),
				Path: jsii.String("/ping"),
				Timeout: cdk.Duration_*Seconds(jsii.Number(2)),
				UnhealthyThreshold: jsii.Number(2),
			}),
			Timeout: &HttpTimeout{
				Idle: cdk.Duration_*Seconds(jsii.Number(5)),
			},
		}),
	},
	BackendDefaults: &BackendDefaults{
		TlsClientPolicy: &TlsClientPolicy{
			Validation: &TlsValidation{
				Trust: appmesh.TlsValidationTrust_File(jsii.String("/keys/local_cert_chain.pem")),
			},
		},
	},
	AccessLog: appmesh.AccessLog_FromFilePath(jsii.String("/dev/stdout"), appmesh.LoggingFormat_FromJson(map[string]*string{
		"testKey1": jsii.String("testValue1"),
		"testKey2": jsii.String("testValue2"),
	})),
})

By using a key-value pair indexed signature, you can specify json key pairs to customize the log entry pattern. You can also use text format as below. You can only specify one of these 2 formats.

text
  accessLog: appmesh.AccessLog.fromFilePath('/dev/stdout', appmesh.LoggingFormat.fromText('test_pattern')),

For what values and operators you can use for these two formats, please visit the latest envoy documentation. (https://www.envoyproxy.io/docs/envoy/latest/configuration/observability/access_log/usage) Create a VirtualNode with the constructor and add backend virtual service.

ts
declare const mesh: appmesh.Mesh;
declare const router: appmesh.VirtualRouter;
declare const service: cloudmap.Service;

const node = new appmesh.VirtualNode(this, 'node', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.cloudMap(service),
  listeners: [appmesh.VirtualNodeListener.http({
    port: 8080,
    healthCheck: appmesh.HealthCheck.http({
      healthyThreshold: 3,
      interval: Duration.seconds(5),
      path: '/ping',
      timeout: Duration.seconds(2),
      unhealthyThreshold: 2,
    }),
    timeout: {
      idle: Duration.seconds(5),
    },
  })],
  accessLog: appmesh.AccessLog.fromFilePath('/dev/stdout'),
});

const virtualService = new appmesh.VirtualService(this, 'service-1', {
  virtualServiceProvider: appmesh.VirtualServiceProvider.virtualRouter(router),
  virtualServiceName: 'service1.domain.local',
});

node.addBackend(appmesh.Backend.virtualService(virtualService));
python
# mesh: appmesh.Mesh
# router: appmesh.VirtualRouter
# service: cloudmap.Service


node = appmesh.VirtualNode(self, "node",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.cloud_map(service),
    listeners=[appmesh.VirtualNodeListener.http(
        port=8080,
        health_check=appmesh.HealthCheck.http(
            healthy_threshold=3,
            interval=Duration.seconds(5),
            path="/ping",
            timeout=Duration.seconds(2),
            unhealthy_threshold=2
        ),
        timeout=appmesh.HttpTimeout(
            idle=Duration.seconds(5)
        )
    )],
    access_log=appmesh.AccessLog.from_file_path("/dev/stdout")
)

virtual_service = appmesh.VirtualService(self, "service-1",
    virtual_service_provider=appmesh.VirtualServiceProvider.virtual_router(router),
    virtual_service_name="service1.domain.local"
)

node.add_backend(appmesh.Backend.virtual_service(virtual_service))
java
Mesh mesh;
VirtualRouter router;
Service service;


VirtualNode node = VirtualNode.Builder.create(this, "node")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.cloudMap(service))
        .listeners(List.of(VirtualNodeListener.http(HttpVirtualNodeListenerOptions.builder()
                .port(8080)
                .healthCheck(HealthCheck.http(HttpHealthCheckOptions.builder()
                        .healthyThreshold(3)
                        .interval(Duration.seconds(5))
                        .path("/ping")
                        .timeout(Duration.seconds(2))
                        .unhealthyThreshold(2)
                        .build()))
                .timeout(HttpTimeout.builder()
                        .idle(Duration.seconds(5))
                        .build())
                .build())))
        .accessLog(AccessLog.fromFilePath("/dev/stdout"))
        .build();

VirtualService virtualService = VirtualService.Builder.create(this, "service-1")
        .virtualServiceProvider(VirtualServiceProvider.virtualRouter(router))
        .virtualServiceName("service1.domain.local")
        .build();

node.addBackend(Backend.virtualService(virtualService));
csharp
Mesh mesh;
VirtualRouter router;
Service service;


var node = new VirtualNode(this, "node", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.CloudMap(service),
    Listeners = new [] { VirtualNodeListener.Http(new HttpVirtualNodeListenerOptions {
        Port = 8080,
        HealthCheck = HealthCheck.Http(new HttpHealthCheckOptions {
            HealthyThreshold = 3,
            Interval = Duration.Seconds(5),
            Path = "/ping",
            Timeout = Duration.Seconds(2),
            UnhealthyThreshold = 2
        }),
        Timeout = new HttpTimeout {
            Idle = Duration.Seconds(5)
        }
    }) },
    AccessLog = AccessLog.FromFilePath("/dev/stdout")
});

var virtualService = new VirtualService(this, "service-1", new VirtualServiceProps {
    VirtualServiceProvider = VirtualServiceProvider.VirtualRouter(router),
    VirtualServiceName = "service1.domain.local"
});

node.AddBackend(Backend.VirtualService(virtualService));
go
var mesh Mesh
var router VirtualRouter
var service Service


node := appmesh.NewVirtualNode(this, jsii.String("node"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_CloudMap(service),
	Listeners: []VirtualNodeListener{
		appmesh.VirtualNodeListener_Http(&HttpVirtualNodeListenerOptions{
			Port: jsii.Number(8080),
			HealthCheck: appmesh.HealthCheck_Http(&HttpHealthCheckOptions{
				HealthyThreshold: jsii.Number(3),
				Interval: awscdk.Duration_Seconds(jsii.Number(5)),
				Path: jsii.String("/ping"),
				Timeout: awscdk.Duration_*Seconds(jsii.Number(2)),
				UnhealthyThreshold: jsii.Number(2),
			}),
			Timeout: &HttpTimeout{
				Idle: awscdk.Duration_*Seconds(jsii.Number(5)),
			},
		}),
	},
	AccessLog: appmesh.AccessLog_FromFilePath(jsii.String("/dev/stdout")),
})

virtualService := appmesh.NewVirtualService(this, jsii.String("service-1"), &VirtualServiceProps{
	VirtualServiceProvider: appmesh.VirtualServiceProvider_VirtualRouter(router),
	VirtualServiceName: jsii.String("service1.domain.local"),
})

node.AddBackend(appmesh.Backend_VirtualService(virtualService))

The listeners property can be left blank and added later with the node.addListener() method. The serviceDiscovery property must be specified when specifying a listener.

The backends property can be added with node.addBackend(). In the example, we define a virtual service and add it to the virtual node to allow egress traffic to other nodes.

The backendDefaults property is added to the node while creating the virtual node. These are the virtual node's default settings for all backends.

The VirtualNode.addBackend() method is especially useful if you want to create a circular traffic flow by having a Virtual Service as a backend whose provider is that same Virtual Node:

ts
declare const mesh: appmesh.Mesh;

const node = new appmesh.VirtualNode(this, 'node', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.dns('node'),
});

const virtualService = new appmesh.VirtualService(this, 'service-1', {
  virtualServiceProvider: appmesh.VirtualServiceProvider.virtualNode(node),
  virtualServiceName: 'service1.domain.local',
});

node.addBackend(appmesh.Backend.virtualService(virtualService));
python
# mesh: appmesh.Mesh


node = appmesh.VirtualNode(self, "node",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.dns("node")
)

virtual_service = appmesh.VirtualService(self, "service-1",
    virtual_service_provider=appmesh.VirtualServiceProvider.virtual_node(node),
    virtual_service_name="service1.domain.local"
)

node.add_backend(appmesh.Backend.virtual_service(virtual_service))
java
Mesh mesh;


VirtualNode node = VirtualNode.Builder.create(this, "node")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.dns("node"))
        .build();

VirtualService virtualService = VirtualService.Builder.create(this, "service-1")
        .virtualServiceProvider(VirtualServiceProvider.virtualNode(node))
        .virtualServiceName("service1.domain.local")
        .build();

node.addBackend(Backend.virtualService(virtualService));
csharp
Mesh mesh;


var node = new VirtualNode(this, "node", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.Dns("node")
});

var virtualService = new VirtualService(this, "service-1", new VirtualServiceProps {
    VirtualServiceProvider = VirtualServiceProvider.VirtualNode(node),
    VirtualServiceName = "service1.domain.local"
});

node.AddBackend(Backend.VirtualService(virtualService));
go
var mesh Mesh


node := appmesh.NewVirtualNode(this, jsii.String("node"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_Dns(jsii.String("node")),
})

virtualService := appmesh.NewVirtualService(this, jsii.String("service-1"), &VirtualServiceProps{
	VirtualServiceProvider: appmesh.VirtualServiceProvider_VirtualNode(node),
	VirtualServiceName: jsii.String("service1.domain.local"),
})

node.AddBackend(appmesh.Backend_VirtualService(virtualService))

Adding TLS to a listener ​

The tls property specifies TLS configuration when creating a listener for a virtual node or a virtual gateway. Provide the TLS certificate to the proxy in one of the following ways:

  • A certificate from AWS Certificate Manager (ACM).

  • A customer-provided certificate (specify a certificateChain path file and a privateKey file path).

  • A certificate provided by a Secrets Discovery Service (SDS) endpoint over local Unix Domain Socket (specify its secretName).

ts
// A Virtual Node with listener TLS from an ACM provided certificate
declare const cert: certificatemanager.Certificate;
declare const mesh: appmesh.Mesh;

const node = new appmesh.VirtualNode(this, 'node', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.dns('node'),
  listeners: [appmesh.VirtualNodeListener.grpc({
    port: 80,
    tls: {
      mode: appmesh.TlsMode.STRICT,
      certificate: appmesh.TlsCertificate.acm(cert),
    },
  })],
});

// A Virtual Gateway with listener TLS from a customer provided file certificate
const gateway = new appmesh.VirtualGateway(this, 'gateway', {
  mesh,
  listeners: [appmesh.VirtualGatewayListener.grpc({
    port: 8080,
    tls: {
      mode: appmesh.TlsMode.STRICT,
      certificate: appmesh.TlsCertificate.file('path/to/certChain', 'path/to/privateKey'),
    },
  })],
  virtualGatewayName: 'gateway',
});

// A Virtual Gateway with listener TLS from a SDS provided certificate
const gateway2 = new appmesh.VirtualGateway(this, 'gateway2', {
  mesh,
  listeners: [appmesh.VirtualGatewayListener.http2({
    port: 8080,
    tls: {
      mode: appmesh.TlsMode.STRICT,
      certificate: appmesh.TlsCertificate.sds('secrete_certificate'),
    },
  })],
  virtualGatewayName: 'gateway2',
});
python
# A Virtual Node with listener TLS from an ACM provided certificate
# cert: certificatemanager.Certificate
# mesh: appmesh.Mesh


node = appmesh.VirtualNode(self, "node",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.dns("node"),
    listeners=[appmesh.VirtualNodeListener.grpc(
        port=80,
        tls=appmesh.ListenerTlsOptions(
            mode=appmesh.TlsMode.STRICT,
            certificate=appmesh.TlsCertificate.acm(cert)
        )
    )]
)

# A Virtual Gateway with listener TLS from a customer provided file certificate
gateway = appmesh.VirtualGateway(self, "gateway",
    mesh=mesh,
    listeners=[appmesh.VirtualGatewayListener.grpc(
        port=8080,
        tls=appmesh.ListenerTlsOptions(
            mode=appmesh.TlsMode.STRICT,
            certificate=appmesh.TlsCertificate.file("path/to/certChain", "path/to/privateKey")
        )
    )],
    virtual_gateway_name="gateway"
)

# A Virtual Gateway with listener TLS from a SDS provided certificate
gateway2 = appmesh.VirtualGateway(self, "gateway2",
    mesh=mesh,
    listeners=[appmesh.VirtualGatewayListener.http2(
        port=8080,
        tls=appmesh.ListenerTlsOptions(
            mode=appmesh.TlsMode.STRICT,
            certificate=appmesh.TlsCertificate.sds("secrete_certificate")
        )
    )],
    virtual_gateway_name="gateway2"
)
java
// A Virtual Node with listener TLS from an ACM provided certificate
Certificate cert;
Mesh mesh;


VirtualNode node = VirtualNode.Builder.create(this, "node")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.dns("node"))
        .listeners(List.of(VirtualNodeListener.grpc(GrpcVirtualNodeListenerOptions.builder()
                .port(80)
                .tls(ListenerTlsOptions.builder()
                        .mode(TlsMode.STRICT)
                        .certificate(TlsCertificate.acm(cert))
                        .build())
                .build())))
        .build();

// A Virtual Gateway with listener TLS from a customer provided file certificate
VirtualGateway gateway = VirtualGateway.Builder.create(this, "gateway")
        .mesh(mesh)
        .listeners(List.of(VirtualGatewayListener.grpc(GrpcGatewayListenerOptions.builder()
                .port(8080)
                .tls(ListenerTlsOptions.builder()
                        .mode(TlsMode.STRICT)
                        .certificate(TlsCertificate.file("path/to/certChain", "path/to/privateKey"))
                        .build())
                .build())))
        .virtualGatewayName("gateway")
        .build();

// A Virtual Gateway with listener TLS from a SDS provided certificate
VirtualGateway gateway2 = VirtualGateway.Builder.create(this, "gateway2")
        .mesh(mesh)
        .listeners(List.of(VirtualGatewayListener.http2(Http2GatewayListenerOptions.builder()
                .port(8080)
                .tls(ListenerTlsOptions.builder()
                        .mode(TlsMode.STRICT)
                        .certificate(TlsCertificate.sds("secrete_certificate"))
                        .build())
                .build())))
        .virtualGatewayName("gateway2")
        .build();
csharp
// A Virtual Node with listener TLS from an ACM provided certificate
Certificate cert;
Mesh mesh;


var node = new VirtualNode(this, "node", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.Dns("node"),
    Listeners = new [] { VirtualNodeListener.Grpc(new GrpcVirtualNodeListenerOptions {
        Port = 80,
        Tls = new ListenerTlsOptions {
            Mode = TlsMode.STRICT,
            Certificate = TlsCertificate.Acm(cert)
        }
    }) }
});

// A Virtual Gateway with listener TLS from a customer provided file certificate
var gateway = new VirtualGateway(this, "gateway", new VirtualGatewayProps {
    Mesh = mesh,
    Listeners = new [] { VirtualGatewayListener.Grpc(new GrpcGatewayListenerOptions {
        Port = 8080,
        Tls = new ListenerTlsOptions {
            Mode = TlsMode.STRICT,
            Certificate = TlsCertificate.File("path/to/certChain", "path/to/privateKey")
        }
    }) },
    VirtualGatewayName = "gateway"
});

// A Virtual Gateway with listener TLS from a SDS provided certificate
var gateway2 = new VirtualGateway(this, "gateway2", new VirtualGatewayProps {
    Mesh = mesh,
    Listeners = new [] { VirtualGatewayListener.Http2(new Http2GatewayListenerOptions {
        Port = 8080,
        Tls = new ListenerTlsOptions {
            Mode = TlsMode.STRICT,
            Certificate = TlsCertificate.Sds("secrete_certificate")
        }
    }) },
    VirtualGatewayName = "gateway2"
});
go
// A Virtual Node with listener TLS from an ACM provided certificate
var cert Certificate
var mesh Mesh


node := appmesh.NewVirtualNode(this, jsii.String("node"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_Dns(jsii.String("node")),
	Listeners: []VirtualNodeListener{
		appmesh.VirtualNodeListener_Grpc(&GrpcVirtualNodeListenerOptions{
			Port: jsii.Number(80),
			Tls: &ListenerTlsOptions{
				Mode: appmesh.TlsMode_STRICT,
				Certificate: appmesh.TlsCertificate_Acm(cert),
			},
		}),
	},
})

// A Virtual Gateway with listener TLS from a customer provided file certificate
gateway := appmesh.NewVirtualGateway(this, jsii.String("gateway"), &VirtualGatewayProps{
	Mesh: Mesh,
	Listeners: []VirtualGatewayListener{
		appmesh.VirtualGatewayListener_Grpc(&GrpcGatewayListenerOptions{
			Port: jsii.Number(8080),
			Tls: &ListenerTlsOptions{
				Mode: appmesh.TlsMode_STRICT,
				Certificate: appmesh.TlsCertificate_File(jsii.String("path/to/certChain"), jsii.String("path/to/privateKey")),
			},
		}),
	},
	VirtualGatewayName: jsii.String("gateway"),
})

// A Virtual Gateway with listener TLS from a SDS provided certificate
gateway2 := appmesh.NewVirtualGateway(this, jsii.String("gateway2"), &VirtualGatewayProps{
	Mesh: Mesh,
	Listeners: []VirtualGatewayListener{
		appmesh.VirtualGatewayListener_Http2(&Http2GatewayListenerOptions{
			Port: jsii.Number(8080),
			Tls: &ListenerTlsOptions{
				Mode: appmesh.TlsMode_STRICT,
				Certificate: appmesh.TlsCertificate_Sds(jsii.String("secrete_certificate")),
			},
		}),
	},
	VirtualGatewayName: jsii.String("gateway2"),
})

Adding mutual TLS authentication ​

Mutual TLS authentication is an optional component of TLS that offers two-way peer authentication. To enable mutual TLS authentication, add the mutualTlsCertificate property to TLS client policy and/or the mutualTlsValidation property to your TLS listener.

tls.mutualTlsValidation and tlsClientPolicy.mutualTlsCertificate can be sourced from either:

  • A customer-provided certificate (specify a certificateChain path file and a privateKey file path).

  • A certificate provided by a Secrets Discovery Service (SDS) endpoint over local Unix Domain Socket (specify its secretName).

Note Currently, a certificate from AWS Certificate Manager (ACM) cannot be used for mutual TLS authentication.

ts
declare const mesh: appmesh.Mesh;

const node1 = new appmesh.VirtualNode(this, 'node1', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.dns('node'),
  listeners: [appmesh.VirtualNodeListener.grpc({
    port: 80,
    tls: {
      mode: appmesh.TlsMode.STRICT,
      certificate: appmesh.TlsCertificate.file('path/to/certChain', 'path/to/privateKey'),
      // Validate a file client certificates to enable mutual TLS authentication when a client provides a certificate.
      mutualTlsValidation: {
        trust: appmesh.TlsValidationTrust.file('path-to-certificate'),
      },
    },
  })],
});

const certificateAuthorityArn = 'arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012';
const node2 = new appmesh.VirtualNode(this, 'node2', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.dns('node2'),
  backendDefaults: {
    tlsClientPolicy: {
      ports: [8080, 8081],
      validation: {
        subjectAlternativeNames: appmesh.SubjectAlternativeNames.matchingExactly('mesh-endpoint.apps.local'),
        trust: appmesh.TlsValidationTrust.acm([
          acmpca.CertificateAuthority.fromCertificateAuthorityArn(this, 'certificate', certificateAuthorityArn)]),
      },
      // Provide a SDS client certificate when a server requests it and enable mutual TLS authentication.
      mutualTlsCertificate: appmesh.TlsCertificate.sds('secret_certificate'),
    },
  },
});
python
# mesh: appmesh.Mesh


node1 = appmesh.VirtualNode(self, "node1",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.dns("node"),
    listeners=[appmesh.VirtualNodeListener.grpc(
        port=80,
        tls=appmesh.ListenerTlsOptions(
            mode=appmesh.TlsMode.STRICT,
            certificate=appmesh.TlsCertificate.file("path/to/certChain", "path/to/privateKey"),
            # Validate a file client certificates to enable mutual TLS authentication when a client provides a certificate.
            mutual_tls_validation=appmesh.MutualTlsValidation(
                trust=appmesh.TlsValidationTrust.file("path-to-certificate")
            )
        )
    )]
)

certificate_authority_arn = "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012"
node2 = appmesh.VirtualNode(self, "node2",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.dns("node2"),
    backend_defaults=appmesh.BackendDefaults(
        tls_client_policy=appmesh.TlsClientPolicy(
            ports=[8080, 8081],
            validation=appmesh.TlsValidation(
                subject_alternative_names=appmesh.SubjectAlternativeNames.matching_exactly("mesh-endpoint.apps.local"),
                trust=appmesh.TlsValidationTrust.acm([
                    acmpca.CertificateAuthority.from_certificate_authority_arn(self, "certificate", certificate_authority_arn)
                ])
            ),
            # Provide a SDS client certificate when a server requests it and enable mutual TLS authentication.
            mutual_tls_certificate=appmesh.TlsCertificate.sds("secret_certificate")
        )
    )
)
java
Mesh mesh;


VirtualNode node1 = VirtualNode.Builder.create(this, "node1")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.dns("node"))
        .listeners(List.of(VirtualNodeListener.grpc(GrpcVirtualNodeListenerOptions.builder()
                .port(80)
                .tls(ListenerTlsOptions.builder()
                        .mode(TlsMode.STRICT)
                        .certificate(TlsCertificate.file("path/to/certChain", "path/to/privateKey"))
                        // Validate a file client certificates to enable mutual TLS authentication when a client provides a certificate.
                        .mutualTlsValidation(MutualTlsValidation.builder()
                                .trust(TlsValidationTrust.file("path-to-certificate"))
                                .build())
                        .build())
                .build())))
        .build();

String certificateAuthorityArn = "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012";
VirtualNode node2 = VirtualNode.Builder.create(this, "node2")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.dns("node2"))
        .backendDefaults(BackendDefaults.builder()
                .tlsClientPolicy(TlsClientPolicy.builder()
                        .ports(List.of(8080, 8081))
                        .validation(TlsValidation.builder()
                                .subjectAlternativeNames(SubjectAlternativeNames.matchingExactly("mesh-endpoint.apps.local"))
                                .trust(TlsValidationTrust.acm(List.of(CertificateAuthority.fromCertificateAuthorityArn(this, "certificate", certificateAuthorityArn))))
                                .build())
                        // Provide a SDS client certificate when a server requests it and enable mutual TLS authentication.
                        .mutualTlsCertificate(TlsCertificate.sds("secret_certificate"))
                        .build())
                .build())
        .build();
csharp
Mesh mesh;


var node1 = new VirtualNode(this, "node1", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.Dns("node"),
    Listeners = new [] { VirtualNodeListener.Grpc(new GrpcVirtualNodeListenerOptions {
        Port = 80,
        Tls = new ListenerTlsOptions {
            Mode = TlsMode.STRICT,
            Certificate = TlsCertificate.File("path/to/certChain", "path/to/privateKey"),
            // Validate a file client certificates to enable mutual TLS authentication when a client provides a certificate.
            MutualTlsValidation = new MutualTlsValidation {
                Trust = TlsValidationTrust.File("path-to-certificate")
            }
        }
    }) }
});

var certificateAuthorityArn = "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012";
var node2 = new VirtualNode(this, "node2", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.Dns("node2"),
    BackendDefaults = new BackendDefaults {
        TlsClientPolicy = new TlsClientPolicy {
            Ports = new [] { 8080, 8081 },
            Validation = new TlsValidation {
                SubjectAlternativeNames = SubjectAlternativeNames.MatchingExactly("mesh-endpoint.apps.local"),
                Trust = TlsValidationTrust.Acm(new [] { CertificateAuthority.FromCertificateAuthorityArn(this, "certificate", certificateAuthorityArn) })
            },
            // Provide a SDS client certificate when a server requests it and enable mutual TLS authentication.
            MutualTlsCertificate = TlsCertificate.Sds("secret_certificate")
        }
    }
});
go
var mesh Mesh


node1 := appmesh.NewVirtualNode(this, jsii.String("node1"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_Dns(jsii.String("node")),
	Listeners: []VirtualNodeListener{
		appmesh.VirtualNodeListener_Grpc(&GrpcVirtualNodeListenerOptions{
			Port: jsii.Number(80),
			Tls: &ListenerTlsOptions{
				Mode: appmesh.TlsMode_STRICT,
				Certificate: appmesh.TlsCertificate_File(jsii.String("path/to/certChain"), jsii.String("path/to/privateKey")),
				// Validate a file client certificates to enable mutual TLS authentication when a client provides a certificate.
				MutualTlsValidation: &MutualTlsValidation{
					Trust: appmesh.TlsValidationTrust_File(jsii.String("path-to-certificate")),
				},
			},
		}),
	},
})

certificateAuthorityArn := "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012"
node2 := appmesh.NewVirtualNode(this, jsii.String("node2"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_*Dns(jsii.String("node2")),
	BackendDefaults: &BackendDefaults{
		TlsClientPolicy: &TlsClientPolicy{
			Ports: []*f64{
				jsii.Number(8080),
				jsii.Number(8081),
			},
			Validation: &TlsValidation{
				SubjectAlternativeNames: appmesh.SubjectAlternativeNames_MatchingExactly(jsii.String("mesh-endpoint.apps.local")),
				Trust: appmesh.TlsValidationTrust_Acm([]ICertificateAuthorityRef{
					acmpca.CertificateAuthority_FromCertificateAuthorityArn(this, jsii.String("certificate"), certificateAuthorityArn),
				}),
			},
			// Provide a SDS client certificate when a server requests it and enable mutual TLS authentication.
			MutualTlsCertificate: appmesh.TlsCertificate_Sds(jsii.String("secret_certificate")),
		},
	},
})

Adding outlier detection to a Virtual Node listener ​

The outlierDetection property adds outlier detection to a Virtual Node listener. The properties baseEjectionDuration, interval, maxEjectionPercent, and maxServerErrors are required.

ts
// Cloud Map service discovery is currently required for host ejection by outlier detection
const vpc = new ec2.Vpc(this, 'vpc');
const namespace = new cloudmap.PrivateDnsNamespace(this, 'test-namespace', {
    vpc,
    name: 'domain.local',
});
const service = namespace.createService('Svc');

declare const mesh: appmesh.Mesh;
const node = mesh.addVirtualNode('virtual-node', {
  serviceDiscovery: appmesh.ServiceDiscovery.cloudMap(service),
  listeners: [appmesh.VirtualNodeListener.http({
    outlierDetection: {
      baseEjectionDuration: Duration.seconds(10),
      interval: Duration.seconds(30),
      maxEjectionPercent: 50,
      maxServerErrors: 5,
    },
  })],
});
python
# mesh: appmesh.Mesh
# Cloud Map service discovery is currently required for host ejection by outlier detection
vpc = ec2.Vpc(self, "vpc")
namespace = cloudmap.PrivateDnsNamespace(self, "test-namespace",
    vpc=vpc,
    name="domain.local"
)
service = namespace.create_service("Svc")
node = mesh.add_virtual_node("virtual-node",
    service_discovery=appmesh.ServiceDiscovery.cloud_map(service),
    listeners=[appmesh.VirtualNodeListener.http(
        outlier_detection=appmesh.OutlierDetection(
            base_ejection_duration=Duration.seconds(10),
            interval=Duration.seconds(30),
            max_ejection_percent=50,
            max_server_errors=5
        )
    )]
)
java
Mesh mesh;
// Cloud Map service discovery is currently required for host ejection by outlier detection
Vpc vpc = new Vpc(this, "vpc");
PrivateDnsNamespace namespace = PrivateDnsNamespace.Builder.create(this, "test-namespace")
        .vpc(vpc)
        .name("domain.local")
        .build();
Service service = namespace.createService("Svc");
VirtualNode node = mesh.addVirtualNode("virtual-node", VirtualNodeBaseProps.builder()
        .serviceDiscovery(ServiceDiscovery.cloudMap(service))
        .listeners(List.of(VirtualNodeListener.http(HttpVirtualNodeListenerOptions.builder()
                .outlierDetection(OutlierDetection.builder()
                        .baseEjectionDuration(Duration.seconds(10))
                        .interval(Duration.seconds(30))
                        .maxEjectionPercent(50)
                        .maxServerErrors(5)
                        .build())
                .build())))
        .build());
csharp
Mesh mesh;
// Cloud Map service discovery is currently required for host ejection by outlier detection
var vpc = new Vpc(this, "vpc");
var namespace = new PrivateDnsNamespace(this, "test-namespace", new PrivateDnsNamespaceProps {
    Vpc = vpc,
    Name = "domain.local"
});
var service = namespace.CreateService("Svc");
var node = mesh.AddVirtualNode("virtual-node", new VirtualNodeBaseProps {
    ServiceDiscovery = ServiceDiscovery.CloudMap(service),
    Listeners = new [] { VirtualNodeListener.Http(new HttpVirtualNodeListenerOptions {
        OutlierDetection = new OutlierDetection {
            BaseEjectionDuration = Duration.Seconds(10),
            Interval = Duration.Seconds(30),
            MaxEjectionPercent = 50,
            MaxServerErrors = 5
        }
    }) }
});
go
var mesh Mesh
// Cloud Map service discovery is currently required for host ejection by outlier detection
vpc := ec2.NewVpc(this, jsii.String("vpc"))
namespace := cloudmap.NewPrivateDnsNamespace(this, jsii.String("test-namespace"), &PrivateDnsNamespaceProps{
	Vpc: Vpc,
	Name: jsii.String("domain.local"),
})
service := namespace.CreateService(jsii.String("Svc"))
node := mesh.addVirtualNode(jsii.String("virtual-node"), &VirtualNodeBaseProps{
	ServiceDiscovery: appmesh.ServiceDiscovery_CloudMap(service),
	Listeners: []VirtualNodeListener{
		appmesh.VirtualNodeListener_Http(&HttpVirtualNodeListenerOptions{
			OutlierDetection: &OutlierDetection{
				BaseEjectionDuration: awscdk.Duration_Seconds(jsii.Number(10)),
				Interval: awscdk.Duration_*Seconds(jsii.Number(30)),
				MaxEjectionPercent: jsii.Number(50),
				MaxServerErrors: jsii.Number(5),
			},
		}),
	},
})

Adding a connection pool to a listener ​

The connectionPool property can be added to a Virtual Node listener or Virtual Gateway listener to add a request connection pool. Each listener protocol type has its own connection pool properties.

ts
// A Virtual Node with a gRPC listener with a connection pool set
declare const mesh: appmesh.Mesh;
const node = new appmesh.VirtualNode(this, 'node', {
  mesh,
  // DNS service discovery can optionally specify the DNS response type as either LOAD_BALANCER or ENDPOINTS.
  // LOAD_BALANCER means that the DNS resolver returns a loadbalanced set of endpoints,
  // whereas ENDPOINTS means that the DNS resolver is returning all the endpoints.
  // By default, the response type is assumed to be LOAD_BALANCER
  serviceDiscovery: appmesh.ServiceDiscovery.dns('node', appmesh.DnsResponseType.ENDPOINTS),
  listeners: [appmesh.VirtualNodeListener.http({
    port: 80,
    connectionPool: {
      maxConnections: 100,
      maxPendingRequests: 10,
    },
  })],
});

// A Virtual Gateway with a gRPC listener with a connection pool set
const gateway = new appmesh.VirtualGateway(this, 'gateway', {
  mesh,
  listeners: [appmesh.VirtualGatewayListener.grpc({
    port: 8080,
    connectionPool: {
      maxRequests: 10,
    },
  })],
  virtualGatewayName: 'gateway',
});
python
# A Virtual Node with a gRPC listener with a connection pool set
# mesh: appmesh.Mesh

node = appmesh.VirtualNode(self, "node",
    mesh=mesh,
    # DNS service discovery can optionally specify the DNS response type as either LOAD_BALANCER or ENDPOINTS.
    # LOAD_BALANCER means that the DNS resolver returns a loadbalanced set of endpoints,
    # whereas ENDPOINTS means that the DNS resolver is returning all the endpoints.
    # By default, the response type is assumed to be LOAD_BALANCER
    service_discovery=appmesh.ServiceDiscovery.dns("node", appmesh.DnsResponseType.ENDPOINTS),
    listeners=[appmesh.VirtualNodeListener.http(
        port=80,
        connection_pool=appmesh.HttpConnectionPool(
            max_connections=100,
            max_pending_requests=10
        )
    )]
)

# A Virtual Gateway with a gRPC listener with a connection pool set
gateway = appmesh.VirtualGateway(self, "gateway",
    mesh=mesh,
    listeners=[appmesh.VirtualGatewayListener.grpc(
        port=8080,
        connection_pool=appmesh.GrpcConnectionPool(
            max_requests=10
        )
    )],
    virtual_gateway_name="gateway"
)
java
// A Virtual Node with a gRPC listener with a connection pool set
Mesh mesh;

VirtualNode node = VirtualNode.Builder.create(this, "node")
        .mesh(mesh)
        // DNS service discovery can optionally specify the DNS response type as either LOAD_BALANCER or ENDPOINTS.
        // LOAD_BALANCER means that the DNS resolver returns a loadbalanced set of endpoints,
        // whereas ENDPOINTS means that the DNS resolver is returning all the endpoints.
        // By default, the response type is assumed to be LOAD_BALANCER
        .serviceDiscovery(ServiceDiscovery.dns("node", DnsResponseType.ENDPOINTS))
        .listeners(List.of(VirtualNodeListener.http(HttpVirtualNodeListenerOptions.builder()
                .port(80)
                .connectionPool(HttpConnectionPool.builder()
                        .maxConnections(100)
                        .maxPendingRequests(10)
                        .build())
                .build())))
        .build();

// A Virtual Gateway with a gRPC listener with a connection pool set
VirtualGateway gateway = VirtualGateway.Builder.create(this, "gateway")
        .mesh(mesh)
        .listeners(List.of(VirtualGatewayListener.grpc(GrpcGatewayListenerOptions.builder()
                .port(8080)
                .connectionPool(GrpcConnectionPool.builder()
                        .maxRequests(10)
                        .build())
                .build())))
        .virtualGatewayName("gateway")
        .build();
csharp
// A Virtual Node with a gRPC listener with a connection pool set
Mesh mesh;

var node = new VirtualNode(this, "node", new VirtualNodeProps {
    Mesh = mesh,
    // DNS service discovery can optionally specify the DNS response type as either LOAD_BALANCER or ENDPOINTS.
    // LOAD_BALANCER means that the DNS resolver returns a loadbalanced set of endpoints,
    // whereas ENDPOINTS means that the DNS resolver is returning all the endpoints.
    // By default, the response type is assumed to be LOAD_BALANCER
    ServiceDiscovery = ServiceDiscovery.Dns("node", DnsResponseType.ENDPOINTS),
    Listeners = new [] { VirtualNodeListener.Http(new HttpVirtualNodeListenerOptions {
        Port = 80,
        ConnectionPool = new HttpConnectionPool {
            MaxConnections = 100,
            MaxPendingRequests = 10
        }
    }) }
});

// A Virtual Gateway with a gRPC listener with a connection pool set
var gateway = new VirtualGateway(this, "gateway", new VirtualGatewayProps {
    Mesh = mesh,
    Listeners = new [] { VirtualGatewayListener.Grpc(new GrpcGatewayListenerOptions {
        Port = 8080,
        ConnectionPool = new GrpcConnectionPool {
            MaxRequests = 10
        }
    }) },
    VirtualGatewayName = "gateway"
});
go
// A Virtual Node with a gRPC listener with a connection pool set
var mesh Mesh

node := appmesh.NewVirtualNode(this, jsii.String("node"), &VirtualNodeProps{
	Mesh: Mesh,
	// DNS service discovery can optionally specify the DNS response type as either LOAD_BALANCER or ENDPOINTS.
	// LOAD_BALANCER means that the DNS resolver returns a loadbalanced set of endpoints,
	// whereas ENDPOINTS means that the DNS resolver is returning all the endpoints.
	// By default, the response type is assumed to be LOAD_BALANCER
	ServiceDiscovery: appmesh.ServiceDiscovery_Dns(jsii.String("node"), appmesh.DnsResponseType_ENDPOINTS),
	Listeners: []VirtualNodeListener{
		appmesh.VirtualNodeListener_Http(&HttpVirtualNodeListenerOptions{
			Port: jsii.Number(80),
			ConnectionPool: &HttpConnectionPool{
				MaxConnections: jsii.Number(100),
				MaxPendingRequests: jsii.Number(10),
			},
		}),
	},
})

// A Virtual Gateway with a gRPC listener with a connection pool set
gateway := appmesh.NewVirtualGateway(this, jsii.String("gateway"), &VirtualGatewayProps{
	Mesh: Mesh,
	Listeners: []VirtualGatewayListener{
		appmesh.VirtualGatewayListener_Grpc(&GrpcGatewayListenerOptions{
			Port: jsii.Number(8080),
			ConnectionPool: &GrpcConnectionPool{
				MaxRequests: jsii.Number(10),
			},
		}),
	},
	VirtualGatewayName: jsii.String("gateway"),
})

Adding an IP Preference to a Virtual Node ​

An ipPreference can be specified as part of a Virtual Node's service discovery. An IP preference defines how clients for this Virtual Node will interact with it.

There a four different IP preferences available to use which each specify what IP versions this Virtual Node will use and prefer.

  • IPv4_ONLY - Only use IPv4. For CloudMap service discovery, only IPv4 addresses returned from CloudMap will be used. For DNS service discovery, Envoy's DNS resolver will only resolve DNS queries for IPv4.

  • IPv4_PREFERRED - Prefer IPv4 and fall back to IPv6. For CloudMap service discovery, an IPv4 address will be used if returned from CloudMap. Otherwise, an IPv6 address will be used if available. For DNS service discovery, Envoy's DNS resolver will first attempt to resolve DNS queries using IPv4 and fall back to IPv6.

  • IPv6_ONLY - Only use IPv6. For CloudMap service discovery, only IPv6 addresses returned from CloudMap will be used. For DNS service discovery, Envoy's DNS resolver will only resolve DNS queries for IPv6.

  • IPv6_PREFERRED - Prefer IPv6 and fall back to IPv4. For CloudMap service discovery, an IPv6 address will be used if returned from CloudMap. Otherwise, an IPv4 address will be used if available. For DNS service discovery, Envoy's DNS resolver will first attempt to resolve DNS queries using IPv6 and fall back to IPv4.

ts
const mesh = new appmesh.Mesh(this, 'mesh', {
  meshName: 'mesh-with-preference',
});

// Virtual Node with DNS service discovery and an IP preference
const dnsNode = new appmesh.VirtualNode(this, 'dns-node', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.dns('test', appmesh.DnsResponseType.LOAD_BALANCER, appmesh.IpPreference.IPV4_ONLY),
});

// Virtual Node with CloudMap service discovery and an IP preference
const vpc = new ec2.Vpc(this, 'vpc');
const namespace = new cloudmap.PrivateDnsNamespace(this, 'test-namespace', {
  vpc,
  name: 'domain.local',
});
const service = namespace.createService('Svc');

const instanceAttribute : { [key: string]: string} = {};
instanceAttribute.testKey = 'testValue';

const cloudmapNode = new appmesh.VirtualNode(this, 'cloudmap-node', {
  mesh,
  serviceDiscovery: appmesh.ServiceDiscovery.cloudMap(service, instanceAttribute, appmesh.IpPreference.IPV4_ONLY),
});
python
mesh = appmesh.Mesh(self, "mesh",
    mesh_name="mesh-with-preference"
)

# Virtual Node with DNS service discovery and an IP preference
dns_node = appmesh.VirtualNode(self, "dns-node",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.dns("test", appmesh.DnsResponseType.LOAD_BALANCER, appmesh.IpPreference.IPV4_ONLY)
)

# Virtual Node with CloudMap service discovery and an IP preference
vpc = ec2.Vpc(self, "vpc")
namespace = cloudmap.PrivateDnsNamespace(self, "test-namespace",
    vpc=vpc,
    name="domain.local"
)
service = namespace.create_service("Svc")

instance_attribute = {}
instance_attribute.test_key = "testValue"

cloudmap_node = appmesh.VirtualNode(self, "cloudmap-node",
    mesh=mesh,
    service_discovery=appmesh.ServiceDiscovery.cloud_map(service, instance_attribute, appmesh.IpPreference.IPV4_ONLY)
)
java
Mesh mesh = Mesh.Builder.create(this, "mesh")
        .meshName("mesh-with-preference")
        .build();

// Virtual Node with DNS service discovery and an IP preference
VirtualNode dnsNode = VirtualNode.Builder.create(this, "dns-node")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.dns("test", DnsResponseType.LOAD_BALANCER, IpPreference.IPV4_ONLY))
        .build();

// Virtual Node with CloudMap service discovery and an IP preference
Vpc vpc = new Vpc(this, "vpc");
PrivateDnsNamespace namespace = PrivateDnsNamespace.Builder.create(this, "test-namespace")
        .vpc(vpc)
        .name("domain.local")
        .build();
Service service = namespace.createService("Svc");

Map<String, String> instanceAttribute = Map.of();
instanceAttribute.getTestKey() = "testValue";

VirtualNode cloudmapNode = VirtualNode.Builder.create(this, "cloudmap-node")
        .mesh(mesh)
        .serviceDiscovery(ServiceDiscovery.cloudMap(service, instanceAttribute, IpPreference.IPV4_ONLY))
        .build();
csharp
var mesh = new Mesh(this, "mesh", new MeshProps {
    MeshName = "mesh-with-preference"
});

// Virtual Node with DNS service discovery and an IP preference
var dnsNode = new VirtualNode(this, "dns-node", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.Dns("test", DnsResponseType.LOAD_BALANCER, IpPreference.IPV4_ONLY)
});

// Virtual Node with CloudMap service discovery and an IP preference
var vpc = new Vpc(this, "vpc");
var namespace = new PrivateDnsNamespace(this, "test-namespace", new PrivateDnsNamespaceProps {
    Vpc = vpc,
    Name = "domain.local"
});
var service = namespace.CreateService("Svc");

IDictionary<string, string> instanceAttribute = new Dictionary<string, object> { };
instanceAttribute.TestKey = "testValue";

var cloudmapNode = new VirtualNode(this, "cloudmap-node", new VirtualNodeProps {
    Mesh = mesh,
    ServiceDiscovery = ServiceDiscovery.CloudMap(service, instanceAttribute, IpPreference.IPV4_ONLY)
});
go
mesh := appmesh.NewMesh(this, jsii.String("mesh"), &MeshProps{
	MeshName: jsii.String("mesh-with-preference"),
})

// Virtual Node with DNS service discovery and an IP preference
dnsNode := appmesh.NewVirtualNode(this, jsii.String("dns-node"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_Dns(jsii.String("test"), appmesh.DnsResponseType_LOAD_BALANCER, appmesh.IpPreference_IPV4_ONLY),
})

// Virtual Node with CloudMap service discovery and an IP preference
vpc := ec2.NewVpc(this, jsii.String("vpc"))
namespace := cloudmap.NewPrivateDnsNamespace(this, jsii.String("test-namespace"), &PrivateDnsNamespaceProps{
	Vpc: Vpc,
	Name: jsii.String("domain.local"),
})
service := namespace.CreateService(jsii.String("Svc"))

instanceAttribute := map[string]interface{}{
}
instanceAttribute.testKey = "testValue"

cloudmapNode := appmesh.NewVirtualNode(this, jsii.String("cloudmap-node"), &VirtualNodeProps{
	Mesh: Mesh,
	ServiceDiscovery: appmesh.ServiceDiscovery_CloudMap(service, instanceAttribute, appmesh.IpPreference_IPV4_ONLY),
})

Adding a Route ​

A route matches requests with an associated virtual router and distributes traffic to its associated virtual nodes. The route distributes matching requests to one or more target virtual nodes with relative weighting.

The RouteSpec class lets you define protocol-specific route specifications. The tcp(), http(), http2(), and grpc() methods create a specification for the named protocols.

For HTTP-based routes, the match field can match on path (prefix, exact, or regex), HTTP method, scheme, HTTP headers, and query parameters. By default, HTTP-based routes match all requests.

For gRPC-based routes, the match field can match on service name, method name, and metadata. When specifying the method name, the service name must also be specified.

For example, here's how to add an HTTP route that matches based on a prefix of the URL path:

ts
declare const router: appmesh.VirtualRouter;
declare const node: appmesh.VirtualNode;

router.addRoute('route-http', {
  routeSpec: appmesh.RouteSpec.http({
    weightedTargets: [
      {
        virtualNode: node,
      },
    ],
    match: {
      // Path that is passed to this method must start with '/'.
      path: appmesh.HttpRoutePathMatch.startsWith('/path-to-app'),
    },
  }),
});
python
# router: appmesh.VirtualRouter
# node: appmesh.VirtualNode


router.add_route("route-http",
    route_spec=appmesh.RouteSpec.http(
        weighted_targets=[appmesh.WeightedTarget(
            virtual_node=node
        )
        ],
        match=appmesh.HttpRouteMatch(
            # Path that is passed to this method must start with '/'.
            path=appmesh.HttpRoutePathMatch.starts_with("/path-to-app")
        )
    )
)
java
VirtualRouter router;
VirtualNode node;


router.addRoute("route-http", RouteBaseProps.builder()
        .routeSpec(RouteSpec.http(HttpRouteSpecOptions.builder()
                .weightedTargets(List.of(WeightedTarget.builder()
                        .virtualNode(node)
                        .build()))
                .match(HttpRouteMatch.builder()
                        // Path that is passed to this method must start with '/'.
                        .path(HttpRoutePathMatch.startsWith("/path-to-app"))
                        .build())
                .build()))
        .build());
csharp
VirtualRouter router;
VirtualNode node;


router.AddRoute("route-http", new RouteBaseProps {
    RouteSpec = RouteSpec.Http(new HttpRouteSpecOptions {
        WeightedTargets = new [] { new WeightedTarget {
            VirtualNode = node
        } },
        Match = new HttpRouteMatch {
            // Path that is passed to this method must start with '/'.
            Path = HttpRoutePathMatch.StartsWith("/path-to-app")
        }
    })
});
go
var router VirtualRouter
var node VirtualNode


router.addRoute(jsii.String("route-http"), &RouteBaseProps{
	RouteSpec: appmesh.RouteSpec_Http(&HttpRouteSpecOptions{
		WeightedTargets: []WeightedTarget{
			&WeightedTarget{
				VirtualNode: node,
			},
		},
		Match: &HttpRouteMatch{
			// Path that is passed to this method must start with '/'.
			Path: appmesh.HttpRoutePathMatch_StartsWith(jsii.String("/path-to-app")),
		},
	}),
})

Add an HTTP2 route that matches based on exact path, method, scheme, headers, and query parameters:

ts
declare const router: appmesh.VirtualRouter;
declare const node: appmesh.VirtualNode;

router.addRoute('route-http2', {
  routeSpec: appmesh.RouteSpec.http2({
    weightedTargets: [
      {
        virtualNode: node,
      },
    ],
    match: {
      path: appmesh.HttpRoutePathMatch.exactly('/exact'),
      method: appmesh.HttpRouteMethod.POST,
      protocol: appmesh.HttpRouteProtocol.HTTPS,
      headers: [
        // All specified headers must match for the route to match.
        appmesh.HeaderMatch.valueIs('Content-Type', 'application/json'),
        appmesh.HeaderMatch.valueIsNot('Content-Type', 'application/json'),
      ],
      queryParameters: [
        // All specified query parameters must match for the route to match.
        appmesh.QueryParameterMatch.valueIs('query-field', 'value')
      ],
    },
  }),
});
python
# router: appmesh.VirtualRouter
# node: appmesh.VirtualNode


router.add_route("route-http2",
    route_spec=appmesh.RouteSpec.http2(
        weighted_targets=[appmesh.WeightedTarget(
            virtual_node=node
        )
        ],
        match=appmesh.HttpRouteMatch(
            path=appmesh.HttpRoutePathMatch.exactly("/exact"),
            method=appmesh.HttpRouteMethod.POST,
            protocol=appmesh.HttpRouteProtocol.HTTPS,
            headers=[
                # All specified headers must match for the route to match.
                appmesh.HeaderMatch.value_is("Content-Type", "application/json"),
                appmesh.HeaderMatch.value_is_not("Content-Type", "application/json")
            ],
            query_parameters=[
                # All specified query parameters must match for the route to match.
                appmesh.QueryParameterMatch.value_is("query-field", "value")
            ]
        )
    )
)
java
VirtualRouter router;
VirtualNode node;


router.addRoute("route-http2", RouteBaseProps.builder()
        .routeSpec(RouteSpec.http2(HttpRouteSpecOptions.builder()
                .weightedTargets(List.of(WeightedTarget.builder()
                        .virtualNode(node)
                        .build()))
                .match(HttpRouteMatch.builder()
                        .path(HttpRoutePathMatch.exactly("/exact"))
                        .method(HttpRouteMethod.POST)
                        .protocol(HttpRouteProtocol.HTTPS)
                        .headers(List.of(HeaderMatch.valueIs("Content-Type", "application/json"), HeaderMatch.valueIsNot("Content-Type", "application/json")))
                        .queryParameters(List.of(QueryParameterMatch.valueIs("query-field", "value")))
                        .build())
                .build()))
        .build());
csharp
VirtualRouter router;
VirtualNode node;


router.AddRoute("route-http2", new RouteBaseProps {
    RouteSpec = RouteSpec.Http2(new HttpRouteSpecOptions {
        WeightedTargets = new [] { new WeightedTarget {
            VirtualNode = node
        } },
        Match = new HttpRouteMatch {
            Path = HttpRoutePathMatch.Exactly("/exact"),
            Method = HttpRouteMethod.POST,
            Protocol = HttpRouteProtocol.HTTPS,
            Headers = new [] { HeaderMatch.ValueIs("Content-Type", "application/json"), HeaderMatch.ValueIsNot("Content-Type", "application/json") },
            QueryParameters = new [] { QueryParameterMatch.ValueIs("query-field", "value") }
        }
    })
});
go
var router VirtualRouter
var node VirtualNode


router.addRoute(jsii.String("route-http2"), &RouteBaseProps{
	RouteSpec: appmesh.RouteSpec_Http2(&HttpRouteSpecOptions{
		WeightedTargets: []WeightedTarget{
			&WeightedTarget{
				VirtualNode: node,
			},
		},
		Match: &HttpRouteMatch{
			Path: appmesh.HttpRoutePathMatch_Exactly(jsii.String("/exact")),
			Method: appmesh.HttpRouteMethod_POST,
			Protocol: appmesh.HttpRouteProtocol_HTTPS,
			Headers: []HeaderMatch{
				appmesh.HeaderMatch_ValueIs(jsii.String("Content-Type"), jsii.String("application/json")),
				appmesh.HeaderMatch_ValueIsNot(jsii.String("Content-Type"), jsii.String("application/json")),
			},
			QueryParameters: []QueryParameterMatch{
				appmesh.QueryParameterMatch_ValueIs(jsii.String("query-field"), jsii.String("value")),
			},
		},
	}),
})

Add a single route with two targets and split traffic 50/50:

ts
declare const router: appmesh.VirtualRouter;
declare const node: appmesh.VirtualNode;

router.addRoute('route-http', {
  routeSpec: appmesh.RouteSpec.http({
    weightedTargets: [
      {
        virtualNode: node,
        weight: 50,
      },
      {
        virtualNode: node,
        weight: 50,
      },
    ],
    match: {
      path: appmesh.HttpRoutePathMatch.startsWith('/path-to-app'),
    },
  }),
});
python
# router: appmesh.VirtualRouter
# node: appmesh.VirtualNode


router.add_route("route-http",
    route_spec=appmesh.RouteSpec.http(
        weighted_targets=[appmesh.WeightedTarget(
            virtual_node=node,
            weight=50
        ), appmesh.WeightedTarget(
            virtual_node=node,
            weight=50
        )
        ],
        match=appmesh.HttpRouteMatch(
            path=appmesh.HttpRoutePathMatch.starts_with("/path-to-app")
        )
    )
)
java
VirtualRouter router;
VirtualNode node;


router.addRoute("route-http", RouteBaseProps.builder()
        .routeSpec(RouteSpec.http(HttpRouteSpecOptions.builder()
                .weightedTargets(List.of(WeightedTarget.builder()
                        .virtualNode(node)
                        .weight(50)
                        .build(), WeightedTarget.builder()
                        .virtualNode(node)
                        .weight(50)
                        .build()))
                .match(HttpRouteMatch.builder()
                        .path(HttpRoutePathMatch.startsWith("/path-to-app"))
                        .build())
                .build()))
        .build());
csharp
VirtualRouter router;
VirtualNode node;


router.AddRoute("route-http", new RouteBaseProps {
    RouteSpec = RouteSpec.Http(new HttpRouteSpecOptions {
        WeightedTargets = new [] { new WeightedTarget {
            VirtualNode = node,
            Weight = 50
        }, new WeightedTarget {
            VirtualNode = node,
            Weight = 50
        } },
        Match = new HttpRouteMatch {
            Path = HttpRoutePathMatch.StartsWith("/path-to-app")
        }
    })
});
go
var router VirtualRouter
var node VirtualNode


router.addRoute(jsii.String("route-http"), &RouteBaseProps{
	RouteSpec: appmesh.RouteSpec_Http(&HttpRouteSpecOptions{
		WeightedTargets: []WeightedTarget{
			&WeightedTarget{
				VirtualNode: node,
				Weight: jsii.Number(50),
			},
			&WeightedTarget{
				VirtualNode: node,
				Weight: jsii.Number(50),
			},
		},
		Match: &HttpRouteMatch{
			Path: appmesh.HttpRoutePathMatch_StartsWith(jsii.String("/path-to-app")),
		},
	}),
})

Add an http2 route with retries:

ts
declare const router: appmesh.VirtualRouter;
declare const node: appmesh.VirtualNode;

router.addRoute('route-http2-retry', {
  routeSpec: appmesh.RouteSpec.http2({
    weightedTargets: [{ virtualNode: node }],
    retryPolicy: {
      // Retry if the connection failed
      tcpRetryEvents: [appmesh.TcpRetryEvent.CONNECTION_ERROR],
      // Retry if HTTP responds with a gateway error (502, 503, 504)
      httpRetryEvents: [appmesh.HttpRetryEvent.GATEWAY_ERROR],
      // Retry five times
      retryAttempts: 5,
      // Use a 1 second timeout per retry
      retryTimeout: Duration.seconds(1),
    },
  }),
});
python
# router: appmesh.VirtualRouter
# node: appmesh.VirtualNode


router.add_route("route-http2-retry",
    route_spec=appmesh.RouteSpec.http2(
        weighted_targets=[appmesh.WeightedTarget(virtual_node=node)],
        retry_policy=appmesh.HttpRetryPolicy(
            # Retry if the connection failed
            tcp_retry_events=[appmesh.TcpRetryEvent.CONNECTION_ERROR],
            # Retry if HTTP responds with a gateway error (502, 503, 504)
            http_retry_events=[appmesh.HttpRetryEvent.GATEWAY_ERROR],
            # Retry five times
            retry_attempts=5,
            # Use a 1 second timeout per retry
            retry_timeout=Duration.seconds(1)
        )
    )
)
java
VirtualRouter router;
VirtualNode node;


router.addRoute("route-http2-retry", RouteBaseProps.builder()
        .routeSpec(RouteSpec.http2(HttpRouteSpecOptions.builder()
                .weightedTargets(List.of(WeightedTarget.builder().virtualNode(node).build()))
                .retryPolicy(HttpRetryPolicy.builder()
                        // Retry if the connection failed
                        .tcpRetryEvents(List.of(TcpRetryEvent.CONNECTION_ERROR))
                        // Retry if HTTP responds with a gateway error (502, 503, 504)
                        .httpRetryEvents(List.of(HttpRetryEvent.GATEWAY_ERROR))
                        // Retry five times
                        .retryAttempts(5)
                        // Use a 1 second timeout per retry
                        .retryTimeout(Duration.seconds(1))
                        .build())
                .build()))
        .build());
csharp
VirtualRouter router;
VirtualNode node;


router.AddRoute("route-http2-retry", new RouteBaseProps {
    RouteSpec = RouteSpec.Http2(new HttpRouteSpecOptions {
        WeightedTargets = new [] { new WeightedTarget { VirtualNode = node } },
        RetryPolicy = new HttpRetryPolicy {
            // Retry if the connection failed
            TcpRetryEvents = new [] { TcpRetryEvent.CONNECTION_ERROR },
            // Retry if HTTP responds with a gateway error (502, 503, 504)
            HttpRetryEvents = new [] { HttpRetryEvent.GATEWAY_ERROR },
            // Retry five times
            RetryAttempts = 5,
            // Use a 1 second timeout per retry
            RetryTimeout = Duration.Seconds(1)
        }
    })
});
go
var router VirtualRouter
var node VirtualNode


router.addRoute(jsii.String("route-http2-retry"), &RouteBaseProps{
	RouteSpec: appmesh.RouteSpec_Http2(&HttpRouteSpecOptions{
		WeightedTargets: []WeightedTarget{
			&WeightedTarget{
				VirtualNode: node,
			},
		},
		RetryPolicy: &HttpRetryPolicy{
			// Retry if the connection failed
			TcpRetryEvents: []cONNECTION_ERROR{
				appmesh.TcpRetryEvent_*cONNECTION_ERROR,
			},
			// Retry if HTTP responds with a gateway error (502, 503, 504)
			HttpRetryEvents: []HttpRetryEvent{
				appmesh.HttpRetryEvent_GATEWAY_ERROR,
			},
			// Retry five times
			RetryAttempts: jsii.Number(5),
			// Use a 1 second timeout per retry
			RetryTimeout: awscdk.Duration_Seconds(jsii.Number(1)),
		},
	}),
})

Add a gRPC route with retries:

ts
declare const router: appmesh.VirtualRouter;
declare const node: appmesh.VirtualNode;

router.addRoute('route-grpc-retry', {
  routeSpec: appmesh.RouteSpec.grpc({
    weightedTargets: [{ virtualNode: node }],
    match: { serviceName: 'servicename' },
    retryPolicy: {
      tcpRetryEvents: [appmesh.TcpRetryEvent.CONNECTION_ERROR],
      httpRetryEvents: [appmesh.HttpRetryEvent.GATEWAY_ERROR],
      // Retry if gRPC responds that the request was cancelled, a resource
      // was exhausted, or if the service is unavailable
      grpcRetryEvents: [
        appmesh.GrpcRetryEvent.CANCELLED,
        appmesh.GrpcRetryEvent.RESOURCE_EXHAUSTED,
        appmesh.GrpcRetryEvent.UNAVAILABLE,
      ],
      retryAttempts: 5,
      retryTimeout: Duration.seconds(1),
    },
  }),
});
python
# router: appmesh.VirtualRouter
# node: appmesh.VirtualNode


router.add_route("route-grpc-retry",
    route_spec=appmesh.RouteSpec.grpc(
        weighted_targets=[appmesh.WeightedTarget(virtual_node=node)],
        match=appmesh.GrpcRouteMatch(service_name="servicename"),
        retry_policy=appmesh.GrpcRetryPolicy(
            tcp_retry_events=[appmesh.TcpRetryEvent.CONNECTION_ERROR],
            http_retry_events=[appmesh.HttpRetryEvent.GATEWAY_ERROR],
            # Retry if gRPC responds that the request was cancelled, a resource
            # was exhausted, or if the service is unavailable
            grpc_retry_events=[appmesh.GrpcRetryEvent.CANCELLED, appmesh.GrpcRetryEvent.RESOURCE_EXHAUSTED, appmesh.GrpcRetryEvent.UNAVAILABLE
            ],
            retry_attempts=5,
            retry_timeout=Duration.seconds(1)
        )
    )
)
java
VirtualRouter router;
VirtualNode node;


router.addRoute("route-grpc-retry", RouteBaseProps.builder()
        .routeSpec(RouteSpec.grpc(GrpcRouteSpecOptions.builder()
                .weightedTargets(List.of(WeightedTarget.builder().virtualNode(node).build()))
                .match(GrpcRouteMatch.builder().serviceName("servicename").build())
                .retryPolicy(GrpcRetryPolicy.builder()
                        .tcpRetryEvents(List.of(TcpRetryEvent.CONNECTION_ERROR))
                        .httpRetryEvents(List.of(HttpRetryEvent.GATEWAY_ERROR))
                        // Retry if gRPC responds that the request was cancelled, a resource
                        // was exhausted, or if the service is unavailable
                        .grpcRetryEvents(List.of(GrpcRetryEvent.CANCELLED, GrpcRetryEvent.RESOURCE_EXHAUSTED, GrpcRetryEvent.UNAVAILABLE))
                        .retryAttempts(5)
                        .retryTimeout(Duration.seconds(1))
                        .build())
                .build()))
        .build());
csharp
VirtualRouter router;
VirtualNode node;


router.AddRoute("route-grpc-retry", new RouteBaseProps {
    RouteSpec = RouteSpec.Grpc(new GrpcRouteSpecOptions {
        WeightedTargets = new [] { new WeightedTarget { VirtualNode = node } },
        Match = new GrpcRouteMatch { ServiceName = "servicename" },
        RetryPolicy = new GrpcRetryPolicy {
            TcpRetryEvents = new [] { TcpRetryEvent.CONNECTION_ERROR },
            HttpRetryEvents = new [] { HttpRetryEvent.GATEWAY_ERROR },
            // Retry if gRPC responds that the request was cancelled, a resource
            // was exhausted, or if the service is unavailable
            GrpcRetryEvents = new [] { GrpcRetryEvent.CANCELLED, GrpcRetryEvent.RESOURCE_EXHAUSTED, GrpcRetryEvent.UNAVAILABLE },
            RetryAttempts = 5,
            RetryTimeout = Duration.Seconds(1)
        }
    })
});
go
var router VirtualRouter
var node VirtualNode


router.addRoute(jsii.String("route-grpc-retry"), &RouteBaseProps{
	RouteSpec: appmesh.RouteSpec_Grpc(&GrpcRouteSpecOptions{
		WeightedTargets: []WeightedTarget{
			&WeightedTarget{
				VirtualNode: node,
			},
		},
		Match: &GrpcRouteMatch{
			ServiceName: jsii.String("servicename"),
		},
		RetryPolicy: &GrpcRetryPolicy{
			TcpRetryEvents: []cONNECTION_ERROR{
				appmesh.TcpRetryEvent_*cONNECTION_ERROR,
			},
			HttpRetryEvents: []HttpRetryEvent{
				appmesh.HttpRetryEvent_GATEWAY_ERROR,
			},
			// Retry if gRPC responds that the request was cancelled, a resource
			// was exhausted, or if the service is unavailable
			GrpcRetryEvents: []GrpcRetryEvent{
				appmesh.GrpcRetryEvent_CANCELLED,
				appmesh.GrpcRetryEvent_RESOURCE_EXHAUSTED,
				appmesh.GrpcRetryEvent_UNAVAILABLE,
			},
			RetryAttempts: jsii.Number(5),
			RetryTimeout: awscdk.Duration_Seconds(jsii.Number(1)),
		},
	}),
})

Add an gRPC route that matches based on method name and metadata:

ts
declare const router: appmesh.VirtualRouter;
declare const node: appmesh.VirtualNode;

router.addRoute('route-grpc-retry', {
  routeSpec: appmesh.RouteSpec.grpc({
    weightedTargets: [{ virtualNode: node }],
    match: {
      // When method name is specified, service name must be also specified.
      methodName: 'methodname',
      serviceName: 'servicename',
      metadata: [
        // All specified metadata must match for the route to match.
        appmesh.HeaderMatch.valueStartsWith('Content-Type', 'application/'),
        appmesh.HeaderMatch.valueDoesNotStartWith('Content-Type', 'text/'),
      ],
    },
  }),
});
python
# router: appmesh.VirtualRouter
# node: appmesh.VirtualNode


router.add_route("route-grpc-retry",
    route_spec=appmesh.RouteSpec.grpc(
        weighted_targets=[appmesh.WeightedTarget(virtual_node=node)],
        match=appmesh.GrpcRouteMatch(
            # When method name is specified, service name must be also specified.
            method_name="methodname",
            service_name="servicename",
            metadata=[
                # All specified metadata must match for the route to match.
                appmesh.HeaderMatch.value_starts_with("Content-Type", "application/"),
                appmesh.HeaderMatch.value_does_not_start_with("Content-Type", "text/")
            ]
        )
    )
)
java
VirtualRouter router;
VirtualNode node;


router.addRoute("route-grpc-retry", RouteBaseProps.builder()
        .routeSpec(RouteSpec.grpc(GrpcRouteSpecOptions.builder()
                .weightedTargets(List.of(WeightedTarget.builder().virtualNode(node).build()))
                .match(GrpcRouteMatch.builder()
                        // When method name is specified, service name must be also specified.
                        .methodName("methodname")
                        .serviceName("servicename")
                        .metadata(List.of(HeaderMatch.valueStartsWith("Content-Type", "application/"), HeaderMatch.valueDoesNotStartWith("Content-Type", "text/")))
                        .build())
                .build()))
        .build());
csharp
VirtualRouter router;
VirtualNode node;


router.AddRoute("route-grpc-retry", new RouteBaseProps {
    RouteSpec = RouteSpec.Grpc(new GrpcRouteSpecOptions {
        WeightedTargets = new [] { new WeightedTarget { VirtualNode = node } },
        Match = new GrpcRouteMatch {
            // When method name is specified, service name must be also specified.
            MethodName = "methodname",
            ServiceName = "servicename",
            Metadata = new [] { HeaderMatch.ValueStartsWith("Content-Type", "application/"), HeaderMatch.ValueDoesNotStartWith("Content-Type", "text/") }
        }
    })
});
go
var router VirtualRouter
var node VirtualNode


router.addRoute(jsii.String("route-grpc-retry"), &RouteBaseProps{
	RouteSpec: appmesh.RouteSpec_Grpc(&GrpcRouteSpecOptions{
		WeightedTargets: []WeightedTarget{
			&WeightedTarget{
				VirtualNode: node,
			},
		},
		Match: &GrpcRouteMatch{
			// When method name is specified, service name must be also specified.
			MethodName: jsii.String("methodname"),
			ServiceName: jsii.String("servicename"),
			Metadata: []HeaderMatch{
				appmesh.HeaderMatch_ValueStartsWith(jsii.String("Content-Type"), jsii.String("application/")),
				appmesh.HeaderMatch_ValueDoesNotStartWith(jsii.String("Content-Type"), jsii.String("text/")),
			},
		},
	}),
})

Add a gRPC route that matches based on port:

ts
declare const router: appmesh.VirtualRouter;
declare const node: appmesh.VirtualNode;

router.addRoute('route-grpc-port', {
  routeSpec: appmesh.RouteSpec.grpc({
    weightedTargets: [
      {
        virtualNode: node,
      },
    ],
    match: {
      port: 1234,
    },
  }),
});
python
# router: appmesh.VirtualRouter
# node: appmesh.VirtualNode


router.add_route("route-grpc-port",
    route_spec=appmesh.RouteSpec.grpc(
        weighted_targets=[appmesh.WeightedTarget(
            virtual_node=node
        )
        ],
        match=appmesh.GrpcRouteMatch(
            port=1234
        )
    )
)
java
VirtualRouter router;
VirtualNode node;


router.addRoute("route-grpc-port", RouteBaseProps.builder()
        .routeSpec(RouteSpec.grpc(GrpcRouteSpecOptions.builder()
                .weightedTargets(List.of(WeightedTarget.builder()
                        .virtualNode(node)
                        .build()))
                .match(GrpcRouteMatch.builder()
                        .port(1234)
                        .build())
                .build()))
        .build());
csharp
VirtualRouter router;
VirtualNode node;


router.AddRoute("route-grpc-port", new RouteBaseProps {
    RouteSpec = RouteSpec.Grpc(new GrpcRouteSpecOptions {
        WeightedTargets = new [] { new WeightedTarget {
            VirtualNode = node
        } },
        Match = new GrpcRouteMatch {
            Port = 1234
        }
    })
});
go
var router VirtualRouter
var node VirtualNode


router.addRoute(jsii.String("route-grpc-port"), &RouteBaseProps{
	RouteSpec: appmesh.RouteSpec_Grpc(&GrpcRouteSpecOptions{
		WeightedTargets: []WeightedTarget{
			&WeightedTarget{
				VirtualNode: node,
			},
		},
		Match: &GrpcRouteMatch{
			Port: jsii.Number(1234),
		},
	}),
})

Add a gRPC route with timeout:

ts
declare const router: appmesh.VirtualRouter;
declare const node: appmesh.VirtualNode;

router.addRoute('route-http', {
  routeSpec: appmesh.RouteSpec.grpc({
    weightedTargets: [
      {
        virtualNode: node,
      },
    ],
    match: {
      serviceName: 'my-service.default.svc.cluster.local',
    },
    timeout:  {
      idle : Duration.seconds(2),
      perRequest: Duration.seconds(1),
    },
  }),
});
python
# router: appmesh.VirtualRouter
# node: appmesh.VirtualNode


router.add_route("route-http",
    route_spec=appmesh.RouteSpec.grpc(
        weighted_targets=[appmesh.WeightedTarget(
            virtual_node=node
        )
        ],
        match=appmesh.GrpcRouteMatch(
            service_name="my-service.default.svc.cluster.local"
        ),
        timeout=appmesh.GrpcTimeout(
            idle=Duration.seconds(2),
            per_request=Duration.seconds(1)
        )
    )
)
java
VirtualRouter router;
VirtualNode node;


router.addRoute("route-http", RouteBaseProps.builder()
        .routeSpec(RouteSpec.grpc(GrpcRouteSpecOptions.builder()
                .weightedTargets(List.of(WeightedTarget.builder()
                        .virtualNode(node)
                        .build()))
                .match(GrpcRouteMatch.builder()
                        .serviceName("my-service.default.svc.cluster.local")
                        .build())
                .timeout(GrpcTimeout.builder()
                        .idle(Duration.seconds(2))
                        .perRequest(Duration.seconds(1))
                        .build())
                .build()))
        .build());
csharp
VirtualRouter router;
VirtualNode node;


router.AddRoute("route-http", new RouteBaseProps {
    RouteSpec = RouteSpec.Grpc(new GrpcRouteSpecOptions {
        WeightedTargets = new [] { new WeightedTarget {
            VirtualNode = node
        } },
        Match = new GrpcRouteMatch {
            ServiceName = "my-service.default.svc.cluster.local"
        },
        Timeout = new GrpcTimeout {
            Idle = Duration.Seconds(2),
            PerRequest = Duration.Seconds(1)
        }
    })
});
go
var router VirtualRouter
var node VirtualNode


router.addRoute(jsii.String("route-http"), &RouteBaseProps{
	RouteSpec: appmesh.RouteSpec_Grpc(&GrpcRouteSpecOptions{
		WeightedTargets: []WeightedTarget{
			&WeightedTarget{
				VirtualNode: node,
			},
		},
		Match: &GrpcRouteMatch{
			ServiceName: jsii.String("my-service.default.svc.cluster.local"),
		},
		Timeout: &GrpcTimeout{
			Idle: awscdk.Duration_Seconds(jsii.Number(2)),
			PerRequest: awscdk.Duration_*Seconds(jsii.Number(1)),
		},
	}),
})

Adding a Virtual Gateway ​

A virtual gateway allows resources outside your mesh to communicate with resources inside your mesh. The virtual gateway represents an Envoy proxy running in an Amazon ECS task, in a Kubernetes service, or on an Amazon EC2 instance. Unlike a virtual node, which represents Envoy running with an application, a virtual gateway represents Envoy deployed by itself.

A virtual gateway is similar to a virtual node in that it has a listener that accepts traffic for a particular port and protocol (HTTP, HTTP2, gRPC). Traffic received by the virtual gateway is directed to other services in your mesh using rules defined in gateway routes which can be added to your virtual gateway.

Create a virtual gateway with the constructor:

ts
declare const mesh: appmesh.Mesh;
const certificateAuthorityArn = 'arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012';

const gateway = new appmesh.VirtualGateway(this, 'gateway', {
  mesh: mesh,
  listeners: [appmesh.VirtualGatewayListener.http({
    port: 443,
    healthCheck: appmesh.HealthCheck.http({
      interval: Duration.seconds(10),
    }),
  })],
  backendDefaults: {
    tlsClientPolicy: {
      ports: [8080, 8081],
      validation: {
        trust: appmesh.TlsValidationTrust.acm([
          acmpca.CertificateAuthority.fromCertificateAuthorityArn(this, 'certificate', certificateAuthorityArn)]),
      },
    },
  },
  accessLog: appmesh.AccessLog.fromFilePath('/dev/stdout'),
  virtualGatewayName: 'virtualGateway',
});
python
# mesh: appmesh.Mesh

certificate_authority_arn = "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012"

gateway = appmesh.VirtualGateway(self, "gateway",
    mesh=mesh,
    listeners=[appmesh.VirtualGatewayListener.http(
        port=443,
        health_check=appmesh.HealthCheck.http(
            interval=Duration.seconds(10)
        )
    )],
    backend_defaults=appmesh.BackendDefaults(
        tls_client_policy=appmesh.TlsClientPolicy(
            ports=[8080, 8081],
            validation=appmesh.TlsValidation(
                trust=appmesh.TlsValidationTrust.acm([
                    acmpca.CertificateAuthority.from_certificate_authority_arn(self, "certificate", certificate_authority_arn)
                ])
            )
        )
    ),
    access_log=appmesh.AccessLog.from_file_path("/dev/stdout"),
    virtual_gateway_name="virtualGateway"
)
java
Mesh mesh;

String certificateAuthorityArn = "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012";

VirtualGateway gateway = VirtualGateway.Builder.create(this, "gateway")
        .mesh(mesh)
        .listeners(List.of(VirtualGatewayListener.http(HttpGatewayListenerOptions.builder()
                .port(443)
                .healthCheck(HealthCheck.http(HttpHealthCheckOptions.builder()
                        .interval(Duration.seconds(10))
                        .build()))
                .build())))
        .backendDefaults(BackendDefaults.builder()
                .tlsClientPolicy(TlsClientPolicy.builder()
                        .ports(List.of(8080, 8081))
                        .validation(TlsValidation.builder()
                                .trust(TlsValidationTrust.acm(List.of(CertificateAuthority.fromCertificateAuthorityArn(this, "certificate", certificateAuthorityArn))))
                                .build())
                        .build())
                .build())
        .accessLog(AccessLog.fromFilePath("/dev/stdout"))
        .virtualGatewayName("virtualGateway")
        .build();
csharp
Mesh mesh;

var certificateAuthorityArn = "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012";

var gateway = new VirtualGateway(this, "gateway", new VirtualGatewayProps {
    Mesh = mesh,
    Listeners = new [] { VirtualGatewayListener.Http(new HttpGatewayListenerOptions {
        Port = 443,
        HealthCheck = HealthCheck.Http(new HttpHealthCheckOptions {
            Interval = Duration.Seconds(10)
        })
    }) },
    BackendDefaults = new BackendDefaults {
        TlsClientPolicy = new TlsClientPolicy {
            Ports = new [] { 8080, 8081 },
            Validation = new TlsValidation {
                Trust = TlsValidationTrust.Acm(new [] { CertificateAuthority.FromCertificateAuthorityArn(this, "certificate", certificateAuthorityArn) })
            }
        }
    },
    AccessLog = AccessLog.FromFilePath("/dev/stdout"),
    VirtualGatewayName = "virtualGateway"
});
go
var mesh Mesh

certificateAuthorityArn := "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012"

gateway := appmesh.NewVirtualGateway(this, jsii.String("gateway"), &VirtualGatewayProps{
	Mesh: mesh,
	Listeners: []VirtualGatewayListener{
		appmesh.VirtualGatewayListener_Http(&HttpGatewayListenerOptions{
			Port: jsii.Number(443),
			HealthCheck: appmesh.HealthCheck_Http(&HttpHealthCheckOptions{
				Interval: awscdk.Duration_Seconds(jsii.Number(10)),
			}),
		}),
	},
	BackendDefaults: &BackendDefaults{
		TlsClientPolicy: &TlsClientPolicy{
			Ports: []*f64{
				jsii.Number(8080),
				jsii.Number(8081),
			},
			Validation: &TlsValidation{
				Trust: appmesh.TlsValidationTrust_Acm([]ICertificateAuthorityRef{
					acmpca.CertificateAuthority_FromCertificateAuthorityArn(this, jsii.String("certificate"), certificateAuthorityArn),
				}),
			},
		},
	},
	AccessLog: appmesh.AccessLog_FromFilePath(jsii.String("/dev/stdout")),
	VirtualGatewayName: jsii.String("virtualGateway"),
})

Add a virtual gateway directly to the mesh:

ts
declare const mesh: appmesh.Mesh;

const gateway = mesh.addVirtualGateway('gateway', {
  accessLog: appmesh.AccessLog.fromFilePath('/dev/stdout'),
  virtualGatewayName: 'virtualGateway',
    listeners: [appmesh.VirtualGatewayListener.http({
      port: 443,
      healthCheck: appmesh.HealthCheck.http({
        interval: Duration.seconds(10),
      }),
  })],
});
python
# mesh: appmesh.Mesh


gateway = mesh.add_virtual_gateway("gateway",
    access_log=appmesh.AccessLog.from_file_path("/dev/stdout"),
    virtual_gateway_name="virtualGateway",
    listeners=[appmesh.VirtualGatewayListener.http(
        port=443,
        health_check=appmesh.HealthCheck.http(
            interval=Duration.seconds(10)
        )
    )]
)
java
Mesh mesh;


VirtualGateway gateway = mesh.addVirtualGateway("gateway", VirtualGatewayBaseProps.builder()
        .accessLog(AccessLog.fromFilePath("/dev/stdout"))
        .virtualGatewayName("virtualGateway")
        .listeners(List.of(VirtualGatewayListener.http(HttpGatewayListenerOptions.builder()
                .port(443)
                .healthCheck(HealthCheck.http(HttpHealthCheckOptions.builder()
                        .interval(Duration.seconds(10))
                        .build()))
                .build())))
        .build());
csharp
Mesh mesh;


var gateway = mesh.AddVirtualGateway("gateway", new VirtualGatewayBaseProps {
    AccessLog = AccessLog.FromFilePath("/dev/stdout"),
    VirtualGatewayName = "virtualGateway",
    Listeners = new [] { VirtualGatewayListener.Http(new HttpGatewayListenerOptions {
        Port = 443,
        HealthCheck = HealthCheck.Http(new HttpHealthCheckOptions {
            Interval = Duration.Seconds(10)
        })
    }) }
});
go
var mesh Mesh


gateway := mesh.addVirtualGateway(jsii.String("gateway"), &VirtualGatewayBaseProps{
	AccessLog: appmesh.AccessLog_FromFilePath(jsii.String("/dev/stdout")),
	VirtualGatewayName: jsii.String("virtualGateway"),
	Listeners: []VirtualGatewayListener{
		appmesh.VirtualGatewayListener_Http(&HttpGatewayListenerOptions{
			Port: jsii.Number(443),
			HealthCheck: appmesh.HealthCheck_Http(&HttpHealthCheckOptions{
				Interval: awscdk.Duration_Seconds(jsii.Number(10)),
			}),
		}),
	},
})

The listeners field defaults to an HTTP Listener on port 8080 if omitted. A gateway route can be added using the gateway.addGatewayRoute() method.

The backendDefaults property, provided when creating the virtual gateway, specifies the virtual gateway's default settings for all backends.

Adding a Gateway Route ​

A gateway route is attached to a virtual gateway and routes matching traffic to an existing virtual service.

For HTTP-based gateway routes, the match field can be used to match on path (prefix, exact, or regex), HTTP method, host name, HTTP headers, and query parameters. By default, HTTP-based gateway routes match all requests.

ts
declare const gateway: appmesh.VirtualGateway;
declare const virtualService: appmesh.VirtualService;

gateway.addGatewayRoute('gateway-route-http', {
  routeSpec: appmesh.GatewayRouteSpec.http({
    routeTarget: virtualService,
    match: {
      path: appmesh.HttpGatewayRoutePathMatch.regex('regex'),
    },
  }),
});
python
# gateway: appmesh.VirtualGateway
# virtual_service: appmesh.VirtualService


gateway.add_gateway_route("gateway-route-http",
    route_spec=appmesh.GatewayRouteSpec.http(
        route_target=virtual_service,
        match=appmesh.HttpGatewayRouteMatch(
            path=appmesh.HttpGatewayRoutePathMatch.regex("regex")
        )
    )
)
java
VirtualGateway gateway;
VirtualService virtualService;


gateway.addGatewayRoute("gateway-route-http", GatewayRouteBaseProps.builder()
        .routeSpec(GatewayRouteSpec.http(HttpGatewayRouteSpecOptions.builder()
                .routeTarget(virtualService)
                .match(HttpGatewayRouteMatch.builder()
                        .path(HttpGatewayRoutePathMatch.regex("regex"))
                        .build())
                .build()))
        .build());
csharp
VirtualGateway gateway;
VirtualService virtualService;


gateway.AddGatewayRoute("gateway-route-http", new GatewayRouteBaseProps {
    RouteSpec = GatewayRouteSpec.Http(new HttpGatewayRouteSpecOptions {
        RouteTarget = virtualService,
        Match = new HttpGatewayRouteMatch {
            Path = HttpGatewayRoutePathMatch.Regex("regex")
        }
    })
});
go
var gateway VirtualGateway
var virtualService VirtualService


gateway.addGatewayRoute(jsii.String("gateway-route-http"), &GatewayRouteBaseProps{
	RouteSpec: appmesh.GatewayRouteSpec_Http(&HttpGatewayRouteSpecOptions{
		RouteTarget: virtualService,
		Match: &HttpGatewayRouteMatch{
			Path: appmesh.HttpGatewayRoutePathMatch_Regex(jsii.String("regex")),
		},
	}),
})

For gRPC-based gateway routes, the match field can be used to match on service name, host name, port and metadata.

ts
declare const gateway: appmesh.VirtualGateway;
declare const virtualService: appmesh.VirtualService;

gateway.addGatewayRoute('gateway-route-grpc', {
  routeSpec: appmesh.GatewayRouteSpec.grpc({
    routeTarget: virtualService,
    match: {
      hostname: appmesh.GatewayRouteHostnameMatch.endsWith('.example.com'),
    },
  }),
});
python
# gateway: appmesh.VirtualGateway
# virtual_service: appmesh.VirtualService


gateway.add_gateway_route("gateway-route-grpc",
    route_spec=appmesh.GatewayRouteSpec.grpc(
        route_target=virtual_service,
        match=appmesh.GrpcGatewayRouteMatch(
            hostname=appmesh.GatewayRouteHostnameMatch.ends_with(".example.com")
        )
    )
)
java
VirtualGateway gateway;
VirtualService virtualService;


gateway.addGatewayRoute("gateway-route-grpc", GatewayRouteBaseProps.builder()
        .routeSpec(GatewayRouteSpec.grpc(GrpcGatewayRouteSpecOptions.builder()
                .routeTarget(virtualService)
                .match(GrpcGatewayRouteMatch.builder()
                        .hostname(GatewayRouteHostnameMatch.endsWith(".example.com"))
                        .build())
                .build()))
        .build());
csharp
VirtualGateway gateway;
VirtualService virtualService;


gateway.AddGatewayRoute("gateway-route-grpc", new GatewayRouteBaseProps {
    RouteSpec = GatewayRouteSpec.Grpc(new GrpcGatewayRouteSpecOptions {
        RouteTarget = virtualService,
        Match = new GrpcGatewayRouteMatch {
            Hostname = GatewayRouteHostnameMatch.EndsWith(".example.com")
        }
    })
});
go
var gateway VirtualGateway
var virtualService VirtualService


gateway.addGatewayRoute(jsii.String("gateway-route-grpc"), &GatewayRouteBaseProps{
	RouteSpec: appmesh.GatewayRouteSpec_Grpc(&GrpcGatewayRouteSpecOptions{
		RouteTarget: virtualService,
		Match: &GrpcGatewayRouteMatch{
			Hostname: appmesh.GatewayRouteHostnameMatch_EndsWith(jsii.String(".example.com")),
		},
	}),
})

For HTTP based gateway routes, App Mesh automatically rewrites the matched prefix path in Gateway Route to “/”. This automatic rewrite configuration can be overwritten in following ways:

ts
declare const gateway: appmesh.VirtualGateway;
declare const virtualService: appmesh.VirtualService;

gateway.addGatewayRoute('gateway-route-http', {
  routeSpec: appmesh.GatewayRouteSpec.http({
    routeTarget: virtualService,
    match: {
      // This disables the default rewrite to '/', and retains original path.
      path: appmesh.HttpGatewayRoutePathMatch.startsWith('/path-to-app/', ''),
    },
  }),
});

gateway.addGatewayRoute('gateway-route-http-1', {
  routeSpec: appmesh.GatewayRouteSpec.http({
    routeTarget: virtualService,
    match: {
      // If the request full path is '/path-to-app/xxxxx', this rewrites the path to '/rewrittenUri/xxxxx'.
      // Please note both `prefixPathMatch` and `rewriteTo` must start and end with the `/` character.
      path: appmesh.HttpGatewayRoutePathMatch.startsWith('/path-to-app/', '/rewrittenUri/'),
    },
  }),
});
python
# gateway: appmesh.VirtualGateway
# virtual_service: appmesh.VirtualService


gateway.add_gateway_route("gateway-route-http",
    route_spec=appmesh.GatewayRouteSpec.http(
        route_target=virtual_service,
        match=appmesh.HttpGatewayRouteMatch(
            # This disables the default rewrite to '/', and retains original path.
            path=appmesh.HttpGatewayRoutePathMatch.starts_with("/path-to-app/", "")
        )
    )
)

gateway.add_gateway_route("gateway-route-http-1",
    route_spec=appmesh.GatewayRouteSpec.http(
        route_target=virtual_service,
        match=appmesh.HttpGatewayRouteMatch(
            # If the request full path is '/path-to-app/xxxxx', this rewrites the path to '/rewrittenUri/xxxxx'.
            # Please note both `prefixPathMatch` and `rewriteTo` must start and end with the `/` character.
            path=appmesh.HttpGatewayRoutePathMatch.starts_with("/path-to-app/", "/rewrittenUri/")
        )
    )
)
java
VirtualGateway gateway;
VirtualService virtualService;


gateway.addGatewayRoute("gateway-route-http", GatewayRouteBaseProps.builder()
        .routeSpec(GatewayRouteSpec.http(HttpGatewayRouteSpecOptions.builder()
                .routeTarget(virtualService)
                .match(HttpGatewayRouteMatch.builder()
                        // This disables the default rewrite to '/', and retains original path.
                        .path(HttpGatewayRoutePathMatch.startsWith("/path-to-app/", ""))
                        .build())
                .build()))
        .build());

gateway.addGatewayRoute("gateway-route-http-1", GatewayRouteBaseProps.builder()
        .routeSpec(GatewayRouteSpec.http(HttpGatewayRouteSpecOptions.builder()
                .routeTarget(virtualService)
                .match(HttpGatewayRouteMatch.builder()
                        // If the request full path is '/path-to-app/xxxxx', this rewrites the path to '/rewrittenUri/xxxxx'.
                        // Please note both `prefixPathMatch` and `rewriteTo` must start and end with the `/` character.
                        .path(HttpGatewayRoutePathMatch.startsWith("/path-to-app/", "/rewrittenUri/"))
                        .build())
                .build()))
        .build());
csharp
VirtualGateway gateway;
VirtualService virtualService;


gateway.AddGatewayRoute("gateway-route-http", new GatewayRouteBaseProps {
    RouteSpec = GatewayRouteSpec.Http(new HttpGatewayRouteSpecOptions {
        RouteTarget = virtualService,
        Match = new HttpGatewayRouteMatch {
            // This disables the default rewrite to '/', and retains original path.
            Path = HttpGatewayRoutePathMatch.StartsWith("/path-to-app/", "")
        }
    })
});

gateway.AddGatewayRoute("gateway-route-http-1", new GatewayRouteBaseProps {
    RouteSpec = GatewayRouteSpec.Http(new HttpGatewayRouteSpecOptions {
        RouteTarget = virtualService,
        Match = new HttpGatewayRouteMatch {
            // If the request full path is '/path-to-app/xxxxx', this rewrites the path to '/rewrittenUri/xxxxx'.
            // Please note both `prefixPathMatch` and `rewriteTo` must start and end with the `/` character.
            Path = HttpGatewayRoutePathMatch.StartsWith("/path-to-app/", "/rewrittenUri/")
        }
    })
});
go
var gateway VirtualGateway
var virtualService VirtualService


gateway.addGatewayRoute(jsii.String("gateway-route-http"), &GatewayRouteBaseProps{
	RouteSpec: appmesh.GatewayRouteSpec_Http(&HttpGatewayRouteSpecOptions{
		RouteTarget: virtualService,
		Match: &HttpGatewayRouteMatch{
			// This disables the default rewrite to '/', and retains original path.
			Path: appmesh.HttpGatewayRoutePathMatch_StartsWith(jsii.String("/path-to-app/"), jsii.String("")),
		},
	}),
})

gateway.addGatewayRoute(jsii.String("gateway-route-http-1"), &GatewayRouteBaseProps{
	RouteSpec: appmesh.GatewayRouteSpec_*Http(&HttpGatewayRouteSpecOptions{
		RouteTarget: virtualService,
		Match: &HttpGatewayRouteMatch{
			// If the request full path is '/path-to-app/xxxxx', this rewrites the path to '/rewrittenUri/xxxxx'.
			// Please note both `prefixPathMatch` and `rewriteTo` must start and end with the `/` character.
			Path: appmesh.HttpGatewayRoutePathMatch_*StartsWith(jsii.String("/path-to-app/"), jsii.String("/rewrittenUri/")),
		},
	}),
})

If matching other path (exact or regex), only specific rewrite path can be specified. Unlike startsWith() method above, no default rewrite is performed.

ts
declare const gateway: appmesh.VirtualGateway;
declare const virtualService: appmesh.VirtualService;

gateway.addGatewayRoute('gateway-route-http-2', {
  routeSpec: appmesh.GatewayRouteSpec.http({
    routeTarget: virtualService,
    match: {
      // This rewrites the path from '/test' to '/rewrittenPath'.
      path: appmesh.HttpGatewayRoutePathMatch.exactly('/test', '/rewrittenPath'),
    },
  }),
});
python
# gateway: appmesh.VirtualGateway
# virtual_service: appmesh.VirtualService


gateway.add_gateway_route("gateway-route-http-2",
    route_spec=appmesh.GatewayRouteSpec.http(
        route_target=virtual_service,
        match=appmesh.HttpGatewayRouteMatch(
            # This rewrites the path from '/test' to '/rewrittenPath'.
            path=appmesh.HttpGatewayRoutePathMatch.exactly("/test", "/rewrittenPath")
        )
    )
)
java
VirtualGateway gateway;
VirtualService virtualService;


gateway.addGatewayRoute("gateway-route-http-2", GatewayRouteBaseProps.builder()
        .routeSpec(GatewayRouteSpec.http(HttpGatewayRouteSpecOptions.builder()
                .routeTarget(virtualService)
                .match(HttpGatewayRouteMatch.builder()
                        // This rewrites the path from '/test' to '/rewrittenPath'.
                        .path(HttpGatewayRoutePathMatch.exactly("/test", "/rewrittenPath"))
                        .build())
                .build()))
        .build());
csharp
VirtualGateway gateway;
VirtualService virtualService;


gateway.AddGatewayRoute("gateway-route-http-2", new GatewayRouteBaseProps {
    RouteSpec = GatewayRouteSpec.Http(new HttpGatewayRouteSpecOptions {
        RouteTarget = virtualService,
        Match = new HttpGatewayRouteMatch {
            // This rewrites the path from '/test' to '/rewrittenPath'.
            Path = HttpGatewayRoutePathMatch.Exactly("/test", "/rewrittenPath")
        }
    })
});
go
var gateway VirtualGateway
var virtualService VirtualService


gateway.addGatewayRoute(jsii.String("gateway-route-http-2"), &GatewayRouteBaseProps{
	RouteSpec: appmesh.GatewayRouteSpec_Http(&HttpGatewayRouteSpecOptions{
		RouteTarget: virtualService,
		Match: &HttpGatewayRouteMatch{
			// This rewrites the path from '/test' to '/rewrittenPath'.
			Path: appmesh.HttpGatewayRoutePathMatch_Exactly(jsii.String("/test"), jsii.String("/rewrittenPath")),
		},
	}),
})

For HTTP/gRPC based routes, App Mesh automatically rewrites the original request received at the Virtual Gateway to the destination Virtual Service name. This default host name rewrite can be configured by specifying the rewrite rule as one of the match property:

ts
declare const gateway: appmesh.VirtualGateway;
declare const virtualService: appmesh.VirtualService;

gateway.addGatewayRoute('gateway-route-grpc', {
  routeSpec: appmesh.GatewayRouteSpec.grpc({
    routeTarget: virtualService,
    match: {
      hostname: appmesh.GatewayRouteHostnameMatch.exactly('example.com'),
      // This disables the default rewrite to virtual service name and retain original request.
      rewriteRequestHostname: false,
    },
  }),
});
python
# gateway: appmesh.VirtualGateway
# virtual_service: appmesh.VirtualService


gateway.add_gateway_route("gateway-route-grpc",
    route_spec=appmesh.GatewayRouteSpec.grpc(
        route_target=virtual_service,
        match=appmesh.GrpcGatewayRouteMatch(
            hostname=appmesh.GatewayRouteHostnameMatch.exactly("example.com"),
            # This disables the default rewrite to virtual service name and retain original request.
            rewrite_request_hostname=False
        )
    )
)
java
VirtualGateway gateway;
VirtualService virtualService;


gateway.addGatewayRoute("gateway-route-grpc", GatewayRouteBaseProps.builder()
        .routeSpec(GatewayRouteSpec.grpc(GrpcGatewayRouteSpecOptions.builder()
                .routeTarget(virtualService)
                .match(GrpcGatewayRouteMatch.builder()
                        .hostname(GatewayRouteHostnameMatch.exactly("example.com"))
                        // This disables the default rewrite to virtual service name and retain original request.
                        .rewriteRequestHostname(false)
                        .build())
                .build()))
        .build());
csharp
VirtualGateway gateway;
VirtualService virtualService;


gateway.AddGatewayRoute("gateway-route-grpc", new GatewayRouteBaseProps {
    RouteSpec = GatewayRouteSpec.Grpc(new GrpcGatewayRouteSpecOptions {
        RouteTarget = virtualService,
        Match = new GrpcGatewayRouteMatch {
            Hostname = GatewayRouteHostnameMatch.Exactly("example.com"),
            // This disables the default rewrite to virtual service name and retain original request.
            RewriteRequestHostname = false
        }
    })
});
go
var gateway VirtualGateway
var virtualService VirtualService


gateway.addGatewayRoute(jsii.String("gateway-route-grpc"), &GatewayRouteBaseProps{
	RouteSpec: appmesh.GatewayRouteSpec_Grpc(&GrpcGatewayRouteSpecOptions{
		RouteTarget: virtualService,
		Match: &GrpcGatewayRouteMatch{
			Hostname: appmesh.GatewayRouteHostnameMatch_Exactly(jsii.String("example.com")),
			// This disables the default rewrite to virtual service name and retain original request.
			RewriteRequestHostname: jsii.Boolean(false),
		},
	}),
})

Importing Resources ​

Each App Mesh resource class comes with two static methods, from<Resource>Arn and from<Resource>Attributes (where <Resource> is replaced with the resource name, such as VirtualNode) for importing a reference to an existing App Mesh resource. These imported resources can be used with other resources in your mesh as if they were defined directly in your CDK application.

ts
const arn = 'arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh/virtualNode/testNode';
appmesh.VirtualNode.fromVirtualNodeArn(this, 'importedVirtualNode', arn);
python
arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh/virtualNode/testNode"
appmesh.VirtualNode.from_virtual_node_arn(self, "importedVirtualNode", arn)
java
String arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh/virtualNode/testNode";
VirtualNode.fromVirtualNodeArn(this, "importedVirtualNode", arn);
csharp
var arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh/virtualNode/testNode";
VirtualNode.FromVirtualNodeArn(this, "importedVirtualNode", arn);
go
arn := "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh/virtualNode/testNode"
appmesh.VirtualNode_FromVirtualNodeArn(this, jsii.String("importedVirtualNode"), arn)
ts
const virtualNodeName = 'my-virtual-node';
appmesh.VirtualNode.fromVirtualNodeAttributes(this, 'imported-virtual-node', {
  mesh: appmesh.Mesh.fromMeshName(this, 'Mesh', 'testMesh'),
  virtualNodeName: virtualNodeName,
});
python
virtual_node_name = "my-virtual-node"
appmesh.VirtualNode.from_virtual_node_attributes(self, "imported-virtual-node",
    mesh=appmesh.Mesh.from_mesh_name(self, "Mesh", "testMesh"),
    virtual_node_name=virtual_node_name
)
java
String virtualNodeName = "my-virtual-node";
VirtualNode.fromVirtualNodeAttributes(this, "imported-virtual-node", VirtualNodeAttributes.builder()
        .mesh(Mesh.fromMeshName(this, "Mesh", "testMesh"))
        .virtualNodeName(virtualNodeName)
        .build());
csharp
var virtualNodeName = "my-virtual-node";
VirtualNode.FromVirtualNodeAttributes(this, "imported-virtual-node", new VirtualNodeAttributes {
    Mesh = Mesh.FromMeshName(this, "Mesh", "testMesh"),
    VirtualNodeName = virtualNodeName
});
go
virtualNodeName := "my-virtual-node"
appmesh.VirtualNode_FromVirtualNodeAttributes(this, jsii.String("imported-virtual-node"), &VirtualNodeAttributes{
	Mesh: appmesh.Mesh_FromMeshName(this, jsii.String("Mesh"), jsii.String("testMesh")),
	VirtualNodeName: virtualNodeName,
})

To import a mesh, again there are two static methods, fromMeshArn and fromMeshName.

ts
const arn = 'arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh';
appmesh.Mesh.fromMeshArn(this, 'imported-mesh', arn);
python
arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh"
appmesh.Mesh.from_mesh_arn(self, "imported-mesh", arn)
java
String arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh";
Mesh.fromMeshArn(this, "imported-mesh", arn);
csharp
var arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh";
Mesh.FromMeshArn(this, "imported-mesh", arn);
go
arn := "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh"
appmesh.Mesh_FromMeshArn(this, jsii.String("imported-mesh"), arn)
ts
appmesh.Mesh.fromMeshName(this, 'imported-mesh', 'abc');
python
appmesh.Mesh.from_mesh_name(self, "imported-mesh", "abc")
java
Mesh.fromMeshName(this, "imported-mesh", "abc");
csharp
Mesh.FromMeshName(this, "imported-mesh", "abc");
go
appmesh.Mesh_FromMeshName(this, jsii.String("imported-mesh"), jsii.String("abc"))

IAM Grants ​

VirtualNode and VirtualGateway have a grants property that provides a streamAggregatedResources methods that grant identities that are running Envoy access to stream generated config from App Mesh.

ts
declare const mesh: appmesh.Mesh;
const gateway = new appmesh.VirtualGateway(this, 'testGateway', { mesh });
const envoyUser = new iam.User(this, 'envoyUser');

/**
 * This will grant `appmesh:StreamAggregatedResources` ONLY for this gateway.
 */
gateway.grants.streamAggregatedResources(envoyUser)
python
# mesh: appmesh.Mesh

gateway = appmesh.VirtualGateway(self, "testGateway", mesh=mesh)
envoy_user = iam.User(self, "envoyUser")

#
# This will grant `appmesh:StreamAggregatedResources` ONLY for this gateway.
#
gateway.grants.stream_aggregated_resources(envoy_user)
java
Mesh mesh;

VirtualGateway gateway = VirtualGateway.Builder.create(this, "testGateway").mesh(mesh).build();
User envoyUser = new User(this, "envoyUser");

/**
 * This will grant `appmesh:StreamAggregatedResources` ONLY for this gateway.
 */
gateway.grants.streamAggregatedResources(envoyUser);
csharp
Mesh mesh;

var gateway = new VirtualGateway(this, "testGateway", new VirtualGatewayProps { Mesh = mesh });
var envoyUser = new User(this, "envoyUser");

/**
 * This will grant `appmesh:StreamAggregatedResources` ONLY for this gateway.
 */
gateway.Grants.StreamAggregatedResources(envoyUser);
go
var mesh Mesh

gateway := appmesh.NewVirtualGateway(this, jsii.String("testGateway"), &VirtualGatewayProps{
	Mesh: Mesh,
})
envoyUser := iam.NewUser(this, jsii.String("envoyUser"))

/**
 * This will grant `appmesh:StreamAggregatedResources` ONLY for this gateway.
 */
gateway.grants.StreamAggregatedResources(envoyUser)

Adding Resources to shared meshes ​

A shared mesh allows resources created by different accounts to communicate with each other in the same mesh:

ts
// This is the ARN for the mesh from different AWS IAM account ID.
// Ensure mesh is properly shared with your account. For more details, see: https://github.com/aws/aws-cdk/issues/15404
const arn = 'arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh';
const sharedMesh = appmesh.Mesh.fromMeshArn(this, 'imported-mesh', arn);

// This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.
new appmesh.VirtualNode(this, 'test-node', {
  mesh: sharedMesh,
});
python
# This is the ARN for the mesh from different AWS IAM account ID.
# Ensure mesh is properly shared with your account. For more details, see: https://github.com/aws/aws-cdk/issues/15404
arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh"
shared_mesh = appmesh.Mesh.from_mesh_arn(self, "imported-mesh", arn)

# This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.
appmesh.VirtualNode(self, "test-node",
    mesh=shared_mesh
)
java
// This is the ARN for the mesh from different AWS IAM account ID.
// Ensure mesh is properly shared with your account. For more details, see: https://github.com/aws/aws-cdk/issues/15404
String arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh";
IMesh sharedMesh = Mesh.fromMeshArn(this, "imported-mesh", arn);

// This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.
// This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.
VirtualNode.Builder.create(this, "test-node")
        .mesh(sharedMesh)
        .build();
csharp
// This is the ARN for the mesh from different AWS IAM account ID.
// Ensure mesh is properly shared with your account. For more details, see: https://github.com/aws/aws-cdk/issues/15404
var arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh";
var sharedMesh = Mesh.FromMeshArn(this, "imported-mesh", arn);

// This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.
// This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.
new VirtualNode(this, "test-node", new VirtualNodeProps {
    Mesh = sharedMesh
});
go
// This is the ARN for the mesh from different AWS IAM account ID.
// Ensure mesh is properly shared with your account. For more details, see: https://github.com/aws/aws-cdk/issues/15404
arn := "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh"
sharedMesh := appmesh.Mesh_FromMeshArn(this, jsii.String("imported-mesh"), arn)

// This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.
// This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.
appmesh.NewVirtualNode(this, jsii.String("test-node"), &VirtualNodeProps{
	Mesh: sharedMesh,
})

Types ​

Constructs (L2) ​

  • GatewayRoute Construct (L2)
    GatewayRoute represents a new or existing gateway route attached to a VirtualGateway and Mesh.
  • Mesh Construct (L2)
    Define a new AppMesh mesh.
  • Route Construct (L2)
    Route represents a new or existing route attached to a VirtualRouter and Mesh.
  • VirtualGateway Construct (L2)
    VirtualGateway represents a newly defined App Mesh Virtual Gateway.
  • VirtualNode Construct (L2)
    VirtualNode represents a newly defined AppMesh VirtualNode.
  • VirtualRouter Construct (L2)
  • VirtualService Construct (L2)
    VirtualService represents a service inside an AppMesh.

Constructs (L1) ​

Classes ​

Structs ​

Enums ​

  • DnsResponseType Enum
    Enum of DNS service discovery response type.
  • GrpcRetryEvent Enum
    gRPC events.
  • HttpRetryEvent Enum
    HTTP events on which to retry.
  • HttpRouteMethod Enum
    Supported values for matching routes based on the HTTP request method.
  • HttpRouteProtocol Enum
    Supported :scheme options for HTTP2.
  • IpPreference Enum
    Enum of supported IP preferences.
  • MeshFilterType Enum
    A utility enum defined for the egressFilter type property, the default of DROP_ALL, allows traffic only to other resources inside the mesh, or API calls to amazon resources.
  • TcpRetryEvent Enum
    TCP events on which you may retry.
  • TlsMode Enum
    Enum of supported TLS modes.

Interfaces ​

  • IGatewayRoute Interface
    Interface for which all GatewayRoute based classes MUST implement.
  • IMesh Interface
    Interface which all Mesh based classes MUST implement.
  • IRoute Interface
    Interface for which all Route based classes MUST implement.
  • IVirtualGateway Interface
    Interface which all Virtual Gateway based classes must implement.
  • IVirtualNode Interface
    Interface which all VirtualNode based classes must implement.
  • IVirtualRouter Interface
    Interface which all VirtualRouter based classes MUST implement.
  • IVirtualService Interface
    Represents the interface which all VirtualService based classes MUST implement.

Facades ​