import json


def format_containers(containers, json_out):
    """Format container data for Ansible

    Args:
        containers: [(hostname, metadata), ...]
        json_out: If True, return JSON, else dictionary.

    Returns:
        Dictionary of container information formatted to Ansible specs.
    """
    data = {'all': {'vars': {'ansible_connection': 'docker'}, 'hosts': [], '_meta': {'hostvars': {}}}}
    for host, metadata in containers:
        # docs use dict keys set to none, but maybe all is special?
        # data['all']['hosts'][host] = None
        data['all']['hosts'].append(host)
        if metadata:
            data['all']['_meta']['hostvars'][host] = {'docker_metadata': metadata}

    return json.dumps(data) if json_out else data