Python SDK

Everything importable from the top-level cycl package is public API. Modules prefixed with an underscore (e.g. cycl._fetch, cycl._utils) are internal and may change without notice.

Functions

cycl.fetch_exports(*, cfn_client=None, describe_stacks=False)[source]

Collect every CloudFormation export in the account and region, along with the stacks importing it.

ListImports only returns stack names, so by default an importing stack gets its ARN (id) only if it also defines an export, and tags are empty. With describe_stacks, every stack gets its ARN and tags.

This makes one ListImports call per export, so it can take a while on accounts with many exports. Fetch once and pass the result to build_graph() as many times as needed.

Parameters:
  • cfn_client (CloudFormationClient | None) – CloudFormation client used to list exports and imports. If omitted, one is created with boto3 (standard credential chain) and adaptive retries (10 attempts). A client you pass in is used as is, so configure retries on it yourself to avoid throttling on accounts with many exports, for example boto3.Session(profile_name=..., region_name=...).client('cloudformation', config=botocore.config.Config(retries={'max_attempts': 10, 'mode': 'adaptive'})).

  • describe_stacks (bool) – Also make a DescribeStacks call (paginated, about one call per 100 stacks), to fill in the id and tags of every stack. Requires the cloudformation:DescribeStacks and cloudformation:ListStacks permissions.

Returns:

A mapping of export name to its Export.

Return type:

dict[str, Export]

cycl.build_graph(exports, *, node_key_fn=attrgetter('name'), ignore_nodes=(), ignore_edges=(), remove_selfloops=False)[source]

Build a directed graph of stack dependencies, where an edge points from the exporting to the importing node.

Parameters:
  • exports (Mapping[str, Export]) – Result of fetch_exports().

  • node_key_fn (Callable[[Stack], Hashable]) –

    Function mapping a Stack to its node key in the graph. It is called for every exporting and importing stack and must return a hashable value. Defaults to the stack name.

    Stacks that map to the same key are merged into one node, whose stacks attribute holds all of them. This lets you look for cycles between groups of stacks, such as applications or environments, rather than between individual stacks. Dependencies between stacks in the same group become self loops, see remove_selfloops.

    Node keys are what ignore_nodes, ignore_edges and the resulting cycles refer to. For example, to group stacks by the prefix before the first -:

    build_graph(exports, node_key_fn=lambda stack: stack.name.split('-')[0])
    

    or to group stacks by a tag:

    build_graph(exports, node_key_fn=lambda stack: stack.tags.get('github-repo', stack.name))
    

  • ignore_nodes (Collection[Hashable]) – Node keys to leave out of the graph.

  • ignore_edges (Collection[tuple[Hashable, Hashable]]) – Edges, as (exporter, importer) node key pairs, to leave out of the graph.

  • remove_selfloops (bool) – Remove edges where a node depends on itself, which only happens when node_key_fn merges an exporting stack and one of its importers into the same node.

Returns:

A networkx.MultiDiGraph. Each node has a stacks attribute (set[Stack]) and an exports attribute (dict[str, Export], the exports defined by the node’s stacks). Each edge is keyed by the export name and has an export attribute (Export).

Return type:

nx.MultiDiGraph

cycl.merge_graphs(graphs)[source]

Merge graphs built from different accounts or regions into one graph.

Nodes with the same key in several graphs become one node, so the node keys decide what is merged. With the default node_key_fn (stack name), unrelated stacks that share a name across accounts would be merged, so build each graph with a node_key_fn that is meaningful across accounts, such as a tag, or that includes the source.

Export names are only unique within an account and region, so in the merged graph edges are keyed by (source, export name), as are the entries of each node’s exports. A node’s stacks is the union of its stacks in every graph. Fetch with describe_stacks=True to tell those stacks apart: otherwise stacks which only import have no id, so same named ones from different sources are equal and kept once.

Parameters:

graphs (Mapping[Hashable, nx.MultiDiGraph]) – Graphs from build_graph(), keyed by a hashable label for their source, such as the account ID or an (account, region) pair.

Returns:

A networkx.MultiDiGraph with the same node and edge attributes as build_graph().

Return type:

nx.MultiDiGraph

Models

class cycl.Stack(*, name, id=None, tags=<factory>)[source]

A CloudFormation stack.

Stacks are identified by name and id, so stacks with the same name in different accounts or regions are different stacks. tags is not used for equality or hashing.

Parameters:
name

The stack name.

Type:

str

id

The stack ARN. None when not known: from fetch_exports(), that is a stack which only imports, unless fetched with describe_stacks=True.

Type:

str | None

tags

The stack tags, as a read-only mapping of key to value. Empty unless fetched with describe_stacks=True.

Type:

Mapping[str, str]

class cycl.Export(*, name, value, exporting_stack, importing_stacks=())[source]

A CloudFormation export, along with the stack exporting it and the stacks importing it.

Parameters:
name

The export name.

Type:

str

value

The exported value.

Type:

str

exporting_stack

The stack which defines the export.

Type:

cycl.models.Stack

