# AWS App Mesh Construct Library
<!--BEGIN STABILITY BANNER-->---
![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)
![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)
---
<!--END STABILITY BANNER-->
AWS App Mesh is a service mesh based on the [Envoy](https://www.envoyproxy.io/) 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](https://docs.aws.amazon.com/app-mesh/index.html).
## Create the App and Stack
```python
app = cdk.App()
stack = cdk.Stack(app, "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](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appmesh-mesh-egressfilter.html) for more info on egress filters.
```python
mesh = appmesh.Mesh(self, "AppMesh",
mesh_name="myAwsMesh"
)
```
The mesh can instead be created with the `ALLOW_ALL` egress filter by providing the `egressFilter` property.
```python
mesh = appmesh.Mesh(self, "AppMesh",
mesh_name="myAwsMesh",
egress_filter=appmesh.MeshFilterType.ALLOW_ALL
)
```
## 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.
```python
# mesh: appmesh.Mesh
router = mesh.add_virtual_router("router",
listeners=[appmesh.VirtualRouterListener.http(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:
```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)]
)
```
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:
```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)
)
```
Adding a virtual node as the provider:
```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)
)
```
## 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.
```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=cdk.Duration.seconds(5), # minimum
path="/health-check-path",
timeout=cdk.Duration.seconds(2), # minimum
unhealthy_threshold=2
)
)],
access_log=appmesh.AccessLog.from_file_path("/dev/stdout")
)
```
Create a `VirtualNode` with the constructor and add tags.
```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")
)
cdk.Tags.of(node).add("Environment", "Dev")
```
Create a `VirtualNode` with the constructor and add backend virtual service.
```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=cdk.Duration.seconds(5),
path="/ping",
timeout=cdk.Duration.seconds(2),
unhealthy_threshold=2
),
timeout=appmesh.HttpTimeout(
idle=cdk.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))
```
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:
```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))
```
### 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`).
```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"
)
```
### 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.
```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")
)
)
)
```
### 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.
```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=cdk.Duration.seconds(10),
interval=cdk.Duration.seconds(30),
max_ejection_percent=50,
max_server_errors=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.
```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"
)
```
## 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:
```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")
)
)
)
```
Add an HTTP2 route that matches based on exact path, method, scheme, headers, and query parameters:
```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")
]
)
)
)
```
Add a single route with two targets and split traffic 50/50:
```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")
)
)
)
```
Add an http2 route with retries:
```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=cdk.Duration.seconds(1)
)
)
)
```
Add a gRPC route with retries:
```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=cdk.Duration.seconds(1)
)
)
)
```
Add an gRPC route that matches based on method name and metadata:
```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/")
]
)
)
)
```
Add a gRPC route with timeout:
```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=cdk.Duration.seconds(2),
per_request=cdk.Duration.seconds(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:
```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=cdk.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"
)
```
Add a virtual gateway directly to the mesh:
```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=cdk.Duration.seconds(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.
```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")
)
)
)
```
For gRPC-based gateway routes, the `match` field can be used to match on service name, host name, and metadata.
```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")
)
)
)
```
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:
```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/")
)
)
)
```
If matching other path (exact or regex), only specific rewrite path can be specified.
Unlike `startsWith()` method above, no default rewrite is performed.
```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")
)
)
)
```
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:
```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
)
)
)
```
## 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.
```python
arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh/virtualNode/testNode"
appmesh.VirtualNode.from_virtual_node_arn(self, "importedVirtualNode", arn)
```
```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
)
```
To import a mesh, again there are two static methods, `fromMeshArn` and `fromMeshName`.
```python
arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh"
appmesh.Mesh.from_mesh_arn(self, "imported-mesh", arn)
```
```python
appmesh.Mesh.from_mesh_name(self, "imported-mesh", "abc")
```
## IAM Grants
`VirtualNode` and `VirtualGateway` provide `grantStreamAggregatedResources` methods that grant identities that are running
Envoy access to stream generated config from App Mesh.
```python
# mesh: appmesh.Mesh
gateway = appmesh.VirtualGateway(self, "testGateway", mesh=mesh)
envoy_user = iam.User(self, "envoyUser")
#
# This will grant `grantStreamAggregatedResources` ONLY for this gateway.
#
gateway.grant_stream_aggregated_resources(envoy_user)
```
## Adding Resources to shared meshes
A shared mesh allows resources created by different accounts to communicate with each other in the same mesh:
```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
)
```
Raw data
{
"_id": null,
"home_page": "https://github.com/aws/aws-cdk",
"name": "aws-cdk.aws-appmesh",
"maintainer": "",
"docs_url": null,
"requires_python": "~=3.7",
"maintainer_email": "",
"keywords": "",
"author": "Amazon Web Services",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/2f/2c/73218eb8b6cd0ae5983b0105ffe4deea887123aee329e7f312da97f12eff/aws-cdk.aws-appmesh-1.203.0.tar.gz",
"platform": null,
"description": "# AWS App Mesh Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)\n\n![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)\n\n---\n<!--END STABILITY BANNER-->\n\nAWS App Mesh is a service mesh based on the [Envoy](https://www.envoyproxy.io/) 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.\n\nApp Mesh gives you consistent visibility and network traffic controls for every microservice in an application.\n\nApp 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.\n\nFor further information on **AWS App Mesh**, visit the [AWS App Mesh Documentation](https://docs.aws.amazon.com/app-mesh/index.html).\n\n## Create the App and Stack\n\n```python\napp = cdk.App()\nstack = cdk.Stack(app, \"stack\")\n```\n\n## Creating the Mesh\n\nA service mesh is a logical boundary for network traffic between the services that reside within it.\n\nAfter 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.\n\nThe following example creates the `AppMesh` service mesh with the default egress filter of `DROP_ALL`. See [the AWS CloudFormation `EgressFilter` resource](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appmesh-mesh-egressfilter.html) for more info on egress filters.\n\n```python\nmesh = appmesh.Mesh(self, \"AppMesh\",\n mesh_name=\"myAwsMesh\"\n)\n```\n\nThe mesh can instead be created with the `ALLOW_ALL` egress filter by providing the `egressFilter` property.\n\n```python\nmesh = appmesh.Mesh(self, \"AppMesh\",\n mesh_name=\"myAwsMesh\",\n egress_filter=appmesh.MeshFilterType.ALLOW_ALL\n)\n```\n\n## Adding VirtualRouters\n\nA *mesh* uses *virtual routers* as logical units to route requests to *virtual nodes*.\n\nVirtual routers handle traffic for one or more virtual services within your mesh.\nAfter you create a virtual router, you can create and associate routes to your virtual router that direct incoming requests to different virtual nodes.\n\n```python\n# mesh: appmesh.Mesh\n\nrouter = mesh.add_virtual_router(\"router\",\n listeners=[appmesh.VirtualRouterListener.http(8080)]\n)\n```\n\nNote that creating the router using the `addVirtualRouter()` method places it in the same stack as the mesh\n(which might be different from the current stack).\nThe router can also be created using the `VirtualRouter` constructor (passing in the mesh) instead of calling the `addVirtualRouter()` method.\nThis 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:\n\n```python\n# infra_stack: cdk.Stack\n# app_stack: cdk.Stack\n\n\nmesh = appmesh.Mesh(infra_stack, \"AppMesh\",\n mesh_name=\"myAwsMesh\",\n egress_filter=appmesh.MeshFilterType.ALLOW_ALL\n)\n\n# the VirtualRouter will belong to 'appStack',\n# even though the Mesh belongs to 'infraStack'\nrouter = appmesh.VirtualRouter(app_stack, \"router\",\n mesh=mesh, # notice that mesh is a required property when creating a router with the 'new' statement\n listeners=[appmesh.VirtualRouterListener.http(8081)]\n)\n```\n\nThe same is true for other `add*()` methods in the App Mesh construct library.\n\nThe `VirtualRouterListener` class lets you define protocol-specific listeners.\nThe `http()`, `http2()`, `grpc()` and `tcp()` methods create listeners for the named protocols.\nThey accept a single parameter that defines the port to on which requests will be matched.\nThe port parameter defaults to 8080 if omitted.\n\n## Adding a VirtualService\n\nA *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.\n\nWe recommend that you use the service discovery name of the real service that you're targeting (such as `my-service.default.svc.cluster.local`).\n\nWhen creating a virtual service:\n\n* If you want the virtual service to spread traffic across multiple virtual nodes, specify a virtual router.\n* If you want the virtual service to reach a virtual node directly, without a virtual router, specify a virtual node.\n\nAdding a virtual router as the provider:\n\n```python\n# router: appmesh.VirtualRouter\n\n\nappmesh.VirtualService(self, \"virtual-service\",\n virtual_service_name=\"my-service.default.svc.cluster.local\", # optional\n virtual_service_provider=appmesh.VirtualServiceProvider.virtual_router(router)\n)\n```\n\nAdding a virtual node as the provider:\n\n```python\n# node: appmesh.VirtualNode\n\n\nappmesh.VirtualService(self, \"virtual-service\",\n virtual_service_name=\"my-service.default.svc.cluster.local\", # optional\n virtual_service_provider=appmesh.VirtualServiceProvider.virtual_node(node)\n)\n```\n\n## Adding a VirtualNode\n\nA *virtual node* acts as a logical pointer to a particular task group, such as an Amazon ECS service or a Kubernetes deployment.\n\nWhen 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*.\n\nThe 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.\n\n> **Note**\n> 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.\n\n```python\n# mesh: appmesh.Mesh\nvpc = ec2.Vpc(self, \"vpc\")\nnamespace = cloudmap.PrivateDnsNamespace(self, \"test-namespace\",\n vpc=vpc,\n name=\"domain.local\"\n)\nservice = namespace.create_service(\"Svc\")\nnode = mesh.add_virtual_node(\"virtual-node\",\n service_discovery=appmesh.ServiceDiscovery.cloud_map(service),\n listeners=[appmesh.VirtualNodeListener.http(\n port=8081,\n health_check=appmesh.HealthCheck.http(\n healthy_threshold=3,\n interval=cdk.Duration.seconds(5), # minimum\n path=\"/health-check-path\",\n timeout=cdk.Duration.seconds(2), # minimum\n unhealthy_threshold=2\n )\n )],\n access_log=appmesh.AccessLog.from_file_path(\"/dev/stdout\")\n)\n```\n\nCreate a `VirtualNode` with the constructor and add tags.\n\n```python\n# mesh: appmesh.Mesh\n# service: cloudmap.Service\n\n\nnode = appmesh.VirtualNode(self, \"node\",\n mesh=mesh,\n service_discovery=appmesh.ServiceDiscovery.cloud_map(service),\n listeners=[appmesh.VirtualNodeListener.http(\n port=8080,\n health_check=appmesh.HealthCheck.http(\n healthy_threshold=3,\n interval=cdk.Duration.seconds(5),\n path=\"/ping\",\n timeout=cdk.Duration.seconds(2),\n unhealthy_threshold=2\n ),\n timeout=appmesh.HttpTimeout(\n idle=cdk.Duration.seconds(5)\n )\n )],\n backend_defaults=appmesh.BackendDefaults(\n tls_client_policy=appmesh.TlsClientPolicy(\n validation=appmesh.TlsValidation(\n trust=appmesh.TlsValidationTrust.file(\"/keys/local_cert_chain.pem\")\n )\n )\n ),\n access_log=appmesh.AccessLog.from_file_path(\"/dev/stdout\")\n)\n\ncdk.Tags.of(node).add(\"Environment\", \"Dev\")\n```\n\nCreate a `VirtualNode` with the constructor and add backend virtual service.\n\n```python\n# mesh: appmesh.Mesh\n# router: appmesh.VirtualRouter\n# service: cloudmap.Service\n\n\nnode = appmesh.VirtualNode(self, \"node\",\n mesh=mesh,\n service_discovery=appmesh.ServiceDiscovery.cloud_map(service),\n listeners=[appmesh.VirtualNodeListener.http(\n port=8080,\n health_check=appmesh.HealthCheck.http(\n healthy_threshold=3,\n interval=cdk.Duration.seconds(5),\n path=\"/ping\",\n timeout=cdk.Duration.seconds(2),\n unhealthy_threshold=2\n ),\n timeout=appmesh.HttpTimeout(\n idle=cdk.Duration.seconds(5)\n )\n )],\n access_log=appmesh.AccessLog.from_file_path(\"/dev/stdout\")\n)\n\nvirtual_service = appmesh.VirtualService(self, \"service-1\",\n virtual_service_provider=appmesh.VirtualServiceProvider.virtual_router(router),\n virtual_service_name=\"service1.domain.local\"\n)\n\nnode.add_backend(appmesh.Backend.virtual_service(virtual_service))\n```\n\nThe `listeners` property can be left blank and added later with the `node.addListener()` method. The `serviceDiscovery` property must be specified when specifying a listener.\n\nThe `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.\n\nThe `backendDefaults` property is added to the node while creating the virtual node. These are the virtual node's default settings for all backends.\n\nThe `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:\n\n```python\n# mesh: appmesh.Mesh\n\n\nnode = appmesh.VirtualNode(self, \"node\",\n mesh=mesh,\n service_discovery=appmesh.ServiceDiscovery.dns(\"node\")\n)\n\nvirtual_service = appmesh.VirtualService(self, \"service-1\",\n virtual_service_provider=appmesh.VirtualServiceProvider.virtual_node(node),\n virtual_service_name=\"service1.domain.local\"\n)\n\nnode.add_backend(appmesh.Backend.virtual_service(virtual_service))\n```\n\n### Adding TLS to a listener\n\nThe `tls` property specifies TLS configuration when creating a listener for a virtual node or a virtual gateway.\nProvide the TLS certificate to the proxy in one of the following ways:\n\n* A certificate from AWS Certificate Manager (ACM).\n* A customer-provided certificate (specify a `certificateChain` path file and a `privateKey` file path).\n* A certificate provided by a Secrets Discovery Service (SDS) endpoint over local Unix Domain Socket (specify its `secretName`).\n\n```python\n# A Virtual Node with listener TLS from an ACM provided certificate\n# cert: certificatemanager.Certificate\n# mesh: appmesh.Mesh\n\n\nnode = appmesh.VirtualNode(self, \"node\",\n mesh=mesh,\n service_discovery=appmesh.ServiceDiscovery.dns(\"node\"),\n listeners=[appmesh.VirtualNodeListener.grpc(\n port=80,\n tls=appmesh.ListenerTlsOptions(\n mode=appmesh.TlsMode.STRICT,\n certificate=appmesh.TlsCertificate.acm(cert)\n )\n )]\n)\n\n# A Virtual Gateway with listener TLS from a customer provided file certificate\ngateway = appmesh.VirtualGateway(self, \"gateway\",\n mesh=mesh,\n listeners=[appmesh.VirtualGatewayListener.grpc(\n port=8080,\n tls=appmesh.ListenerTlsOptions(\n mode=appmesh.TlsMode.STRICT,\n certificate=appmesh.TlsCertificate.file(\"path/to/certChain\", \"path/to/privateKey\")\n )\n )],\n virtual_gateway_name=\"gateway\"\n)\n\n# A Virtual Gateway with listener TLS from a SDS provided certificate\ngateway2 = appmesh.VirtualGateway(self, \"gateway2\",\n mesh=mesh,\n listeners=[appmesh.VirtualGatewayListener.http2(\n port=8080,\n tls=appmesh.ListenerTlsOptions(\n mode=appmesh.TlsMode.STRICT,\n certificate=appmesh.TlsCertificate.sds(\"secrete_certificate\")\n )\n )],\n virtual_gateway_name=\"gateway2\"\n)\n```\n\n### Adding mutual TLS authentication\n\nMutual TLS authentication is an optional component of TLS that offers two-way peer authentication.\nTo enable mutual TLS authentication, add the `mutualTlsCertificate` property to TLS client policy and/or the `mutualTlsValidation` property to your TLS listener.\n\n`tls.mutualTlsValidation` and `tlsClientPolicy.mutualTlsCertificate` can be sourced from either:\n\n* A customer-provided certificate (specify a `certificateChain` path file and a `privateKey` file path).\n* A certificate provided by a Secrets Discovery Service (SDS) endpoint over local Unix Domain Socket (specify its `secretName`).\n\n> **Note**\n> Currently, a certificate from AWS Certificate Manager (ACM) cannot be used for mutual TLS authentication.\n\n```python\n# mesh: appmesh.Mesh\n\n\nnode1 = appmesh.VirtualNode(self, \"node1\",\n mesh=mesh,\n service_discovery=appmesh.ServiceDiscovery.dns(\"node\"),\n listeners=[appmesh.VirtualNodeListener.grpc(\n port=80,\n tls=appmesh.ListenerTlsOptions(\n mode=appmesh.TlsMode.STRICT,\n certificate=appmesh.TlsCertificate.file(\"path/to/certChain\", \"path/to/privateKey\"),\n # Validate a file client certificates to enable mutual TLS authentication when a client provides a certificate.\n mutual_tls_validation=appmesh.MutualTlsValidation(\n trust=appmesh.TlsValidationTrust.file(\"path-to-certificate\")\n )\n )\n )]\n)\n\ncertificate_authority_arn = \"arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012\"\nnode2 = appmesh.VirtualNode(self, \"node2\",\n mesh=mesh,\n service_discovery=appmesh.ServiceDiscovery.dns(\"node2\"),\n backend_defaults=appmesh.BackendDefaults(\n tls_client_policy=appmesh.TlsClientPolicy(\n ports=[8080, 8081],\n validation=appmesh.TlsValidation(\n subject_alternative_names=appmesh.SubjectAlternativeNames.matching_exactly(\"mesh-endpoint.apps.local\"),\n trust=appmesh.TlsValidationTrust.acm([\n acmpca.CertificateAuthority.from_certificate_authority_arn(self, \"certificate\", certificate_authority_arn)\n ])\n ),\n # Provide a SDS client certificate when a server requests it and enable mutual TLS authentication.\n mutual_tls_certificate=appmesh.TlsCertificate.sds(\"secret_certificate\")\n )\n )\n)\n```\n\n### Adding outlier detection to a Virtual Node listener\n\nThe `outlierDetection` property adds outlier detection to a Virtual Node listener. The properties\n`baseEjectionDuration`, `interval`, `maxEjectionPercent`, and `maxServerErrors` are required.\n\n```python\n# mesh: appmesh.Mesh\n# Cloud Map service discovery is currently required for host ejection by outlier detection\nvpc = ec2.Vpc(self, \"vpc\")\nnamespace = cloudmap.PrivateDnsNamespace(self, \"test-namespace\",\n vpc=vpc,\n name=\"domain.local\"\n)\nservice = namespace.create_service(\"Svc\")\nnode = mesh.add_virtual_node(\"virtual-node\",\n service_discovery=appmesh.ServiceDiscovery.cloud_map(service),\n listeners=[appmesh.VirtualNodeListener.http(\n outlier_detection=appmesh.OutlierDetection(\n base_ejection_duration=cdk.Duration.seconds(10),\n interval=cdk.Duration.seconds(30),\n max_ejection_percent=50,\n max_server_errors=5\n )\n )]\n)\n```\n\n### Adding a connection pool to a listener\n\nThe `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.\n\n```python\n# A Virtual Node with a gRPC listener with a connection pool set\n# mesh: appmesh.Mesh\n\nnode = appmesh.VirtualNode(self, \"node\",\n mesh=mesh,\n # DNS service discovery can optionally specify the DNS response type as either LOAD_BALANCER or ENDPOINTS.\n # LOAD_BALANCER means that the DNS resolver returns a loadbalanced set of endpoints,\n # whereas ENDPOINTS means that the DNS resolver is returning all the endpoints.\n # By default, the response type is assumed to be LOAD_BALANCER\n service_discovery=appmesh.ServiceDiscovery.dns(\"node\", appmesh.DnsResponseType.ENDPOINTS),\n listeners=[appmesh.VirtualNodeListener.http(\n port=80,\n connection_pool=appmesh.HttpConnectionPool(\n max_connections=100,\n max_pending_requests=10\n )\n )]\n)\n\n# A Virtual Gateway with a gRPC listener with a connection pool set\ngateway = appmesh.VirtualGateway(self, \"gateway\",\n mesh=mesh,\n listeners=[appmesh.VirtualGatewayListener.grpc(\n port=8080,\n connection_pool=appmesh.GrpcConnectionPool(\n max_requests=10\n )\n )],\n virtual_gateway_name=\"gateway\"\n)\n```\n\n## Adding a Route\n\nA *route* matches requests with an associated virtual router and distributes traffic to its associated virtual nodes.\nThe route distributes matching requests to one or more target virtual nodes with relative weighting.\n\nThe `RouteSpec` class lets you define protocol-specific route specifications.\nThe `tcp()`, `http()`, `http2()`, and `grpc()` methods create a specification for the named protocols.\n\nFor HTTP-based routes, the match field can match on path (prefix, exact, or regex), HTTP method, scheme,\nHTTP headers, and query parameters. By default, HTTP-based routes match all requests.\n\nFor gRPC-based routes, the match field can match on service name, method name, and metadata.\nWhen specifying the method name, the service name must also be specified.\n\nFor example, here's how to add an HTTP route that matches based on a prefix of the URL path:\n\n```python\n# router: appmesh.VirtualRouter\n# node: appmesh.VirtualNode\n\n\nrouter.add_route(\"route-http\",\n route_spec=appmesh.RouteSpec.http(\n weighted_targets=[appmesh.WeightedTarget(\n virtual_node=node\n )\n ],\n match=appmesh.HttpRouteMatch(\n # Path that is passed to this method must start with '/'.\n path=appmesh.HttpRoutePathMatch.starts_with(\"/path-to-app\")\n )\n )\n)\n```\n\nAdd an HTTP2 route that matches based on exact path, method, scheme, headers, and query parameters:\n\n```python\n# router: appmesh.VirtualRouter\n# node: appmesh.VirtualNode\n\n\nrouter.add_route(\"route-http2\",\n route_spec=appmesh.RouteSpec.http2(\n weighted_targets=[appmesh.WeightedTarget(\n virtual_node=node\n )\n ],\n match=appmesh.HttpRouteMatch(\n path=appmesh.HttpRoutePathMatch.exactly(\"/exact\"),\n method=appmesh.HttpRouteMethod.POST,\n protocol=appmesh.HttpRouteProtocol.HTTPS,\n headers=[\n # All specified headers must match for the route to match.\n appmesh.HeaderMatch.value_is(\"Content-Type\", \"application/json\"),\n appmesh.HeaderMatch.value_is_not(\"Content-Type\", \"application/json\")\n ],\n query_parameters=[\n # All specified query parameters must match for the route to match.\n appmesh.QueryParameterMatch.value_is(\"query-field\", \"value\")\n ]\n )\n )\n)\n```\n\nAdd a single route with two targets and split traffic 50/50:\n\n```python\n# router: appmesh.VirtualRouter\n# node: appmesh.VirtualNode\n\n\nrouter.add_route(\"route-http\",\n route_spec=appmesh.RouteSpec.http(\n weighted_targets=[appmesh.WeightedTarget(\n virtual_node=node,\n weight=50\n ), appmesh.WeightedTarget(\n virtual_node=node,\n weight=50\n )\n ],\n match=appmesh.HttpRouteMatch(\n path=appmesh.HttpRoutePathMatch.starts_with(\"/path-to-app\")\n )\n )\n)\n```\n\nAdd an http2 route with retries:\n\n```python\n# router: appmesh.VirtualRouter\n# node: appmesh.VirtualNode\n\n\nrouter.add_route(\"route-http2-retry\",\n route_spec=appmesh.RouteSpec.http2(\n weighted_targets=[appmesh.WeightedTarget(virtual_node=node)],\n retry_policy=appmesh.HttpRetryPolicy(\n # Retry if the connection failed\n tcp_retry_events=[appmesh.TcpRetryEvent.CONNECTION_ERROR],\n # Retry if HTTP responds with a gateway error (502, 503, 504)\n http_retry_events=[appmesh.HttpRetryEvent.GATEWAY_ERROR],\n # Retry five times\n retry_attempts=5,\n # Use a 1 second timeout per retry\n retry_timeout=cdk.Duration.seconds(1)\n )\n )\n)\n```\n\nAdd a gRPC route with retries:\n\n```python\n# router: appmesh.VirtualRouter\n# node: appmesh.VirtualNode\n\n\nrouter.add_route(\"route-grpc-retry\",\n route_spec=appmesh.RouteSpec.grpc(\n weighted_targets=[appmesh.WeightedTarget(virtual_node=node)],\n match=appmesh.GrpcRouteMatch(service_name=\"servicename\"),\n retry_policy=appmesh.GrpcRetryPolicy(\n tcp_retry_events=[appmesh.TcpRetryEvent.CONNECTION_ERROR],\n http_retry_events=[appmesh.HttpRetryEvent.GATEWAY_ERROR],\n # Retry if gRPC responds that the request was cancelled, a resource\n # was exhausted, or if the service is unavailable\n grpc_retry_events=[appmesh.GrpcRetryEvent.CANCELLED, appmesh.GrpcRetryEvent.RESOURCE_EXHAUSTED, appmesh.GrpcRetryEvent.UNAVAILABLE\n ],\n retry_attempts=5,\n retry_timeout=cdk.Duration.seconds(1)\n )\n )\n)\n```\n\nAdd an gRPC route that matches based on method name and metadata:\n\n```python\n# router: appmesh.VirtualRouter\n# node: appmesh.VirtualNode\n\n\nrouter.add_route(\"route-grpc-retry\",\n route_spec=appmesh.RouteSpec.grpc(\n weighted_targets=[appmesh.WeightedTarget(virtual_node=node)],\n match=appmesh.GrpcRouteMatch(\n # When method name is specified, service name must be also specified.\n method_name=\"methodname\",\n service_name=\"servicename\",\n metadata=[\n # All specified metadata must match for the route to match.\n appmesh.HeaderMatch.value_starts_with(\"Content-Type\", \"application/\"),\n appmesh.HeaderMatch.value_does_not_start_with(\"Content-Type\", \"text/\")\n ]\n )\n )\n)\n```\n\nAdd a gRPC route with timeout:\n\n```python\n# router: appmesh.VirtualRouter\n# node: appmesh.VirtualNode\n\n\nrouter.add_route(\"route-http\",\n route_spec=appmesh.RouteSpec.grpc(\n weighted_targets=[appmesh.WeightedTarget(\n virtual_node=node\n )\n ],\n match=appmesh.GrpcRouteMatch(\n service_name=\"my-service.default.svc.cluster.local\"\n ),\n timeout=appmesh.GrpcTimeout(\n idle=cdk.Duration.seconds(2),\n per_request=cdk.Duration.seconds(1)\n )\n )\n)\n```\n\n## Adding a Virtual Gateway\n\nA *virtual gateway* allows resources outside your mesh to communicate with resources inside your mesh.\nThe virtual gateway represents an Envoy proxy running in an Amazon ECS task, in a Kubernetes service, or on an Amazon EC2 instance.\nUnlike a virtual node, which represents Envoy running with an application, a virtual gateway represents Envoy deployed by itself.\n\nA 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).\nTraffic received by the virtual gateway is directed to other services in your mesh\nusing rules defined in gateway routes which can be added to your virtual gateway.\n\nCreate a virtual gateway with the constructor:\n\n```python\n# mesh: appmesh.Mesh\n\ncertificate_authority_arn = \"arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012\"\n\ngateway = appmesh.VirtualGateway(self, \"gateway\",\n mesh=mesh,\n listeners=[appmesh.VirtualGatewayListener.http(\n port=443,\n health_check=appmesh.HealthCheck.http(\n interval=cdk.Duration.seconds(10)\n )\n )],\n backend_defaults=appmesh.BackendDefaults(\n tls_client_policy=appmesh.TlsClientPolicy(\n ports=[8080, 8081],\n validation=appmesh.TlsValidation(\n trust=appmesh.TlsValidationTrust.acm([\n acmpca.CertificateAuthority.from_certificate_authority_arn(self, \"certificate\", certificate_authority_arn)\n ])\n )\n )\n ),\n access_log=appmesh.AccessLog.from_file_path(\"/dev/stdout\"),\n virtual_gateway_name=\"virtualGateway\"\n)\n```\n\nAdd a virtual gateway directly to the mesh:\n\n```python\n# mesh: appmesh.Mesh\n\n\ngateway = mesh.add_virtual_gateway(\"gateway\",\n access_log=appmesh.AccessLog.from_file_path(\"/dev/stdout\"),\n virtual_gateway_name=\"virtualGateway\",\n listeners=[appmesh.VirtualGatewayListener.http(\n port=443,\n health_check=appmesh.HealthCheck.http(\n interval=cdk.Duration.seconds(10)\n )\n )]\n)\n```\n\nThe `listeners` field defaults to an HTTP Listener on port 8080 if omitted.\nA gateway route can be added using the `gateway.addGatewayRoute()` method.\n\nThe `backendDefaults` property, provided when creating the virtual gateway, specifies the virtual gateway's default settings for all backends.\n\n## Adding a Gateway Route\n\nA *gateway route* is attached to a virtual gateway and routes matching traffic to an existing virtual service.\n\nFor HTTP-based gateway routes, the `match` field can be used to match on\npath (prefix, exact, or regex), HTTP method, host name, HTTP headers, and query parameters.\nBy default, HTTP-based gateway routes match all requests.\n\n```python\n# gateway: appmesh.VirtualGateway\n# virtual_service: appmesh.VirtualService\n\n\ngateway.add_gateway_route(\"gateway-route-http\",\n route_spec=appmesh.GatewayRouteSpec.http(\n route_target=virtual_service,\n match=appmesh.HttpGatewayRouteMatch(\n path=appmesh.HttpGatewayRoutePathMatch.regex(\"regex\")\n )\n )\n)\n```\n\nFor gRPC-based gateway routes, the `match` field can be used to match on service name, host name, and metadata.\n\n```python\n# gateway: appmesh.VirtualGateway\n# virtual_service: appmesh.VirtualService\n\n\ngateway.add_gateway_route(\"gateway-route-grpc\",\n route_spec=appmesh.GatewayRouteSpec.grpc(\n route_target=virtual_service,\n match=appmesh.GrpcGatewayRouteMatch(\n hostname=appmesh.GatewayRouteHostnameMatch.ends_with(\".example.com\")\n )\n )\n)\n```\n\nFor HTTP based gateway routes, App Mesh automatically rewrites the matched prefix path in Gateway Route to \u201c/\u201d.\nThis automatic rewrite configuration can be overwritten in following ways:\n\n```python\n# gateway: appmesh.VirtualGateway\n# virtual_service: appmesh.VirtualService\n\n\ngateway.add_gateway_route(\"gateway-route-http\",\n route_spec=appmesh.GatewayRouteSpec.http(\n route_target=virtual_service,\n match=appmesh.HttpGatewayRouteMatch(\n # This disables the default rewrite to '/', and retains original path.\n path=appmesh.HttpGatewayRoutePathMatch.starts_with(\"/path-to-app/\", \"\")\n )\n )\n)\n\ngateway.add_gateway_route(\"gateway-route-http-1\",\n route_spec=appmesh.GatewayRouteSpec.http(\n route_target=virtual_service,\n match=appmesh.HttpGatewayRouteMatch(\n # If the request full path is '/path-to-app/xxxxx', this rewrites the path to '/rewrittenUri/xxxxx'.\n # Please note both `prefixPathMatch` and `rewriteTo` must start and end with the `/` character.\n path=appmesh.HttpGatewayRoutePathMatch.starts_with(\"/path-to-app/\", \"/rewrittenUri/\")\n )\n )\n)\n```\n\nIf matching other path (exact or regex), only specific rewrite path can be specified.\nUnlike `startsWith()` method above, no default rewrite is performed.\n\n```python\n# gateway: appmesh.VirtualGateway\n# virtual_service: appmesh.VirtualService\n\n\ngateway.add_gateway_route(\"gateway-route-http-2\",\n route_spec=appmesh.GatewayRouteSpec.http(\n route_target=virtual_service,\n match=appmesh.HttpGatewayRouteMatch(\n # This rewrites the path from '/test' to '/rewrittenPath'.\n path=appmesh.HttpGatewayRoutePathMatch.exactly(\"/test\", \"/rewrittenPath\")\n )\n )\n)\n```\n\nFor HTTP/gRPC based routes, App Mesh automatically rewrites\nthe original request received at the Virtual Gateway to the destination Virtual Service name.\nThis default host name rewrite can be configured by specifying the rewrite rule as one of the `match` property:\n\n```python\n# gateway: appmesh.VirtualGateway\n# virtual_service: appmesh.VirtualService\n\n\ngateway.add_gateway_route(\"gateway-route-grpc\",\n route_spec=appmesh.GatewayRouteSpec.grpc(\n route_target=virtual_service,\n match=appmesh.GrpcGatewayRouteMatch(\n hostname=appmesh.GatewayRouteHostnameMatch.exactly(\"example.com\"),\n # This disables the default rewrite to virtual service name and retain original request.\n rewrite_request_hostname=False\n )\n )\n)\n```\n\n## Importing Resources\n\nEach 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.\nThese imported resources can be used with other resources in your mesh as if they were defined directly in your CDK application.\n\n```python\narn = \"arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh/virtualNode/testNode\"\nappmesh.VirtualNode.from_virtual_node_arn(self, \"importedVirtualNode\", arn)\n```\n\n```python\nvirtual_node_name = \"my-virtual-node\"\nappmesh.VirtualNode.from_virtual_node_attributes(self, \"imported-virtual-node\",\n mesh=appmesh.Mesh.from_mesh_name(self, \"Mesh\", \"testMesh\"),\n virtual_node_name=virtual_node_name\n)\n```\n\nTo import a mesh, again there are two static methods, `fromMeshArn` and `fromMeshName`.\n\n```python\narn = \"arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh\"\nappmesh.Mesh.from_mesh_arn(self, \"imported-mesh\", arn)\n```\n\n```python\nappmesh.Mesh.from_mesh_name(self, \"imported-mesh\", \"abc\")\n```\n\n## IAM Grants\n\n`VirtualNode` and `VirtualGateway` provide `grantStreamAggregatedResources` methods that grant identities that are running\nEnvoy access to stream generated config from App Mesh.\n\n```python\n# mesh: appmesh.Mesh\n\ngateway = appmesh.VirtualGateway(self, \"testGateway\", mesh=mesh)\nenvoy_user = iam.User(self, \"envoyUser\")\n\n#\n# This will grant `grantStreamAggregatedResources` ONLY for this gateway.\n#\ngateway.grant_stream_aggregated_resources(envoy_user)\n```\n\n## Adding Resources to shared meshes\n\nA shared mesh allows resources created by different accounts to communicate with each other in the same mesh:\n\n```python\n# This is the ARN for the mesh from different AWS IAM account ID.\n# Ensure mesh is properly shared with your account. For more details, see: https://github.com/aws/aws-cdk/issues/15404\narn = \"arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh\"\nshared_mesh = appmesh.Mesh.from_mesh_arn(self, \"imported-mesh\", arn)\n\n# This VirtualNode resource can communicate with the resources in the mesh from different AWS IAM account ID.\nappmesh.VirtualNode(self, \"test-node\",\n mesh=shared_mesh\n)\n```\n\n\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "The CDK Construct Library for AWS::AppMesh",
"version": "1.203.0",
"project_urls": {
"Homepage": "https://github.com/aws/aws-cdk",
"Source": "https://github.com/aws/aws-cdk.git"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "362932fb469ad2b736511acd0f5853c3dc79a4e09ee7cd65b6efe9f2574ae50b",
"md5": "0aa4246383cc8cc374030abdc35fc015",
"sha256": "4a47d833027a9987394d3eec63d735b9db624998547af99fea7deeab02611e53"
},
"downloads": -1,
"filename": "aws_cdk.aws_appmesh-1.203.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "0aa4246383cc8cc374030abdc35fc015",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "~=3.7",
"size": 757654,
"upload_time": "2023-05-31T22:52:42",
"upload_time_iso_8601": "2023-05-31T22:52:42.774148Z",
"url": "https://files.pythonhosted.org/packages/36/29/32fb469ad2b736511acd0f5853c3dc79a4e09ee7cd65b6efe9f2574ae50b/aws_cdk.aws_appmesh-1.203.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "2f2c73218eb8b6cd0ae5983b0105ffe4deea887123aee329e7f312da97f12eff",
"md5": "d92100f8309fcc113c9ad444badfa72c",
"sha256": "0d64b696a80824cc7fb559acb5a019af76b1852a583e44b1ec621c19840e287b"
},
"downloads": -1,
"filename": "aws-cdk.aws-appmesh-1.203.0.tar.gz",
"has_sig": false,
"md5_digest": "d92100f8309fcc113c9ad444badfa72c",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "~=3.7",
"size": 763196,
"upload_time": "2023-05-31T23:00:40",
"upload_time_iso_8601": "2023-05-31T23:00:40.799742Z",
"url": "https://files.pythonhosted.org/packages/2f/2c/73218eb8b6cd0ae5983b0105ffe4deea887123aee329e7f312da97f12eff/aws-cdk.aws-appmesh-1.203.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-05-31 23:00:40",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "aws",
"github_project": "aws-cdk",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "aws-cdk.aws-appmesh"
}