AWSCDK::AppMesh

137 types

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

app = AWSCDK::App.new
stack = AWSCDK::Stack.new(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 for more info on egress filters.

mesh = AWSCDK::AppMesh::Mesh.new(self, "AppMesh", {
    mesh_name: "myAwsMesh",
})

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

mesh = AWSCDK::AppMesh::Mesh.new(self, "AppMesh", {
    mesh_name: "myAwsMesh",
    egress_filter: AWSCDK::AppMesh::MeshFilterType::ALLOW_ALL,
})

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

mesh = AWSCDK::AppMesh::Mesh.new(self, "AppMesh", {
    mesh_name: "myAwsMesh",
    service_discovery: {
        ip_preference: AWSCDK::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.

mesh = nil # AWSCDK::AppMesh::Mesh

router = mesh.add_virtual_router("router", {
    listeners: [AWSCDK::AppMesh::VirtualRouterListener.http(8080)],
})

Note that creating the router using the add_virtual_router() 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 add_virtual_router() 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:

infra_stack = nil # AWSCDK::Stack
app_stack = nil # AWSCDK::Stack


mesh = AWSCDK::AppMesh::Mesh.new(infra_stack, "AppMesh", {
    mesh_name: "myAwsMesh",
    egress_filter: AWSCDK::AppMesh::MeshFilterType::ALLOW_ALL,
})

# the VirtualRouter will belong to 'appStack',
# even though the Mesh belongs to 'infraStack'
router = AWSCDK::AppMesh::VirtualRouter.new(app_stack, "router", {
    mesh: mesh,
     # notice that mesh is a required property when creating a router with the 'new' statement
    listeners: [AWSCDK::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 virtual_service_name, 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:

Adding a virtual router as the provider:

router = nil # AWSCDK::AppMesh::VirtualRouter


AWSCDK::AppMesh::VirtualService.new(self, "virtual-service", {
    virtual_service_name: "my-service.default.svc.cluster.local",
     # optional
    virtual_service_provider: AWSCDK::AppMesh::VirtualServiceProvider.virtual_router(router),
})

Adding a virtual node as the provider:

node = nil # AWSCDK::AppMesh::VirtualNode


AWSCDK::AppMesh::VirtualService.new(self, "virtual-service", {
    virtual_service_name: "my-service.default.svc.cluster.local",
     # optional
    virtual_service_provider: AWSCDK::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.

mesh = nil # AWSCDK::AppMesh::Mesh
vpc = AWSCDK::EC2::VPC.new(self, "vpc")
namespace = AWSCDK::ServiceDiscovery::PrivateDNSNamespace.new(self, "test-namespace", {
    vpc: vpc,
    name: "domain.local",
})
service = namespace.create_service("Svc")
node = mesh.add_virtual_node("virtual-node", {
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.cloud_map(service),
    listeners: [
        AWSCDK::AppMesh::VirtualNodeListener.http({
            port: 8081,
            health_check: AWSCDK::AppMesh::HealthCheck.http({
                healthy_threshold: 3,
                interval: AWSCDK::Duration.seconds(5),
                 # minimum
                path: "/health-check-path",
                timeout: AWSCDK::Duration.seconds(2),
                 # minimum
                unhealthy_threshold: 2,
            }),
        }),
    ],
    access_log: AWSCDK::AppMesh::AccessLog.from_file_path("/dev/stdout"),
})

Create a VirtualNode with the constructor and add tags.

mesh = nil # AWSCDK::AppMesh::Mesh
service = nil # AWSCDK::ServiceDiscovery::Service


node = AWSCDK::AppMesh::VirtualNode.new(self, "node", {
    mesh: mesh,
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.cloud_map(service),
    listeners: [
        AWSCDK::AppMesh::VirtualNodeListener.http({
            port: 8080,
            health_check: AWSCDK::AppMesh::HealthCheck.http({
                healthy_threshold: 3,
                interval: AWSCDK::Duration.seconds(5),
                path: "/ping",
                timeout: AWSCDK::Duration.seconds(2),
                unhealthy_threshold: 2,
            }),
            timeout: {
                idle: AWSCDK::Duration.seconds(5),
            },
        }),
    ],
    backend_defaults: {
        tls_client_policy: {
            validation: {
                trust: AWSCDK::AppMesh::TLSValidationTrust.file("/keys/local_cert_chain.pem"),
            },
        },
    },
    access_log: AWSCDK::AppMesh::AccessLog.from_file_path("/dev/stdout"),
})

AWSCDK::Tags.of(node).add("Environment", "Dev")

Create a VirtualNode with the customized access logging format.

mesh = nil # AWSCDK::AppMesh::Mesh
service = nil # AWSCDK::ServiceDiscovery::Service

node = AWSCDK::AppMesh::VirtualNode.new(self, "node", {
    mesh: mesh,
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.cloud_map(service),
    listeners: [
        AWSCDK::AppMesh::VirtualNodeListener.http({
            port: 8080,
            health_check: AWSCDK::AppMesh::HealthCheck.http({
                healthy_threshold: 3,
                interval: AWSCDK::Duration.seconds(5),
                path: "/ping",
                timeout: AWSCDK::Duration.seconds(2),
                unhealthy_threshold: 2,
            }),
            timeout: {
                idle: AWSCDK::Duration.seconds(5),
            },
        }),
    ],
    backend_defaults: {
        tls_client_policy: {
            validation: {
                trust: AWSCDK::AppMesh::TLSValidationTrust.file("/keys/local_cert_chain.pem"),
            },
        },
    },
    access_log: AWSCDK::AppMesh::AccessLog.from_file_path("/dev/stdout", AWSCDK::AppMesh::LoggingFormat.from_json({test_key1: "testValue1", test_key2: "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.

  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.

mesh = nil # AWSCDK::AppMesh::Mesh
router = nil # AWSCDK::AppMesh::VirtualRouter
service = nil # AWSCDK::ServiceDiscovery::Service


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

virtual_service = AWSCDK::AppMesh::VirtualService.new(self, "service-1", {
    virtual_service_provider: AWSCDK::AppMesh::VirtualServiceProvider.virtual_router(router),
    virtual_service_name: "service1.domain.local",
})

node.add_backend(AWSCDK::AppMesh::Backend.virtual_service(virtual_service))

The listeners property can be left blank and added later with the node.addListener() method. The service_discovery 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 backend_defaults 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:

mesh = nil # AWSCDK::AppMesh::Mesh


node = AWSCDK::AppMesh::VirtualNode.new(self, "node", {
    mesh: mesh,
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.dns("node"),
})

virtual_service = AWSCDK::AppMesh::VirtualService.new(self, "service-1", {
    virtual_service_provider: AWSCDK::AppMesh::VirtualServiceProvider.virtual_node(node),
    virtual_service_name: "service1.domain.local",
})

node.add_backend(AWSCDK::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 Virtual Node with listener TLS from an ACM provided certificate
cert = nil # AWSCDK::CertificateManager::Certificate
mesh = nil # AWSCDK::AppMesh::Mesh


node = AWSCDK::AppMesh::VirtualNode.new(self, "node", {
    mesh: mesh,
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.dns("node"),
    listeners: [
        AWSCDK::AppMesh::VirtualNodeListener.grpc({
            port: 80,
            tls: {
                mode: AWSCDK::AppMesh::TLSMode::STRICT,
                certificate: AWSCDK::AppMesh::TLSCertificate.acm(cert),
            },
        }),
    ],
})

# A Virtual Gateway with listener TLS from a customer provided file certificate
gateway = AWSCDK::AppMesh::VirtualGateway.new(self, "gateway", {
    mesh: mesh,
    listeners: [
        AWSCDK::AppMesh::VirtualGatewayListener.grpc({
            port: 8080,
            tls: {
                mode: AWSCDK::AppMesh::TLSMode::STRICT,
                certificate: AWSCDK::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 = AWSCDK::AppMesh::VirtualGateway.new(self, "gateway2", {
    mesh: mesh,
    listeners: [
        AWSCDK::AppMesh::VirtualGatewayListener.http2({
            port: 8080,
            tls: {
                mode: AWSCDK::AppMesh::TLSMode::STRICT,
                certificate: AWSCDK::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 mutual_tls_certificate property to TLS client policy and/or the mutual_tls_validation property to your TLS listener.

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

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

mesh = nil # AWSCDK::AppMesh::Mesh


node1 = AWSCDK::AppMesh::VirtualNode.new(self, "node1", {
    mesh: mesh,
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.dns("node"),
    listeners: [
        AWSCDK::AppMesh::VirtualNodeListener.grpc({
            port: 80,
            tls: {
                mode: AWSCDK::AppMesh::TLSMode::STRICT,
                certificate: AWSCDK::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: {
                    trust: AWSCDK::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 = AWSCDK::AppMesh::VirtualNode.new(self, "node2", {
    mesh: mesh,
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.dns("node2"),
    backend_defaults: {
        tls_client_policy: {
            ports: [8080, 8081],
            validation: {
                subject_alternative_names: AWSCDK::AppMesh::SubjectAlternativeNames.matching_exactly("mesh-endpoint.apps.local"),
                trust: AWSCDK::AppMesh::TLSValidationTrust.acm([
                    AWSCDK::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: AWSCDK::AppMesh::TLSCertificate.sds("secret_certificate"),
        },
    },
})

Adding outlier detection to a Virtual Node listener

The outlier_detection property adds outlier detection to a Virtual Node listener. The properties base_ejection_duration, interval, max_ejection_percent, and max_server_errors are required.

mesh = nil # AWSCDK::AppMesh::Mesh
# Cloud Map service discovery is currently required for host ejection by outlier detection
vpc = AWSCDK::EC2::VPC.new(self, "vpc")
namespace = AWSCDK::ServiceDiscovery::PrivateDNSNamespace.new(self, "test-namespace", {
    vpc: vpc,
    name: "domain.local",
})
service = namespace.create_service("Svc")
node = mesh.add_virtual_node("virtual-node", {
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.cloud_map(service),
    listeners: [
        AWSCDK::AppMesh::VirtualNodeListener.http({
            outlier_detection: {
                base_ejection_duration: AWSCDK::Duration.seconds(10),
                interval: AWSCDK::Duration.seconds(30),
                max_ejection_percent: 50,
                max_server_errors: 5,
            },
        }),
    ],
})

Adding a connection pool to a listener

The connection_pool 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.

# A Virtual Node with a gRPC listener with a connection pool set
mesh = nil # AWSCDK::AppMesh::Mesh

node = AWSCDK::AppMesh::VirtualNode.new(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: AWSCDK::AppMesh::ServiceDiscovery.dns("node", AWSCDK::AppMesh::DNSResponseType::ENDPOINTS),
    listeners: [
        AWSCDK::AppMesh::VirtualNodeListener.http({
            port: 80,
            connection_pool: {
                max_connections: 100,
                max_pending_requests: 10,
            },
        }),
    ],
})

# A Virtual Gateway with a gRPC listener with a connection pool set
gateway = AWSCDK::AppMesh::VirtualGateway.new(self, "gateway", {
    mesh: mesh,
    listeners: [
        AWSCDK::AppMesh::VirtualGatewayListener.grpc({
            port: 8080,
            connection_pool: {
                max_requests: 10,
            },
        }),
    ],
    virtual_gateway_name: "gateway",
})

Adding an IP Preference to a Virtual Node

An ip_preference 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.

mesh = AWSCDK::AppMesh::Mesh.new(self, "mesh", {
    mesh_name: "mesh-with-preference",
})

# Virtual Node with DNS service discovery and an IP preference
dns_node = AWSCDK::AppMesh::VirtualNode.new(self, "dns-node", {
    mesh: mesh,
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.dns("test", AWSCDK::AppMesh::DNSResponseType::LOAD_BALANCER, AWSCDK::AppMesh::IPPreference::IPV4_ONLY),
})

# Virtual Node with CloudMap service discovery and an IP preference
vpc = AWSCDK::EC2::VPC.new(self, "vpc")
namespace = AWSCDK::ServiceDiscovery::PrivateDNSNamespace.new(self, "test-namespace", {
    vpc: vpc,
    name: "domain.local",
})
service = namespace.create_service("Svc")

instance_attribute = {}
instance_attribute.test_key = "testValue"

cloudmap_node = AWSCDK::AppMesh::VirtualNode.new(self, "cloudmap-node", {
    mesh: mesh,
    service_discovery: AWSCDK::AppMesh::ServiceDiscovery.cloud_map(service, instance_attribute, AWSCDK::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:

router = nil # AWSCDK::AppMesh::VirtualRouter
node = nil # AWSCDK::AppMesh::VirtualNode


router.add_route("route-http", {
    route_spec: AWSCDK::AppMesh::RouteSpec.http({
        weighted_targets: [
            {
                virtual_node: node,
            },
        ],
        match: {
            # Path that is passed to this method must start with '/'.
            path: AWSCDK::AppMesh::HttpRoutePathMatch.starts_with("/path-to-app"),
        },
    }),
})

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

router = nil # AWSCDK::AppMesh::VirtualRouter
node = nil # AWSCDK::AppMesh::VirtualNode


router.add_route("route-http2", {
    route_spec: AWSCDK::AppMesh::RouteSpec.http2({
        weighted_targets: [
            {
                virtual_node: node,
            },
        ],
        match: {
            path: AWSCDK::AppMesh::HttpRoutePathMatch.exactly("/exact"),
            method: AWSCDK::AppMesh::HttpRouteMethod::POST,
            protocol: AWSCDK::AppMesh::HttpRouteProtocol::HTTPS,
            headers: [
                AWSCDK::AppMesh::HeaderMatch.value_is("Content-Type", "application/json"),
                AWSCDK::AppMesh::HeaderMatch.value_is_not("Content-Type", "application/json"),
            ],
            query_parameters: [
                AWSCDK::AppMesh::QueryParameterMatch.value_is("query-field", "value"),
            ],
        },
    }),
})

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

router = nil # AWSCDK::AppMesh::VirtualRouter
node = nil # AWSCDK::AppMesh::VirtualNode


router.add_route("route-http", {
    route_spec: AWSCDK::AppMesh::RouteSpec.http({
        weighted_targets: [
            {
                virtual_node: node,
                weight: 50,
            },
            {
                virtual_node: node,
                weight: 50,
            },
        ],
        match: {
            path: AWSCDK::AppMesh::HttpRoutePathMatch.starts_with("/path-to-app"),
        },
    }),
})

Add an http2 route with retries:

router = nil # AWSCDK::AppMesh::VirtualRouter
node = nil # AWSCDK::AppMesh::VirtualNode


router.add_route("route-http2-retry", {
    route_spec: AWSCDK::AppMesh::RouteSpec.http2({
        weighted_targets: [{virtual_node: node}],
        retry_policy: {
            # Retry if the connection failed
            tcp_retry_events: [AWSCDK::AppMesh::TCPRetryEvent::CONNECTION_ERROR],
            # Retry if HTTP responds with a gateway error (502, 503, 504)
            http_retry_events: [AWSCDK::AppMesh::HttpRetryEvent::GATEWAY_ERROR],
            # Retry five times
            retry_attempts: 5,
            # Use a 1 second timeout per retry
            retry_timeout: AWSCDK::Duration.seconds(1),
        },
    }),
})

Add a gRPC route with retries:

router = nil # AWSCDK::AppMesh::VirtualRouter
node = nil # AWSCDK::AppMesh::VirtualNode


router.add_route("route-grpc-retry", {
    route_spec: AWSCDK::AppMesh::RouteSpec.grpc({
        weighted_targets: [{virtual_node: node}],
        match: {service_name: "servicename"},
        retry_policy: {
            tcp_retry_events: [AWSCDK::AppMesh::TCPRetryEvent::CONNECTION_ERROR],
            http_retry_events: [AWSCDK::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: [
                AWSCDK::AppMesh::GrpcRetryEvent::CANCELLED,
                AWSCDK::AppMesh::GrpcRetryEvent::RESOURCE_EXHAUSTED,
                AWSCDK::AppMesh::GrpcRetryEvent::UNAVAILABLE,
            ],
            retry_attempts: 5,
            retry_timeout: AWSCDK::Duration.seconds(1),
        },
    }),
})

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

router = nil # AWSCDK::AppMesh::VirtualRouter
node = nil # AWSCDK::AppMesh::VirtualNode


router.add_route("route-grpc-retry", {
    route_spec: AWSCDK::AppMesh::RouteSpec.grpc({
        weighted_targets: [{virtual_node: node}],
        match: {
            # When method name is specified, service name must be also specified.
            method_name: "methodname",
            service_name: "servicename",
            metadata: [
                AWSCDK::AppMesh::HeaderMatch.value_starts_with("Content-Type", "application/"),
                AWSCDK::AppMesh::HeaderMatch.value_does_not_start_with("Content-Type", "text/"),
            ],
        },
    }),
})

Add a gRPC route that matches based on port:

router = nil # AWSCDK::AppMesh::VirtualRouter
node = nil # AWSCDK::AppMesh::VirtualNode


router.add_route("route-grpc-port", {
    route_spec: AWSCDK::AppMesh::RouteSpec.grpc({
        weighted_targets: [
            {
                virtual_node: node,
            },
        ],
        match: {
            port: 1234,
        },
    }),
})

Add a gRPC route with timeout:

router = nil # AWSCDK::AppMesh::VirtualRouter
node = nil # AWSCDK::AppMesh::VirtualNode


router.add_route("route-http", {
    route_spec: AWSCDK::AppMesh::RouteSpec.grpc({
        weighted_targets: [
            {
                virtual_node: node,
            },
        ],
        match: {
            service_name: "my-service.default.svc.cluster.local",
        },
        timeout: {
            idle: AWSCDK::Duration.seconds(2),
            per_request: AWSCDK::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:

mesh = nil # AWSCDK::AppMesh::Mesh

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

gateway = AWSCDK::AppMesh::VirtualGateway.new(self, "gateway", {
    mesh: mesh,
    listeners: [
        AWSCDK::AppMesh::VirtualGatewayListener.http({
            port: 443,
            health_check: AWSCDK::AppMesh::HealthCheck.http({
                interval: AWSCDK::Duration.seconds(10),
            }),
        }),
    ],
    backend_defaults: {
        tls_client_policy: {
            ports: [8080, 8081],
            validation: {
                trust: AWSCDK::AppMesh::TLSValidationTrust.acm([
                    AWSCDK::ACMPCA::CertificateAuthority.from_certificate_authority_arn(self, "certificate", certificate_authority_arn),
                ]),
            },
        },
    },
    access_log: AWSCDK::AppMesh::AccessLog.from_file_path("/dev/stdout"),
    virtual_gateway_name: "virtualGateway",
})

Add a virtual gateway directly to the mesh:

mesh = nil # AWSCDK::AppMesh::Mesh


gateway = mesh.add_virtual_gateway("gateway", {
    access_log: AWSCDK::AppMesh::AccessLog.from_file_path("/dev/stdout"),
    virtual_gateway_name: "virtualGateway",
    listeners: [
        AWSCDK::AppMesh::VirtualGatewayListener.http({
            port: 443,
            health_check: AWSCDK::AppMesh::HealthCheck.http({
                interval: AWSCDK::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 backend_defaults 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.

gateway = nil # AWSCDK::AppMesh::VirtualGateway
virtual_service = nil # AWSCDK::AppMesh::VirtualService


gateway.add_gateway_route("gateway-route-http", {
    route_spec: AWSCDK::AppMesh::GatewayRouteSpec.http({
        route_target: virtual_service,
        match: {
            path: AWSCDK::AppMesh::HttpGatewayRoutePathMatch.regex("regex"),
        },
    }),
})

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

gateway = nil # AWSCDK::AppMesh::VirtualGateway
virtual_service = nil # AWSCDK::AppMesh::VirtualService


gateway.add_gateway_route("gateway-route-grpc", {
    route_spec: AWSCDK::AppMesh::GatewayRouteSpec.grpc({
        route_target: virtual_service,
        match: {
            hostname: AWSCDK::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:

gateway = nil # AWSCDK::AppMesh::VirtualGateway
virtual_service = nil # AWSCDK::AppMesh::VirtualService


gateway.add_gateway_route("gateway-route-http", {
    route_spec: AWSCDK::AppMesh::GatewayRouteSpec.http({
        route_target: virtual_service,
        match: {
            # This disables the default rewrite to '/', and retains original path.
            path: AWSCDK::AppMesh::HttpGatewayRoutePathMatch.starts_with("/path-to-app/", ""),
        },
    }),
})

gateway.add_gateway_route("gateway-route-http-1", {
    route_spec: AWSCDK::AppMesh::GatewayRouteSpec.http({
        route_target: virtual_service,
        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: AWSCDK::AppMesh::HttpGatewayRoutePathMatch.starts_with("/path-to-app/", "/rewrittenUri/"),
        },
    }),
})

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

gateway = nil # AWSCDK::AppMesh::VirtualGateway
virtual_service = nil # AWSCDK::AppMesh::VirtualService


gateway.add_gateway_route("gateway-route-http-2", {
    route_spec: AWSCDK::AppMesh::GatewayRouteSpec.http({
        route_target: virtual_service,
        match: {
            # This rewrites the path from '/test' to '/rewrittenPath'.
            path: AWSCDK::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:

gateway = nil # AWSCDK::AppMesh::VirtualGateway
virtual_service = nil # AWSCDK::AppMesh::VirtualService


gateway.add_gateway_route("gateway-route-grpc", {
    route_spec: AWSCDK::AppMesh::GatewayRouteSpec.grpc({
        route_target: virtual_service,
        match: {
            hostname: AWSCDK::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.

arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh/virtualNode/testNode"
AWSCDK::AppMesh::VirtualNode.from_virtual_node_arn(self, "importedVirtualNode", arn)
virtual_node_name = "my-virtual-node"
AWSCDK::AppMesh::VirtualNode.from_virtual_node_attributes(self, "imported-virtual-node", {
    mesh: AWSCDK::AppMesh::Mesh.from_mesh_name(self, "Mesh", "testMesh"),
    virtual_node_name: virtual_node_name,
})

To import a mesh, again there are two static methods, from_mesh_arn and from_mesh_name.

arn = "arn:aws:appmesh:us-east-1:123456789012:mesh/testMesh"
AWSCDK::AppMesh::Mesh.from_mesh_arn(self, "imported-mesh", arn)
AWSCDK::AppMesh::Mesh.from_mesh_name(self, "imported-mesh", "abc")

IAM Grants

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

mesh = nil # AWSCDK::AppMesh::Mesh

gateway = AWSCDK::AppMesh::VirtualGateway.new(self, "testGateway", {mesh: mesh})
envoy_user = AWSCDK::IAM::User.new(self, "envoyUser")

#
# This will grant `appmesh:StreamAggregatedResources` ONLY for this gateway.
#
gateway.grants.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:

# 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 = AWSCDK::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.
AWSCDK::AppMesh::VirtualNode.new(self, "test-node", {
    mesh: shared_mesh,
})

API Reference

Classes 37

AccessLogConfiguration for Envoy Access logs for mesh endpoints. BackendContains static factory methods to create backends. CfnGatewayRouteCreates a gateway route. CfnMeshCreates a service mesh. CfnRouteCreates a route that is associated with a virtual router. CfnVirtualGatewayCreates a virtual gateway. CfnVirtualNodeCreates a virtual node within a service mesh. CfnVirtualRouterCreates a virtual router within a service mesh. CfnVirtualServiceCreates a virtual service within a service mesh. GatewayRouteGatewayRoute represents a new or existing gateway route attached to a VirtualGateway and M GatewayRouteHostnameMatchUsed to generate host name matching methods. GatewayRouteSpecUsed to generate specs with different protocols for a GatewayRoute. HeaderMatchUsed to generate header matching methods. HealthCheckContains static factory methods for creating health checks for different protocols. HttpGatewayRoutePathMatchDefines HTTP gateway route matching based on the URL path of the request. HttpRoutePathMatchDefines HTTP route matching based on the URL path of the request. LoggingFormatConfiguration for Envoy Access Logging Format for mesh endpoints. MeshDefine a new AppMesh mesh. MutualTLSCertificateRepresents a TLS certificate that is supported for mutual TLS authentication. MutualTLSValidationTrustRepresents a TLS Validation Context Trust that is supported for mutual TLS authentication. QueryParameterMatchUsed to generate query parameter matching methods. RouteRoute represents a new or existing route attached to a VirtualRouter and Mesh. RouteSpecUsed to generate specs with different protocols for a RouteSpec. ServiceDiscoveryProvides the Service Discovery method a VirtualNode uses. SubjectAlternativeNamesUsed to generate Subject Alternative Names Matchers. TLSCertificateRepresents a TLS certificate. TLSValidationTrustDefines the TLS Validation Context Trust. VirtualGatewayVirtualGateway represents a newly defined App Mesh Virtual Gateway. VirtualGatewayGrantsCollection of grant methods for a IVirtualGatewayRef. VirtualGatewayListenerRepresents the properties needed to define listeners for a VirtualGateway. VirtualNodeVirtualNode represents a newly defined AppMesh VirtualNode. VirtualNodeGrantsCollection of grant methods for a IVirtualNodeRef. VirtualNodeListenerDefines listener for a VirtualNode. VirtualRouter VirtualRouterListenerRepresents the properties needed to define listeners for a VirtualRouter. VirtualServiceVirtualService represents a service inside an AppMesh. VirtualServiceProviderRepresents the properties needed to define the provider for a VirtualService.

Interfaces 91

AccessLogConfigAll Properties for Envoy Access logs for mesh endpoints. BackendConfigProperties for a backend. BackendDefaultsRepresents the properties needed to define backend defaults. CfnGatewayRoutePropsProperties for defining a `CfnGatewayRoute`. CfnMeshPropsProperties for defining a `CfnMesh`. CfnRoutePropsProperties for defining a `CfnRoute`. CfnVirtualGatewayPropsProperties for defining a `CfnVirtualGateway`. CfnVirtualNodePropsProperties for defining a `CfnVirtualNode`. CfnVirtualRouterPropsProperties for defining a `CfnVirtualRouter`. CfnVirtualServicePropsProperties for defining a `CfnVirtualService`. CommonGatewayRouteSpecOptionsBase options for all gateway route specs. GatewayRouteAttributesInterface with properties necessary to import a reusable GatewayRoute. GatewayRouteBasePropsBasic configuration properties for a GatewayRoute. GatewayRouteHostnameMatchConfigConfiguration for gateway route host name match. GatewayRoutePropsProperties to define a new GatewayRoute. GatewayRouteSpecConfigAll Properties for GatewayRoute Specs. GrpcConnectionPoolConnection pool properties for gRPC listeners. GrpcGatewayListenerOptionsRepresents the properties needed to define GRPC Listeners for a VirtualGateway. GrpcGatewayRouteMatchThe criterion for determining a request match for this GatewayRoute. GrpcGatewayRouteSpecOptionsProperties specific for a gRPC GatewayRoute. GrpcHealthCheckOptionsProperties used to define GRPC Based healthchecks. GrpcRetryPolicygRPC retry policy. GrpcRouteMatchThe criterion for determining a request match for this Route. GrpcRouteSpecOptionsProperties specific for a GRPC Based Routes. GrpcTimeoutRepresents timeouts for GRPC protocols. GrpcVirtualNodeListenerOptionsRepresent the GRPC Node Listener property. HeaderMatchConfigConfiguration for `HeaderMatch`. HealthCheckBindOptionsOptions used for creating the Health Check object. HealthCheckConfigAll Properties for Health Checks for mesh endpoints. Http2ConnectionPoolConnection pool properties for HTTP2 listeners. Http2GatewayListenerOptionsRepresents the properties needed to define HTTP2 Listeners for a VirtualGateway. Http2VirtualNodeListenerOptionsRepresent the HTTP2 Node Listener property. HttpConnectionPoolConnection pool properties for HTTP listeners. HttpGatewayListenerOptionsRepresents the properties needed to define HTTP Listeners for a VirtualGateway. HttpGatewayRouteMatchThe criterion for determining a request match for this GatewayRoute. HttpGatewayRoutePathMatchConfigThe type returned from the `bind()` method in `HttpGatewayRoutePathMatch`. HttpGatewayRouteSpecOptionsProperties specific for HTTP Based GatewayRoutes. HttpHealthCheckOptionsProperties used to define HTTP Based healthchecks. HttpRetryPolicyHTTP retry policy. HttpRouteMatchThe criterion for determining a request match for this Route. HttpRoutePathMatchConfigThe type returned from the `bind()` method in `HttpRoutePathMatch`. HttpRouteSpecOptionsProperties specific for HTTP Based Routes. HttpTimeoutRepresents timeouts for HTTP protocols. HttpVirtualNodeListenerOptionsRepresent the HTTP Node Listener property. IGatewayRouteInterface for which all GatewayRoute based classes MUST implement. IMeshInterface which all Mesh based classes MUST implement. IRouteInterface for which all Route based classes MUST implement. IVirtualGatewayInterface which all Virtual Gateway based classes must implement. IVirtualNodeInterface which all VirtualNode based classes must implement. IVirtualRouterInterface which all VirtualRouter based classes MUST implement. IVirtualServiceRepresents the interface which all VirtualService based classes MUST implement. ListenerTLSOptionsRepresents TLS properties for listener. LoggingFormatConfigAll Properties for Envoy Access Logging Format for mesh endpoints. MeshPropsThe set of properties used when creating a Mesh. MeshServiceDiscoveryProperties for Mesh Service Discovery. MutualTLSValidationRepresents the properties needed to define TLS Validation context that is supported for mu OutlierDetectionRepresents the outlier detection for a listener. QueryParameterMatchConfigConfiguration for `QueryParameterMatch`. RouteAttributesInterface with properties ncecessary to import a reusable Route. RouteBasePropsBase interface properties for all Routes. RoutePropsProperties to define new Routes. RouteSpecConfigAll Properties for Route Specs. RouteSpecOptionsBaseBase options for all route specs. ServiceDiscoveryConfigProperties for VirtualNode Service Discovery. SubjectAlternativeNamesMatcherConfigAll Properties for Subject Alternative Names Matcher for both Client Policy and Listener. TCPConnectionPoolConnection pool properties for TCP listeners. TCPHealthCheckOptionsProperties used to define TCP Based healthchecks. TCPRouteSpecOptionsProperties specific for a TCP Based Routes. TCPTimeoutRepresents timeouts for TCP protocols. TCPVirtualNodeListenerOptionsRepresent the TCP Node Listener property. TLSCertificateConfigA wrapper for the tls config returned by `TlsCertificate.bind`. TLSClientPolicyRepresents the properties needed to define client policy. TLSValidationRepresents the properties needed to define TLS Validation context. TLSValidationTrustConfigAll Properties for TLS Validation Trusts for both Client Policy and Listener. VirtualGatewayAttributesUnterface with properties necessary to import a reusable VirtualGateway. VirtualGatewayBasePropsBasic configuration properties for a VirtualGateway. VirtualGatewayListenerConfigProperties for a VirtualGateway listener. VirtualGatewayPropsProperties used when creating a new VirtualGateway. VirtualNodeAttributesInterface with properties necessary to import a reusable VirtualNode. VirtualNodeBasePropsBasic configuration properties for a VirtualNode. VirtualNodeListenerConfigProperties for a VirtualNode listener. VirtualNodePropsThe properties used when creating a new VirtualNode. VirtualRouterAttributesInterface with properties ncecessary to import a reusable VirtualRouter. VirtualRouterBasePropsInterface with base properties all routers willl inherit. VirtualRouterListenerConfigProperties for a VirtualRouter listener. VirtualRouterPropsThe properties used when creating a new VirtualRouter. VirtualServiceAttributesInterface with properties ncecessary to import a reusable VirtualService. VirtualServiceBackendOptionsRepresents the properties needed to define a Virtual Service backend. VirtualServicePropsThe properties applied to the VirtualService being defined. VirtualServiceProviderConfigProperties for a VirtualService provider. WeightedTargetProperties for the Weighted Targets in the route.

Enums 9

DNSResponseTypeEnum of DNS service discovery response type. GrpcRetryEventgRPC events. HttpRetryEventHTTP events on which to retry. HttpRouteMethodSupported values for matching routes based on the HTTP request method. HttpRouteProtocolSupported :scheme options for HTTP2. IPPreferenceEnum of supported IP preferences. MeshFilterTypeA utility enum defined for the egressFilter type property, the default of DROP_ALL, allows TCPRetryEventTCP events on which you may retry. TLSModeEnum of supported TLS modes.