### AWS configuration file setup Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/aws/config.md Example configuration for the default profile and individual account profiles in the AWS config file. ```ini [default] region= output=json ``` ```ini [profile accountname1] role_arn = arn:aws:iam:::role/cartography-read-only region=us-east-1 output=json credential_source = Ec2InstanceMetadata [profile accountname2] role_arn = arn:aws:iam:::role/cartography-read-only region=us-west-1 output=json credential_source = Ec2InstanceMetadata ... etc ... ``` -------------------------------- ### Start the Neo4j database Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Initialize the Neo4j container within the cloned directory. ```bash cd cartography docker-compose up -d ``` -------------------------------- ### JSON State File Example Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/drift-detect.md This is an example of the JSON file generated by the `get-state` command, containing query results and metadata. ```json { "name": "Internet Exposed EC2 Instances", "validation_query": "match (n:EC2Instance) where n.exposed_internet = True return n.instancetype, n.privateipaddress, n.publicdnsname, n.exposed_internet_type" "properties": ["n.instancetype", "n.privateipaddress", "n.publicdnsname", "n.exposed_internet_type"], "results": [ ["c4.large", "10.255.255.251", "ec2.1.compute.amazonaws.com", "direct"], ["t2.micro", "10.255.255.252", "ec2.2.compute.amazonaws.com", "direct"], ["c4.large", "10.255.255.253", "ec2.3.compute.amazonaws.com", "direct|elb"], ["t2.micro", "10.255.255.254", "ec2.4.compute.amazonaws.com", "direct|elb"] ] } ``` -------------------------------- ### Start Neo4j Database Source: https://github.com/cartography-cncf/cartography/blob/master/README.md Launch a Neo4j container with the required ports and volume mapping. ```bash docker run -d --publish=7474:7474 --publish=7687:7687 -v data:/data --env=NEO4J_AUTH=none neo4j:5-community ``` -------------------------------- ### Install Cartography Source: https://github.com/cartography-cncf/cartography/blob/master/README.md Install the package using pip. ```bash pip install cartography ``` -------------------------------- ### Install Cartography with uv Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Installs the uv package manager and uses it to install Cartography as an isolated tool. ```bash # Install uv if you don't have it (see https://docs.astral.sh/uv/getting-started/installation/ for alternatives). curl -LsSf https://astral.sh/uv/install.sh | sh # Install cartography as an isolated tool exposed on your PATH. uv tool install cartography ``` -------------------------------- ### Python: Integration Test Example Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/writing-intel-modules.md Example of an integration test for an intel module. These tests, located in `tests/integration/cartography/intel`, ensure that loaded graph data matches mock data, assuming Neo4j is running locally. ```python # Example from tests/integration/cartography/intel/aws/ec2/test_ec2_instances.py # def test_ec2_instances_integration(neo4j_session): # ... # assert len(nodes) == expected_node_count ``` -------------------------------- ### Configure and run via Docker Compose Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Set environment variables and start the Cartography stack. Ensure the Neo4j password is set before running the container. ```bash # Temporarily disable bash command history set +o history # See the cartography github configuration intel module docs export GITHUB_KEY=BASE64ENCODEDKEY # You need to set this after starting neo4j once, and resetting # the default neo4j password, which is neo4j export NEO4j_PASSWORD=... # Reenable bash command history set -o history # Start cartography dependencies docker-compose up -d # Run cartography docker-compose run -e GITHUB_KEY -e NEO4j_PASSWORD cartography cartography --github-config-env-var GITHUB_KEY --neo4j-uri bolt://neo4j:7687 --neo4j-password-env-var NEO4j_PASSWORD --neo4j-user neo4j ``` -------------------------------- ### Install Shell Autocompletion Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/cli.md Install shell autocompletion for your current shell. After installation, restart your shell to enable Tab completion. ```bash cartography --install-completion ``` ```bash cartography --show-completion ``` -------------------------------- ### Sync Dependencies and Run Sphinx Autobuild Source: https://github.com/cartography-cncf/cartography/blob/master/docs/README.md Use this command to synchronize project dependencies and start the Sphinx documentation server for local development. Changes in `docs/root/` will trigger automatic rebuilds. ```bash uv sync --group doc ``` ```bash uv run sphinx-autobuild docs/root docs/generated/docs -c docs --port 8000 ``` -------------------------------- ### Install Test Requirements Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Installs the necessary Python packages for running tests. Use --frozen to ensure only pinned dependencies from the lockfile are used. ```bash uv sync --frozen --dev ``` -------------------------------- ### Define a basic GCP permission relationship Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gcp/permission-mapping.md Example of a YAML configuration to map read permissions for GCP buckets. ```yaml - target_label: GCPBucket permissions: - storage.objects.get relationship_name: CAN_READ ``` -------------------------------- ### Run Neo4j via Docker Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Starts a Neo4j 5.x community container with ports 7474 and 7687 exposed and authentication disabled. ```bash docker run --publish=7474:7474 --publish=7687:7687 -v data:/data --env=NEO4J_AUTH=none neo4j:5-community ``` -------------------------------- ### Set JAVA_HOME for macOS Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Configures the JAVA_HOME environment variable required for Neo4j installations. ```bash export JAVA_HOME=$(/usr/libexec/java_home) ``` -------------------------------- ### Enable shell tab completion Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Install and use shell tab completion for CLI commands. ```bash cartography-rules --install-completion ``` ```bash cartography-rules list cartography-rules run ``` -------------------------------- ### Rule Execution Output Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Example output generated after running a rule, showing facts, findings, and an execution summary. ```text Executing object_storage_public rule Total facts: 2 Fact 1/2: Internet-Accessible S3 Storage Attack Surface Rule: object_storage_public - Public Object Storage Attack Surface Fact ID: aws_s3_public Description: AWS S3 buckets accessible from the internet Provider: AWS Neo4j Query: http://localhost:7474/browser/?cmd=play&arg= Results: 3 item(s) found Sample findings: 1. bucket=cdn.example.com, region=us-east-1, anonymous_access=True 2. bucket=mybucket.example.com, region=us-east-1, anonymous_actions=['s3:ListBucket', 's3:ListBucketVersions'] 3. bucket=static.example.com, region=us-east-1, public_access=True ... (use --output json to see all) Fact 2/2: Azure Storage Public Blob Access Rule: object_storage_public - Public Object Storage Attack Surface Fact ID: azure_storage_public_blob_access Description: Azure Storage accounts with public blob access Provider: Azure Neo4j Query: http://localhost:7474/browser/?cmd=play&arg= Results: No items found ============================================================ EXECUTION SUMMARY ============================================================ Total facts: 2 Total findings: 3 Rule execution completed with 3 total findings ``` -------------------------------- ### Drift Detection Output Example Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/drift-detect.md This output shows the differences detected between two state files, listing new query results and missing query results. ```text Query Name: Internet Exposed EC2 Instances Query Properties: ["n.instancetype", "n.privateipaddress", "n.publicdnsname", "n.exposed_internet_type"] New Query Results: n.instancetype: t2.micro n.privateipaddress: 10.255.255.250 n.publicdnsname: ec2.0.compute.amazonaws.com n.exposed_internet_type: ['direct'] n.instancetype: c4.large n.privateipaddress: 10.255.255.255 n.publicdnsname: ec2.5.compute.amazonaws.com n.exposed_internet_type: ['direct', 'elb'] Missing Query Results: n.instancetype: t2.micro n.privateipaddress: 10.255.255.253 n.publicdnsname: ec2.4.compute.amazonaws.com n.exposed_internet_type: ['direct', 'elb'] ``` -------------------------------- ### Run Cartography from Source Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md After performing an editable install, this command allows you to run Cartography directly from your local source code. Changes are immediately testable. ```bash uv run cartography --neo4j-uri bolt://localhost:7687 ``` -------------------------------- ### Implement Custom Sync Script Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Example of a Python script to create a custom Cartography sync process. This allows you to selectively include intel modules, such as only the AWS module, for data ingestion. ```python from cartography import cli from cartography import sync from cartography.intel import aws from cartography.intel import create_indexes def build_custom_sync(): s = sync.Sync() s.add_stages([ ('create-indexes', create_indexes.run), ('aws', aws.start_aws_ingestion), ]) return s def main(argv): return cli.CLI(build_custom_sync(), prog='cartography').main(argv) if __name__ == '__main__': import sys sys.exit(main(sys.argv[1:])) ``` -------------------------------- ### Run Cartography Docker Container Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/ops.md Execute the Cartography Docker image with your desired command-line flags. This example shows how to run the container and access its help information. ```bash docker run --rm ghcr.io/cartography-cncf/cartography:0.96.1 --help ``` -------------------------------- ### Define a basic permission relationship Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/aws/permissions-mapping.md Example of mapping S3 read access in the permission relationship YAML file. ```yaml - target_label: S3Bucket permissions: - S3:GetObject relationship_name: CAN_READ ``` -------------------------------- ### List All Distinct Dependencies Across GitHub Repositories Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/samplequeries.md Get a comprehensive list of all unique dependencies used across all GitHub repositories, along with their versions. An alternative query shows which repositories use each dependency. ```cypher MATCH (dep:Dependency) RETURN DISTINCT dep.name AS name, dep.version AS version ORDER BY dep.name ``` ```cypher MATCH (repo:GitHubRepository)-[edge:REQUIRES]->(dep:Dependency) RETURN repo.name, dep.name, edge.specifier, dep.version ``` -------------------------------- ### Compare State Files with get-drift Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/drift-detect.md Use `get-drift` to compare two state files and identify differences. Specify the directory containing the state files and the start and end state files for comparison. ```bash cartography-detectdrift get-drift --query-directory ${DRIFT_DETECTION_DIRECTORY}/internet-exposure-query --start-state .json --end-state .json ``` -------------------------------- ### Configure Cartography with Object Storage Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/docker_scout/config.md Configure Cartography to read Docker Scout text result files from object storage. This example uses an S3 bucket, but gs:// and azblob:// prefixes are also supported. ```bash cartography --selected-modules docker_scout \ --docker-scout-source s3://my-bucket/docker-scout-scans/ ``` -------------------------------- ### Show Contextual Help Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/cli.md Display help output, optionally filtered by selected modules. This helps in discovering relevant options without scrolling through all parameters. ```bash cartography --help ``` ```bash cartography --selected-modules aws --help ``` ```bash cartography --selected-modules aws,github --help ``` -------------------------------- ### Run Full Test Suite with dev.Dockerfile (Manual) Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Execute the full test suite using the development Docker image. Requires a running Neo4j container, shared network, volume mounts, and NEO4J_URL environment variable. ```bash docker run \ --publish=7474:7474 \ --publish=7687:7687 \ --network cartography-network \ -v data:/data \ --name cartography-neo4j \ --env=NEO4J_AUTH=none \ neo4j:5-community ``` ```bash docker run --rm \ -v $(pwd):/var/cartography \ -v $(pwd)/.cache/pre-commit:/var/cartography/.cache/pre-commit \ --network cartography-network \ -e NEO4J_URL=bolt://cartography-neo4j:7687 \ cartography-cncf/cartography-dev \ make test ``` -------------------------------- ### Python: Unit Test Example Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/writing-intel-modules.md Example of a unit test for an intel module's data transformation logic. These tests, typically found in `tests/unit/cartography/intel`, verify that `transform*` functions manipulate data correctly. ```python # Example from tests/unit/cartography/intel/gcp/test_compute.py # def test_compute_instance_transform(): # ... # assert transformed_data == expected_data ``` -------------------------------- ### Run Linter with dev.Dockerfile (Manual) Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Execute the linter using the development Docker image. Requires volume mounts for source files and pre-commit cache. ```bash docker run --rm \ -v $(pwd):/var/cartography \ -v $(pwd)/.cache/pre-commit:/var/cartography/.cache/pre-commit \ cartography-cncf/cartography-dev \ make test_lint ``` -------------------------------- ### Enable and Configure StatsD Metrics Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/cli.md Enable the collection of metrics and specify the StatsD host. Requires setting the Neo4j URI. ```bash cartography \ --neo4j-uri bolt://localhost:7687 \ --statsd-enabled \ --statsd-host metrics.example.com ``` -------------------------------- ### Run Integration Tests with dev.Dockerfile (Manual) Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Execute integration tests using the development Docker image. Requires a running Neo4j container on a shared network and the NEO4J_URL environment variable. ```bash docker run \ --publish=7474:7474 \ --publish=7687:7687 \ --network cartography-network \ -v data:/data \ --name cartography-neo4j \ --env=NEO4J_AUTH=none \ neo4j:5-community ``` ```bash docker run --rm \ --network cartography-network \ -e NEO4J_URL=bolt://cartography-neo4j:7687 \ cartography-cncf/cartography-dev \ make test_integration ``` -------------------------------- ### Configure OCI SDK Credentials Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/oci/config.md Configure your OCI SDK credentials file at `~/.oci/config` with your user OCID, API key fingerprint, tenancy OCID, region, and the path to your private key file. ```INI [DEFAULT] user=ocid1.user.oc1..exampleuniqueID fingerprint=12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef tenancy=ocid1.tenancy.oc1..exampleuniqueID region=us-ashburn-1 key_file=~/.oci/oci_api_key.pem ``` -------------------------------- ### Run AIBOM module with local or cloud storage Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/aibom/config.md Execute the AIBOM module by specifying the source path, which supports local directories, S3, GCS, or Azure Blob Storage. ```bash cartography \ --selected-modules aibom \ --aibom-source /path/to/aibom-results ``` ```bash cartography \ --selected-modules aibom \ --aibom-source s3://my-aibom-bucket/reports/ ``` -------------------------------- ### Query GitLabCIVariable data Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gitlab/schema.md Example queries to identify potentially insecure variables and count variables by scope. ```cypher MATCH (v:GitLabCIVariable) WHERE v.protected = false AND v.masked = false RETURN v.scope_type, v.key, v.environment_scope ``` ```cypher MATCH (v:GitLabCIVariable) RETURN v.scope_type, count(*) AS count ``` -------------------------------- ### Define a target precondition Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/aws/permissions-mapping.md Example of restricting an edge creation based on the existence of a related node in the graph. ```yaml - target_label: EC2Instance permissions: - ssm:StartSession relationship_name: CAN_START_SESSION target_precondition: related_label: SSMInstanceInformation relationship: HAS_INFORMATION direction: outgoing ``` -------------------------------- ### Azure IAM Analysis Queries Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/azure/schema.md Example queries to identify users, principals, and permissions within Azure IAM. ```cypher MATCH (u:EntraUser)-[:HAS_ROLE_ASSIGNMENT]->(ra:AzureRoleAssignment)-[:ROLE_ASSIGNED]->(rd:AzureRoleDefinition) WHERE rd.role_name = 'Owner' RETURN u.email, ra.scope ``` ```cypher MATCH (ra:AzureRoleAssignment)-[:ROLE_ASSIGNED]->(rd:AzureRoleDefinition)-[:HAS_PERMISSIONS]->(p:AzurePermissions) WHERE ANY(action IN p.actions WHERE action CONTAINS 'Microsoft.Storage' AND action CONTAINS 'write') RETURN ra.principal_id, ra.principal_type, rd.role_name, ra.scope ``` ```cypher MATCH (sp:EntraServicePrincipal)-[:HAS_ROLE_ASSIGNMENT]->(ra:AzureRoleAssignment)-[:ROLE_ASSIGNED]->(rd:AzureRoleDefinition) WHERE rd.role_name IN ['Owner', 'Contributor', 'User Access Administrator'] RETURN sp.display_name, rd.role_name, ra.scope ``` -------------------------------- ### Manually run Neo4j container Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Initialize the graph database container with a dedicated network and volume for data persistence. ```bash # Create a docker network so that cartography can talk to neo4j docker network create cartography-network # run the Neo4j graph database docker run \ --publish=7474:7474 \ --publish=7687:7687 \ --network cartography-network \ -v data:/data \ --name cartography-neo4j \ --env=NEO4J_AUTH=none \ neo4j:5-community ``` -------------------------------- ### Configure Tailscale OAuth Client Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/tailscale/config.md Set the required environment variables and pass them to the cartography command to authenticate using an OAuth client. ```bash export TS_OAUTH_CLIENT_ID="" export TS_OAUTH_CLIENT_SECRET="" cartography \ --tailscale-oauth-client-id-env-var TS_OAUTH_CLIENT_ID \ --tailscale-oauth-client-secret-env-var TS_OAUTH_CLIENT_SECRET \ --tailscale-org example.com ``` -------------------------------- ### Abstract multiple permissions into one relationship Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/aws/permissions-mapping.md Example of grouping multiple DynamoDB permissions into a single 'CAN_QUERY' relationship. ```yaml - target_label: DynamoDBTable permissions: - dynamodb:BatchGetItem - dynamodb:GetItem - dynamodb:GetRecords - dynamodb:Query relationship_name: CAN_QUERY ``` -------------------------------- ### Run Unit Tests with dev.Dockerfile (Manual) Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Execute unit tests directly using the development Docker image without docker-compose. ```bash docker run --rm cartography-cncf/cartography-dev make test_unit ``` -------------------------------- ### List Available Rules Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Display all rules currently available in the system. ```bash cartography-rules list ``` -------------------------------- ### Define a complex GCP permission relationship Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gcp/permission-mapping.md Example of a YAML configuration that aggregates multiple permissions into a single management relationship. ```yaml - target_label: GCPBucket permissions: - storage.objects.get - storage.objects.create - storage.objects.update - storage.objects.delete relationship_name: CAN_MANAGE ``` -------------------------------- ### Run Kubernetes TLS Preflight Checks Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/kubernetes/config.md Diagnostic commands to inspect kubeconfig and API server version before syncing. ```bash kubectl config view --raw -o json kubectl get --raw=/version ``` -------------------------------- ### Cypher Index Definitions Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/writing-intel-modules.md Examples of Cypher code defining indexes for Cartography nodes and relationships. These are typically managed automatically by CartographyNodeSchema and CartographyRelSchema. ```cypher CREATE CONSTRAINT ON (n:GCPProject) ASSERT n.id IS UNIQUE; CREATE INDEX ON (n:GCPProject) INCLUDE GCPProject.partial_uri; ``` ```cypher CREATE CONSTRAINT ON (n:GCPVPC) ASSERT n.id IS UNIQUE; CREATE INDEX ON (n:GCPVPC) INCLUDE GCPVPC.partial_uri; ``` ```cypher CREATE CONSTRAINT ON (r:GCPNetworkTag) ASSERT r.id IS UNIQUE; ``` -------------------------------- ### Run Full Test Suite with docker-compose Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Execute the complete test suite (lint, unit, integration) using docker-compose. ```bash docker-compose run --rm cartography-dev make test_lint ``` ```bash docker-compose run --rm cartography-dev make test_unit ``` ```bash docker-compose run --rm cartography-dev make test_integration ``` ```bash # for all the above docker-compose run --rm cartography-dev make test ``` -------------------------------- ### Configure Neo4j authentication Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Provide database credentials via environment variables or an interactive prompt. ```bash cartography-rules run mfa-missing --neo4j-password-env-var MY_NEO4J_PASSWORD ``` ```bash cartography-rules run mfa-missing --neo4j-password-prompt ``` -------------------------------- ### Build dev.Dockerfile Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Build the development Docker image. Assumes the repository has been cloned. ```bash cd /path/to/cartography/repo # We are assuming that you've already cloned the cartography source code docker build -t cartography-cncf/cartography-dev -f dev.Dockerfile ./ ``` -------------------------------- ### Cartography Graph Cleanup Function Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/writing-intel-modules.md Example of a cleanup function for Cartography intel modules, utilizing GraphJob from node schemas to remove stale data. ```python def cleanup(neo4j_session: neo4j.Session, common_job_parameters: Dict) -> None: logger.debug("Running EMR cleanup job.") cleanup_job = GraphJob.from_node_schema(EMRClusterSchema(), common_job_parameters) cleanup_job.run(neo4j_session) ``` -------------------------------- ### List available rules Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Display all available rules or specific rule details. ```bash cartography-rules list ``` ```bash cartography-rules list mfa-missing ``` -------------------------------- ### Example AWS IAM Instance Profile Data Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/writing-intel-modules.md Represents the raw data structure for an AWS IAM instance profile, including associated roles. ```python INSTANCE_PROFILES = [ { "Path": "/", "InstanceProfileName": "my-instance-profile", "InstanceProfileId": "AIPA4SD", "Arn": "arn:aws:iam::1234:instance-profile/my-instance-profile", "CreateDate": datetime.datetime(2024, 12, 21, 23, 54, 16), "Roles": [ { "Path": "/", "RoleName": "role1", "RoleId": "AROA4", "Arn": "arn:aws:iam::1234:role/role1", "CreateDate": datetime.datetime(2024, 12, 21, 6, 53, 29), }, { "Path": "/", "RoleName": "role2", "RoleId": "AROA5", "Arn": "arn:aws:iam::1234:role/role2", "CreateDate": datetime.datetime(2024, 12, 21, 6, 53, 29), }, ], }, ] ``` -------------------------------- ### Programmatic CLI Usage - Default Sync Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/cli.md Use the Cartography CLI programmatically for testing by initializing the CLI with default sync settings and calling its main method with arguments. ```python import cartography.cli import cartography.sync # Default sync cli = cartography.cli.CLI(prog="cartography") exit_code = cli.main(["--neo4j-uri", "bolt://localhost:7687"]) ``` -------------------------------- ### Find GitHub Repositories Depending on a Specific Dependency Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/samplequeries.md Identify which GitHub repositories depend on a given dependency. This query uses 'boto3' as an example Python library. ```cypher MATCH (dep:Dependency:PythonLibrary{name:"boto3"})<-[req:REQUIRES]-(repo:GitHubRepository) RETURN repo.name, req.specifier, dep.version ``` -------------------------------- ### Run Security Rules Source: https://github.com/cartography-cncf/cartography/blob/master/README.md Execute all available security rules against the synchronized environment. ```bash cartography-rules run all ``` -------------------------------- ### Load matchlinks with properties Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/matchlinks.md Execute the loading process by passing the session, schema, mapping data, and required context variables. ```python load_matchlinks( neo4j_session, InspectorFindingToPackageMatchLink(), finding_to_package_mapping, lastupdated=update_tag, _sub_resource_label="AWSAccount", _sub_resource_id=account_id, ) ``` -------------------------------- ### Run Cartography with JumpCloud Options Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/jumpcloud/config.md Use this command to initiate Cartography's analysis of JumpCloud objects. Ensure the JUMPCLOUD_API_KEY environment variable is set and the correct JumpCloud Organization ID is provided. ```bash export JUMPCLOUD_API_KEY="your-api-key" cartography \ --neo4j-uri bolt://localhost:7687 \ --jumpcloud-api-key-env-var JUMPCLOUD_API_KEY \ --jumpcloud-org-id "" ``` -------------------------------- ### Define Relationships in Cartography Node Schema Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/writing-intel-modules.md Relationships can be defined using the 'sub_resource_relationship' or 'other_relationships' fields within a CartographyNodeSchema. This example shows a single relationship defined for an EMR cluster. ```python @dataclass(frozen=True) class EMRClusterSchema(CartographyNodeSchema): label: str = "EMRCluster" properties: EMRClusterNodeProperties = EMRClusterNodeProperties() sub_resource_relationship: EMRClusterToAWSAccountRel = EMRClusterToAWSAccountRel() ``` -------------------------------- ### Run Cartography CLI for Azure Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/azure/config.md CLI command to execute the Azure sync process using service principal authentication. ```bash --azure-sp-auth --azure-sync-all-subscriptions \ --azure-tenant-id ${AZURE_TENANT_ID} \ --azure-client-id ${AZURE_CLIENT_ID} \ --azure-client-secret-env-var AZURE_CLIENT_SECRET ``` -------------------------------- ### Enable Required GCP APIs Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gcp/config.md Commands to enable core and optional Google Cloud APIs on the host project. Replace YOUR_HOST_PROJECT with the actual project ID. ```bash # Core APIs (required) gcloud services enable cloudresourcemanager.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable serviceusage.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable iam.googleapis.com --project=YOUR_HOST_PROJECT # Optional APIs (enable based on what you want to sync) gcloud services enable compute.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable storage.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable container.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable dns.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable cloudkms.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable bigtableadmin.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable sqladmin.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable bigquery.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable bigqueryconnection.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable cloudfunctions.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable secretmanager.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable artifactregistry.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable run.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable aiplatform.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable notebooks.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable cloudasset.googleapis.com --project=YOUR_HOST_PROJECT gcloud services enable apikeys.googleapis.com --project=YOUR_HOST_PROJECT ``` -------------------------------- ### Enable Cloud Asset Inventory API Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gcp/config.md Command to enable the Cloud Asset Inventory API on the project hosting the service account. ```bash gcloud services enable cloudasset.googleapis.com --project=YOUR_SERVICE_ACCOUNT_PROJECT ``` -------------------------------- ### Sync from Self-Hosted GitLab Instance Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gitlab/config.md Use this command to sync data from a self-hosted GitLab instance. Ensure the GITLAB_TOKEN environment variable is set with your personal access token. ```bash export GITLAB_TOKEN="glpat-abc123xyz" cartography \ --neo4j-uri bolt://localhost:7687 \ --selected-modules gitlab \ --gitlab-url "https://gitlab.example.com" \ --gitlab-organization-id 12345678 \ --gitlab-token-env-var "GITLAB_TOKEN" ``` -------------------------------- ### Python: Fake Data for Testing Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/writing-intel-modules.md Example of how to define fake data for testing Cartography intel modules. This fake data is used in unit and integration tests to ensure data transformation logic works as expected. ```python # Example from tests/data/aws/ec2/instances.py # def load_ec2_instances(neo4j_session): # ... # return fake_instances ``` -------------------------------- ### Add Shortcuts for State Files Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/drift-detect.md Use shortcuts to bookmark specific states for easier comparison. You can use Unix timestamp filenames or aliases. ```bash cartography-detectdrift add-shortcut --shortcut first-run --file .json ``` ```bash cartography-detectdrift add-shortcut --shortcut second-run --file .json ``` ```bash cartography-detectdrift add-shortcut --shortcut baseline --file most-recent ``` -------------------------------- ### Generate Docker Scout Recommendations Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/docker_scout/config.md Generate a standard text output file containing Docker Scout recommendations for a given image. This file will be used by Cartography for ingestion. ```bash IMAGE="000000000000.dkr.ecr.us-east-1.amazonaws.com/my-app:latest" OUTPUT_DIR="./docker-scout-results" OUTPUT_FILE="${OUTPUT_DIR}/$(echo "$IMAGE" | tr '/:' '__').txt" mkdir -p "$OUTPUT_DIR" docker scout recommendations --output "$OUTPUT_FILE" "$IMAGE" ``` -------------------------------- ### GSuite OAuth Helper Script Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gsuite/config.md A Python script to assist with the OAuth flow for GSuite. It guides the user through obtaining credentials, fetching an authorization code, and testing the credentials by retrieving user data from the Admin SDK. ```python from __future__ import print_function import json import os from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build scopes = ["https://www.googleapis.com/auth/admin.directory.user.readonly", "https://www.googleapis.com/auth/admin.directory.group.readonly", "https://www.googleapis.com/auth/admin.directory.group.member"] print('Go to https://console.cloud.google.com/ > API & Services > Credentials and download secrets') project_id = input('Provide your project ID:') client_id = input('Provide your client ID:') client_secret = input('Provide your client secret:') with open('credentials.json', 'w', encoding='utf-8') as fc: data = { "installed": { "client_id": client_id, "project_id": project_id, "auth_uri":"https://accounts.google.com/o/oauth2/auth", "token_uri":"https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs", "client_secret":client_secret, "redirect_uris":["http://localhost"] }} json.dump(data, fc) flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', scopes) flow.redirect_uri = 'http://localhost' auth_url, _ = flow.authorization_url(prompt='consent') print(f'Please go to this URL: {auth_url}') code = input('Enter the authorization code: ') flow.fetch_token(code=code) creds = flow.credentials print('Testing your credentials by gettings first 10 users in the domain ...') service = build('admin', 'directory_v1', credentials=creds) print('Getting the first 10 users in the domain') results = service.users().list(customer='my_customer', maxResults=10, orderBy='email').execute() users = results.get('users', []) if not users: print('No users in the domain.') else: print('Users:') for user in users: print(u'{0} ({1})'.format(user['primaryEmail'], user['name']['fullName'])) print('Your credentials:') print(json.dumps(creds.to_json(), indent=2)) os.remove('credentials.json') ``` -------------------------------- ### Invoke Custom Sync Script Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Demonstrates how to execute a custom Python sync script from the command line. The output shows the stages of the sync process, including index creation and AWS ingestion. ```bash cartography$ python custom_sync.py INFO:cartography.sync:Starting sync with update tag '1569022981' INFO:cartography.sync:Starting sync stage 'create-indexes' INFO:cartography.intel.create_indexes:Creating indexes for cartography node types. INFO:cartography.sync:Finishing sync stage 'create-indexes' INFO:cartography.sync:Starting sync stage 'aws' INFO:botocore.credentials:Found credentials in shared credentials file: ~/.aws/credentials ... ``` -------------------------------- ### Find True First Launch Time for EC2 Instances Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/aws/schema.md Use the attach_time of the primary network interface (device_index: 0) to determine the original creation time of an EC2 instance, as the standard LaunchTime field reflects the most recent start time. ```cypher // Get the true first launch time for EC2 instances MATCH (i:EC2Instance)-[:NETWORK_INTERFACE]->(ni:NetworkInterface {device_index: 0}) WHERE ni.attach_time IS NOT NULL RETURN i.instanceid, i.launchtime as last_launch, ni.attach_time as first_launch ``` -------------------------------- ### Drift-Detection Shortcut Configuration Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/drift-detect.md This JSON file provides a name for the drift-detection monitor, which should match the 'name' in the template file. It also includes a placeholder for shortcuts. ```json { "name": "Internet Exposed EC2 Instances", "shortcuts": {} } ``` -------------------------------- ### Run security rules Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Execute security framework rules against the populated graph database. ```bash docker run --rm --network cartography-network cartography-cncf/cartography cartography-rules run all --uri bolt://cartography-neo4j:7687 --neo4j-password-prompt ``` -------------------------------- ### Run security rules Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Execute security framework rules against the graph database. ```bash docker-compose run --rm cartography cartography-rules run all --uri bolt://cartography-neo4j-1:7687 --neo4j-password-prompt ``` -------------------------------- ### Run Cartography Test Suites Source: https://github.com/cartography-cncf/cartography/blob/master/tests/AGENTS.md Use these Make targets to execute unit, integration, or the full suite of tests locally. ```bash make test_unit make test_integration make test ``` -------------------------------- ### Run Cartography CLI with dev.Dockerfile (Manual) Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Access the Cartography CLI using the development Docker image directly. ```bash docker run --rm cartography-cncf/cartography-dev cartography --help ``` -------------------------------- ### Filter and run rules by framework Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Filter and execute rules based on compliance framework short names, scopes, and revisions. ```bash # List all NIST AI RMF-mapped rules cartography-rules list --framework nist:ai-rmf # Run all NIST AI RMF-mapped rules cartography-rules run all --framework nist:ai-rmf ``` -------------------------------- ### Run Cartography with GitHub Module Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/github/config.md Execute the Cartography command using the configured environment variable. ```bash cartography --github-config-env-var GITHUB_CONFIG ``` -------------------------------- ### Display Cartography Help Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Shows CLI arguments or filters help output by specific modules. ```bash cartography --selected-modules aws --help ``` -------------------------------- ### Register the rule in the initialization module Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Import the rule object and add it to the RULES dictionary in the package's __init__.py file. ```python from cartography.rules.data.rules.my_rule import my_rule RULES = { # ... existing rules my_rule.id: my_rule, } ``` -------------------------------- ### Python: Basic Exception Handling Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/writing-intel-modules.md Illustrates recommended exception handling practices. Avoid catching the base `Exception` class and instead catch the narrowest possible exception class that your code can resolve. ```python # Example of good practice: # try: # # Code that might raise a specific exception # except SpecificError as e: # # Handle the error # Example of bad practice: # try: # # Code that might raise any exception # except Exception as e: # # This makes tracing problems difficult ``` -------------------------------- ### Run rules in text or JSON mode Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Execute all rules and specify the output format. ```bash cartography-rules run all # or cartography-rules run all --output text ``` ```bash cartography-rules run all --output json ``` -------------------------------- ### Authenticate and Create Service Principal Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/azure/config.md Commands to authenticate with Azure CLI and create a service principal with the Reader role. ```bash $ az login ``` ```bash $ az ad sp create-for-rbac --name cartography --role Reader ``` -------------------------------- ### File Structure Template Source: https://github.com/cartography-cncf/cartography/blob/master/AGENTS.md Recommended directory layout for a new Cartography service module. ```text cartography/intel/your_service/ ├── __init__.py # Main entry point └── entities.py # Domain sync modules cartography/models/your_service/ ├── entity.py # Data model definitions └── tenant.py # Tenant model tests/data/your_service/ └── entities.py # Mock test data tests/integration/cartography/intel/your_service/ └── test_entities.py # Integration tests ``` -------------------------------- ### Standard Sync Function Template Source: https://github.com/cartography-cncf/cartography/blob/master/AGENTS.md The primary entry point for a sync module, following the standard fetch-transform-load-cleanup lifecycle. ```python @timeit def sync(neo4j_session: neo4j.Session, api_key: str, tenant_id: str, update_tag: int, common_job_parameters: dict[str, Any]) -> None: """ Main sync entry point for the module. """ logger.info("Starting MyResource sync") # 1. GET - Fetch data from API logger.debug("Fetching MyResource data from API") raw_data = get(api_key, tenant_id) # 2. TRANSFORM - Shape data for ingestion logger.debug("Transforming %d MyResource items", len(raw_data)) transformed = transform(raw_data) # 3. LOAD - Ingest to Neo4j load_entities(neo4j_session, transformed, tenant_id, update_tag) # 4. CLEANUP - Remove stale data logger.debug("Running MyResource cleanup job") cleanup(neo4j_session, common_job_parameters) logger.info("Completed MyResource sync") ``` -------------------------------- ### Run Cartography with GitLab Module Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gitlab/config.md Execute Cartography, specifying the GitLab module, Neo4j connection details, the GitLab organization ID, and the environment variable containing the GitLab token. ```bash cartography \ --neo4j-uri bolt://localhost:7687 \ --selected-modules gitlab \ --gitlab-organization-id 12345678 \ --gitlab-token-env-var "GITLAB_TOKEN" ``` -------------------------------- ### Run Cartography Salesforce module Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/salesforce/config.md Executes the Salesforce module using environment variables for credentials and command-line arguments for configuration. ```bash export SALESFORCE_CLIENT_SECRET='' cartography \ --selected-modules salesforce \ --neo4j-uri bolt://localhost:7687 \ --salesforce-login-url 'https://mycompany.my.salesforce.com' \ --salesforce-client-id '' ``` -------------------------------- ### Define GCPCloudSQLBackupConfiguration relationships Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/gcp/schema.md Cypher queries representing the resource and ownership relationships for backup configuration nodes. ```cypher (GCPProject)-[:RESOURCE]->(GCPCloudSQLBackupConfiguration) ``` ```cypher (GCPCloudSQLInstance)-[:HAS_BACKUP_CONFIG]->(GCPCloudSQLBackupConfiguration) ``` -------------------------------- ### Configure Cartography with Local Directory Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/docker_scout/config.md Point Cartography to a local directory containing Docker Scout text result files. Cartography will recursively inspect and ingest matching files. ```bash cartography --selected-modules docker_scout \ --docker-scout-source /path/to/results ``` -------------------------------- ### Sync AWS Data Source Source: https://github.com/cartography-cncf/cartography/blob/master/README.md Execute a sync for AWS assets using the specified Neo4j URI. ```bash cartography --neo4j-uri bolt://localhost:7687 --selected-modules aws ``` -------------------------------- ### Run Custom Sync Script with dev.Dockerfile (Manual) Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/dev/developer-guide.md Execute a custom Python sync script using the development Docker image directly. ```bash docker run --rm cartography-cncf/cartography-dev python custom_sync.py ``` -------------------------------- ### Configure Cartography with Spacelift API Key Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/spacelift/config.md Use this command to configure Cartography with Spacelift API key credentials stored in environment variables. This method is recommended for its use of short-lived tokens. ```bash cartography \ --spacelift-api-endpoint https://YOUR_ACCOUNT.app.spacelift.io/graphql \ --spacelift-api-key-id-env-var SPACELIFT_API_KEY_ID \ --spacelift-api-key-secret-env-var SPACELIFT_API_KEY_SECRET ``` -------------------------------- ### Define a Rule with an output model Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Register the rule by referencing the output model class and providing metadata. ```python class ObjectStoragePublic(Finding): name: str | None = None id: str | None = None region: str | None = None public_access: bool | None = None account: str | None = None # For Azure storage accounts object_storage_public = Rule( id="object_storage_public", name="Public Object Storage Attack Surface", description="Publicly accessible object storage services", output_model=ObjectStoragePublic, # Reference the output model class facts=(...), tags=("infrastructure", "attack_surface"), version="0.1.0", ) ``` -------------------------------- ### Configure Neo4j Credentials Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/install.md Sets the Neo4j password via environment variable and runs Cartography with specific connection flags. ```bash export NEO4J_PASSWORD="your-password" cartography --neo4j-uri bolt://localhost:7687 --neo4j-user neo4j --neo4j-password-env-var NEO4J_PASSWORD ``` -------------------------------- ### Set Environment Variable for Configuration Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/github/config.md Export the base64-encoded configuration string as an environment variable. ```bash export GITHUB_CONFIG="eyJvcmdhbml6YXRpb24iOi..." ``` -------------------------------- ### Configure Neo4j Environment Variables Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Set the necessary environment variables to connect Cartography to your Neo4j instance. Use set +o history to prevent the password from being saved in shell logs. ```bash export NEO4J_URI=bolt://localhost:7687 # or your Neo4j URI export NEO4J_USER=neo4j # or your username export NEO4J_DATABASE=neo4j # or your database name # Store the Neo4j password in an environment variable. You can name this anything you want. set +o history # avoid storing the password in the shell history; can also use something like 1password CLI. export NEO4J_PASSWORD=password set -o history # turn shell history back on ``` -------------------------------- ### Define and Version Cartography Rules Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/rules.md Demonstrates the evolution of a rule definition from experimental facts to stable production-ready status. ```python # Version 0.1.0 - Initial release object_storage_public = Rule( id="object_storage_public", name="Public Object Storage Attack Surface", description="Publicly accessible object storage services such as AWS S3 buckets and Azure Storage Blob Containers", tags=("infrastructure", "attack_surface"), output_model=ObjectStoragePublic, facts=( _aws_s3_public, # EXPERIMENTAL - new query ), version="0.1.0", ) # Version 0.2.0 - Added Azure support object_storage_public = Rule( id="object_storage_public", name="Public Object Storage Attack Surface", description="Publicly accessible object storage services such as AWS S3 buckets and Azure Storage Blob Containers", tags=("infrastructure", "attack_surface"), output_model=ObjectStoragePublic, facts=( _aws_s3_public, # EXPERIMENTAL _azure_storage_public, # EXPERIMENTAL - newly added ), version="0.2.0", ) # Version 0.2.1 - Bug fix # AWS query fixed, no version bump for facts themselves # Version 1.0.0 - Production ready object_storage_public = Rule( id="object_storage_public", name="Public Object Storage Attack Surface", description="Publicly accessible object storage services such as AWS S3 buckets and Azure Storage Blob Containers", tags=("infrastructure", "attack_surface"), output_model=ObjectStoragePublic, facts=( _aws_s3_public, # STABLE - promoted after extensive testing _azure_storage_public, # STABLE - promoted after extensive testing ), version="1.0.0", ) ``` -------------------------------- ### Identify SageMaker Notebook Creation and Role Passing Permissions Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/usage/aws-privilege-escalation-queries.md Use this query to detect principals with permissions to create SageMaker notebook instances and pass roles to them. This combination can be exploited to gain access to the notebook's credentials and associated privileges. ```cypher MATCH p=(stmt:AWSPolicyStatement)--(pol:AWSPolicy)--(principal:AWSPrincipal)--(a:AWSAccount) WHERE stmt.effect = "Allow" AND (any(x in stmt.action WHERE x = "sagemaker:CreateNotebookInstance") AND any(x in stmt.action WHERE x = "sagemaker:CreatePresignedNotebookInstanceUrl") AND any(x in stmt.action WHERE x = "iam:PassRole")) RETURN p ``` -------------------------------- ### Configure Cartography with GitHub App Authentication Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/github/config.md Define the configuration object using GitHub App credentials instead of a PAT. ```python config = { "organization": [ { "client_id": "Iv1.abc123def456", "private_key": open("your-app.private-key.pem").read(), "installation_id": "12345678", "url": "https://api.github.com/graphql", "name": "your-org-name", }, ] } ``` -------------------------------- ### Configure Cartography with PAT Authentication Source: https://github.com/cartography-cncf/cartography/blob/master/docs/root/modules/github/config.md Create a base64-encoded JSON configuration object for GitHub Personal Access Tokens. ```python import json import base64 config = { "organization": [ { "token": "ghp_your_token_here", "url": "https://api.github.com/graphql", "name": "your-org-name", }, # Optional: Add additional orgs or GitHub Enterprise instances # { # "token": "ghp_enterprise_token", # "url": "https://github.example.com/api/graphql", # "name": "enterprise-org-name", # }, ] } # Encode the configuration encoded = base64.b64encode(json.dumps(config).encode()).decode() print(encoded) ```