importing_stacks

The stacks which import the export, without duplicates.

Type:

tuple[cycl.models.Stack, …]

Examples

Find cycles

import networkx as nx

from cycl import build_graph, fetch_exports

graph = build_graph(fetch_exports())  # default boto3 credential chain, region and profile

for cycle in nx.simple_cycles(graph):
    print(cycle)

Use a specific profile or region

fetch_exports makes many AWS calls, so pass a client configured however you need (profile, region, retries, assumed role credentials). A client you pass in is used as is, so give it a retry configuration to avoid throttling on accounts with many exports (the client cycl creates by default uses the one below).

import boto3
from botocore.config import Config

from cycl import build_graph, fetch_exports

cfn_client = boto3.Session(profile_name='my-profile', region_name='us-west-2').client(
    'cloudformation',
    config=Config(retries={'max_attempts': 10, 'mode': 'adaptive'}),
)
graph = build_graph(fetch_exports(cfn_client=cfn_client))

Explain which exports cause a cycle

Edges are keyed by export name and carry the Export.

for cycle in nx.simple_cycles(graph):
    print(' -> '.join(cycle))
    for u, v in zip(cycle, cycle[1:] + cycle[:1]):
        for export_name, attrs in graph[u][v].items():
            print(f'  {u} -> {v} via {export_name} = {attrs["export"].value}')

Fetch once, analyze many ways

exports = fetch_exports()  # the expensive part

full = build_graph(exports)
without_shared = build_graph(exports, ignore_nodes=['shared-networking'])
known_ok = build_graph(exports, ignore_edges=[('stack-a', 'stack-b')])

Group stacks into nodes

node_key_fn maps each Stack to a node key. Stacks with the same key become one node, e.g. to find cycles between environments or applications rather than individual stacks.

graph = build_graph(
    exports,
    node_key_fn=lambda stack: stack.name.split('-')[0],  # 'billing-api' and 'billing-db' -> 'billing'
    remove_selfloops=True,  # dependencies within a group are not cycles between groups
)

graph.nodes['billing']['stacks']   # set of Stack merged into this node
graph.nodes['billing']['exports']  # dict of export name -> Export defined by those stacks

Group stacks by tag

Fetch with describe_stacks=True to fill in each Stack’s tags (one extra paginated DescribeStacks call, and the cloudformation:DescribeStacks and cloudformation:ListStacks permissions). Nodes can then be any grouping you tag stacks with, such as the repository that deploys them.

graph = build_graph(
    fetch_exports(describe_stacks=True),
    node_key_fn=lambda stack: stack.tags.get('github-repo', stack.name),  # untagged stacks stay on their own
    remove_selfloops=True,
)

Merge accounts and regions

merge_graphs() combines graphs from several accounts or regions into one. Nodes with the same key are merged, so pick a node_key_fn that means the same thing everywhere.

Grouping by a tag finds cycles between repositories across all of their deployments. This is a real ordering problem if a repository is released to every account together, but not if each account is deployed on its own:

import boto3
import networkx as nx
from botocore.config import Config

from cycl import build_graph, fetch_exports, merge_graphs

retries = Config(retries={'max_attempts': 10, 'mode': 'adaptive'})
targets = {
    ('dev', 'us-east-1'): boto3.Session(profile_name='dev', region_name='us-east-1'),
    ('prod', 'us-east-1'): boto3.Session(profile_name='prod', region_name='us-east-1'),
    ('prod', 'us-west-2'): boto3.Session(profile_name='prod', region_name='us-west-2'),
}

graphs = {
    source: build_graph(
        fetch_exports(cfn_client=session.client('cloudformation', config=retries), describe_stacks=True),
        node_key_fn=lambda stack: stack.tags.get('github-repo', stack.name),
        remove_selfloops=True,
    )
    for source, session in targets.items()
}
merged = merge_graphs(graphs)

for cycle in nx.simple_cycles(merged):
    print(' -> '.join(cycle))
    for u, v in zip(cycle, cycle[1:] + cycle[:1]):
        for (source, export_name), attrs in merged[u][v].items():  # edges are keyed by (source, export name)
            print(f'  {u} -> {v} via {export_name} in {source}')

To keep each source apart instead, for example to see every stack in one graph, include the source in the key. Without describe_stacks, a stack which only imports has no id, so in a merged graph such stacks with the same name in different sources are equal and kept once in a node’s stacks. Fetch with describe_stacks=True to keep them apart, and to tell from each node’s stacks which accounts it spans, since Stack.id is the stack ARN.

graphs = {
    source: build_graph(fetch_exports(cfn_client=session.client('cloudformation', config=retries)),
                        node_key_fn=lambda stack, source=source: (*source, stack.name))
    for source, session in targets.items()
}
merged = merge_graphs(graphs)  # no cycles across sources, since exports cannot be imported across them

Deployment order

if nx.is_directed_acyclic_graph(graph):
    for generation in nx.topological_generations(graph):
        print(sorted(generation))  # stacks in a generation can be deployed in parallel