Skip to content

Instantly share code, notes, and snippets.

@arc279
Created August 21, 2025 07:20
Show Gist options
  • Save arc279/2fac10a6ed2b11ee9722028ab5ef6225 to your computer and use it in GitHub Desktop.
Save arc279/2fac10a6ed2b11ee9722028ab5ef6225 to your computer and use it in GitHub Desktop.
boto3 の ssm start-session で session-manager-plugin に処理を流す
"""
cf. https://github.com/aws/aws-cli/blob/45b0063b2d0b245b17a57fd9eebd9fcc87c4426a/awscli/customizations/sessionmanager.py#L83
"""
import os
import json
import subprocess
import boto3
instance_id = os.getenv("INSTANCE_ID")
region_name = os.getenv("AWS_REGION")
profile_name = os.getenv("AWS_PROFILE")
def main():
s = boto3.Session(profile_name=profile_name)
client = s.client("ssm", region_name=region_name)
parameters = dict(
Target=instance_id,
DocumentName="AWS-StartNonInteractiveCommand",
Parameters={"command": ["whoami"]},
)
res = client.start_session(**parameters)
# print(res)
result = subprocess.run(
[
"session-manager-plugin",
json.dumps(res),
region_name,
"StartSession",
profile_name,
json.dumps(parameters),
client.meta.endpoint_url,
],
capture_output=True,
)
print(result.stdout.decode("utf-8"))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment