Created
August 4, 2022 19:17
-
-
Save 2XXE-SRA/f9d626cb055fac96b370eb47a9cc9b46 to your computer and use it in GitHub Desktop.
Docker daemon via SSM session port forward
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import docker | |
import os | |
import boto3 | |
import subprocess | |
TARGET_INSTANCE = "<instance ID>" | |
LOCAL_PORT = "9999" | |
REGION = "us-east-1" | |
PROFILE = "default" | |
session = boto3.session.Session(profile_name=PROFILE) | |
ssm = session.client("ssm") | |
params = { | |
"portNumber": ["2375"], | |
"localPortNumber": [LOCAL_PORT] | |
} | |
res = ssm.start_session( | |
Target=TARGET_INSTANCE, | |
DocumentName="AWS-StartPortForwardingSession", | |
Reason="Port Forward", | |
Parameters=params | |
) | |
command = [ | |
"session-manager-plugin", | |
json.dumps(res), | |
REGION, | |
"StartSession", | |
PROFILE, | |
json.dumps({"Target": TARGET_INSTANCE}), | |
ssm.meta.endpoint_url | |
] | |
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
env = dict(os.environ) | |
env["DOCKER_HOST"] = f"tcp://127.0.0.1:{LOCAL_PORT}" | |
client = docker.from_env(environment=env) | |
ver = client.version() | |
proc.terminate() | |
ssm.terminate_session( | |
SessionId=res["SessionId"] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment