Created
August 21, 2025 07:20
-
-
Save arc279/2fac10a6ed2b11ee9722028ab5ef6225 to your computer and use it in GitHub Desktop.
boto3 の ssm start-session で session-manager-plugin に処理を流す
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
| """ | |
| 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