# Buggy code
def new_swapped_deployment(
    old_deployment: Dict,
    container_to_update: str,
    run_id: str,
    telepresence_image: str,
    add_custom_nameserver: bool,
) -> Tuple[Dict, Dict]:
    """
    Create a new Deployment that uses telepresence-k8s image.

    Makes the following changes:

    1. Changes to single replica.
    2. Disables command, args, livenessProbe, readinessProbe, workingDir.
    3. Adds labels.
    4. Adds TELEPRESENCE_NAMESERVER env variable, if requested.
    5. Runs as root, if requested.
    6. Sets terminationMessagePolicy.
    7. Adds TELEPRESENCE_CONTAINER_NAMESPACE env variable so the forwarder does
       not have to access the k8s API from within the pod.

    Returns dictionary that can be encoded to JSON and used with kubectl apply,
    and contents of swapped out container.
    """
    new_deployment_json = deepcopy(old_deployment)
    new_deployment_json["spec"]["replicas"] = 1
    new_deployment_json["metadata"].setdefault("labels", {})["telepresence"] = run_id
    new_deployment_json["spec"]["template"]["metadata"].setdefault("labels", {})[
        "telepresence"
    ] = run_id
    for container, old_container in zip(
        new_deployment_json["spec"]["template"]["spec"]["containers"],
        old_deployment["spec"]["template"]["spec"]["containers"],
    ):
        if container["name"] == container_to_update:
            container["image"] = telepresence_image
            # Not strictly necessary for real use, but tests break without this
            # since we don't upload test images to Docker Hub:
            container["imagePullPolicy"] = "IfNotPresent"
            # Drop unneeded fields:
            for unneeded in [
                "command",
                "args",
                "livenessProbe",
                "readinessProbe",
                "workingDir",
            ]:
                try:
                    container.pop(unneeded)
                except KeyError:
                    pass
            # We don't write out termination file:
            container["terminationMessagePolicy"] = "FallbackToLogsOnError"
            # Use custom name server if necessary:
            if add_custom_nameserver:
                container.setdefault("env", []).append(
                    {
                        "name": "TELEPRESENCE_NAMESERVER",
                        "value": get_alternate_nameserver(),
                    }
                )
            # Add namespace environment variable to support deployments using
            # automountServiceAccountToken: false. To be used by forwarder.py
            # in the k8s-proxy.
            container.setdefault("env", []).append(
                {
                    "name": "TELEPRESENCE_CONTAINER_NAMESPACE",
                    "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}},
                }
            )
            return new_deployment_json, old_container

    raise RuntimeError(
        "Couldn't find container {} in the Deployment.".format(container_to_update)
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/local/Cellar/telepresence/0.82/libexec/lib/python3.6/site-packages/telepresence/cli.py", line 74, in call_f
return f(*args, **kwargs)
File "/usr/local/Cellar/telepresence/0.82/libexec/lib/python3.6/site-packages/telepresence/main.py", line 494, in go_too
runner, args
File "/usr/local/Cellar/telepresence/0.82/libexec/lib/python3.6/site-packages/telepresence/main.py", line 304, in start_proxy
run_id=run_id,
File "/usr/local/Cellar/telepresence/0.82/libexec/lib/python3.6/site-packages/telepresence/remote.py", line 214, in get_remote_info
wait_for_pod(runner, remote_info)
File "/usr/local/Cellar/telepresence/0.82/libexec/lib/python3.6/site-packages/telepresence/remote.py", line 135, in wait_for_pod
"Pod isn't starting or can't be found: {}".format(pod["status"])
RuntimeError: Pod isn't starting or can't be found: {'conditions': [{'lastProbeTime': None, 'lastTransitionTime': '2018-04-12T09:04:39Z', 'status': 'True', 'type': 'Initialized'}, {'lastProbeTime': None, 'lastTransitionTime': '2018-04-12T09:04:39Z', 'message': 'containers with unready status: [triggers-cfapi]', 'reason': 'ContainersNotReady', 'status': 'False', 'type': 'Ready'}, {'lastProbeTime': None, 'lastTransitionTime': '2018-04-12T09:04:39Z', 'status': 'True', 'type': 'PodScheduled'}], 'containerStatuses': [{'containerID': 'docker://7b35045a5dc6c85e336eea9ff5d4c4120b1b329ff709be32348209c617703c08', 'image': 'datawire/telepresence-k8s:0.82', 'imageID': 'docker-pullable://datawire/telepresence-k8s@sha256:4ce9feb392c1f2a79d71e7cc9417b5038729cfd2e8a03bdc645d8a59b4e3a11c', 'lastState': {'terminated': {'containerID': 'docker://7b35045a5dc6c85e336eea9ff5d4c4120b1b329ff709be32348209c617703c08', 'exitCode': 137, 'finishedAt': '2018-04-12T09:06:10Z', 'message': "Listening...\n2018-04-12T09:05:30+0000 [-] Loading ./forwarder.py...\n2018-04-12T09:05:31+0000 [-] /etc/resolv.conf changed, reparsing\n2018-04-12T09:05:31+0000 [-] Resolver added ('10.151.240.10', 53) to server list\n2018-04-12T09:05:31+0000 [-] SOCKSv5Factory starting on 9050\n2018-04-12T09:05:31+0000 [socks.SOCKSv5Factory#info] Starting factory <socks.SOCKSv5Factory object at 0x7ffa4a5f76a0>\n2018-04-12T09:05:31+0000 [-] DNSDatagramProtocol starting on 9053\n2018-04-12T09:05:31+0000 [-] Starting protocol <twisted.names.dns.DNSDatagramProtocol object at 0x7ffa4a5f7a20>\n2018-04-12T09:05:31+0000 [-] Loaded.\n2018-04-12T09:05:31+0000 [twisted.scripts._twistd_unix.UnixAppLogger#info] twistd 17.9.0 (/usr/bin/python3.6 3.6.1) starting up.\n2018-04-12T09:05:31+0000 [twisted.scripts._twistd_unix.UnixAppLogger#info] reactor class: twisted.internet.epollreactor.EPollReactor.\n", 'reason': 'Error', 'startedAt': '2018-04-12T09:05:30Z'}}, 'name': 'triggers-cfapi', 'ready': False, 'restartCount': 1, 'state': {'waiting': {'message': 'Back-off 10s restarting failed container=triggers-cfapi pod=triggers-cfapi-b6bd5dd78-wk77z_triggers(87e8069f-3e30-11e8-81b4-42010a80010a)', 'reason': 'CrashLoopBackOff'}}}], 'hostIP': '10.240.0.11', 'phase': 'Running', 'podIP': '10.148.28.160', 'qosClass': 'BestEffort', 'startTime': '2

# Fixed code
def new_swapped_deployment(
    old_deployment: Dict,
    container_to_update: str,
    run_id: str,
    telepresence_image: str,
    add_custom_nameserver: bool,
) -> Tuple[Dict, Dict]:
    """
    Create a new Deployment that uses telepresence-k8s image.

    Makes the following changes:

    1. Changes to single replica.
    2. Disables command, args, livenessProbe, readinessProbe, workingDir.
    3. Adds labels.
    4. Adds TELEPRESENCE_NAMESERVER env variable, if requested.
    5. Runs as root, if requested.
    6. Sets terminationMessagePolicy.
    7. Adds TELEPRESENCE_CONTAINER_NAMESPACE env variable so the forwarder does
       not have to access the k8s API from within the pod.

    Returns dictionary that can be encoded to JSON and used with kubectl apply,
    and contents of swapped out container.
    """
    new_deployment_json = deepcopy(old_deployment)
    new_deployment_json["spec"]["replicas"] = 1
    new_deployment_json["metadata"].setdefault("labels", {})["telepresence"] = run_id
    new_deployment_json["spec"]["template"]["metadata"].setdefault("labels", {})[
        "telepresence"
    ] = run_id
    for container, old_container in zip(
        new_deployment_json["spec"]["template"]["spec"]["containers"],
        old_deployment["spec"]["template"]["spec"]["containers"],
    ):
        if container["name"] == container_to_update:
            container["image"] = telepresence_image
            # Not strictly necessary for real use, but tests break without this
            # since we don't upload test images to Docker Hub:
            container["imagePullPolicy"] = "IfNotPresent"
            # Drop unneeded fields:
            for unneeded in [
                "command",
                "args",
                "livenessProbe",
                "readinessProbe",
                "workingDir",
                "lifecycle",
            ]:
                try:
                    container.pop(unneeded)
                except KeyError:
                    pass
            # We don't write out termination file:
            container["terminationMessagePolicy"] = "FallbackToLogsOnError"
            # Use custom name server if necessary:
            if add_custom_nameserver:
                container.setdefault("env", []).append(
                    {
                        "name": "TELEPRESENCE_NAMESERVER",
                        "value": get_alternate_nameserver(),
                    }
                )
            # Add namespace environment variable to support deployments using
            # automountServiceAccountToken: false. To be used by forwarder.py
            # in the k8s-proxy.
            container.setdefault("env", []).append(
                {
                    "name": "TELEPRESENCE_CONTAINER_NAMESPACE",
                    "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}},
                }
            )
            return new_deployment_json, old_container

    raise RuntimeError(
        "Couldn't find container {} in the Deployment.".format(container_to_update)
    )