Debian Codegraph @

ansible_collections/amazon/aws/plugins/connection/aws_ssm.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2018, Pat Sharkey <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 # Based on the ssh connection plugin by Michael DeHaan
7
8
9 DOCUMENTATION = r"""
10 name: aws_ssm
11 author:
12 - Pat Sharkey (@psharkey) <[email protected]>
13 - HanumanthaRao MVL (@hanumantharaomvl) <[email protected]>
14 - Gaurav Ashtikar (@gau1991) <[email protected]>
15
16 version_added: 1.0.0
17 version_added_collection: community.aws
18 short_description: connect to EC2 instances via AWS Systems Manager
19 description:
20 - This connection plugin allows Ansible to execute tasks on an EC2 instance via an AWS SSM Session.
21 notes:
22 - The C(amazon.aws.aws_ssm) connection plugin does not support using the ``remote_user`` and
23 ``ansible_user`` variables to configure the remote user. The ``become_user`` parameter should
24 be used to configure which user to run commands as. Remote commands will often default to
25 running as the ``ssm-agent`` user, however this will also depend on how SSM has been configured.
26 - This plugin requires an S3 bucket to send files to/from the remote instance. This is required even for modules
27 which do not explicitly send files (such as the C(shell) or C(command) modules), because Ansible sends over the C(.py) files of the module itself, via S3.
28 - Files sent via S3 will be named in S3 with the EC2 host ID (e.g. C(i-123abc/)) as the prefix.
29 - The files in S3 will be deleted by the end of the playbook run. If the play is terminated ungracefully, the files may remain in the bucket.
30 If the bucket has versioning enabled, the files will remain in version history. If your tasks involve sending secrets to/from the remote instance
31 (e.g. within a C(shell) command, or a SQL password in the C(community.postgresql.postgresql_query) module) then those passwords will be included in
32 plaintext in those files in S3 indefinitely, visible to anyone with access to that bucket. Therefore it is recommended to use a bucket with versioning
33 disabled/suspended.
34 - The files in S3 will be deleted even if the C(keep_remote_files) setting is C(true).
35
36 requirements:
37 - The remote EC2 instance must be running the AWS Systems Manager Agent (SSM Agent).
38 U(https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html)
39 - The control machine must have the AWS session manager plugin installed.
40 U(https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html)
41 - The remote EC2 Linux instance must have curl installed.
42 - The remote EC2 Linux instance and the controller both need network connectivity to S3.
43 - The remote instance does not require IAM credentials for S3. This module will generate a presigned URL for S3 from the controller,
44 and then will pass that URL to the target over SSM, telling the target to download/upload from S3 with C(curl).
45 - The controller requires IAM permissions to upload, download and delete files from the specified S3 bucket. This includes
46 `s3:GetObject`, `s3:PutObject`, `s3:ListBucket`, `s3:DeleteObject` and `s3:GetBucketLocation`.
47
48 options:
49 access_key_id:
50 description: The STS access key to use when connecting via session-manager.
51 vars:
52 - name: ansible_aws_ssm_access_key_id
53 env:
54 - name: AWS_ACCESS_KEY_ID
55 version_added: 1.3.0
56 secret_access_key:
57 description: The STS secret key to use when connecting via session-manager.
58 vars:
59 - name: ansible_aws_ssm_secret_access_key
60 env:
61 - name: AWS_SECRET_ACCESS_KEY
62 version_added: 1.3.0
63 session_token:
64 description: The STS session token to use when connecting via session-manager.
65 vars:
66 - name: ansible_aws_ssm_session_token
67 env:
68 - name: AWS_SESSION_TOKEN
69 version_added: 1.3.0
70 instance_id:
71 description: The EC2 instance ID.
72 vars:
73 - name: ansible_aws_ssm_instance_id
74 region:
75 description: The region the EC2 instance is located.
76 vars:
77 - name: ansible_aws_ssm_region
78 env:
79 - name: AWS_REGION
80 - name: AWS_DEFAULT_REGION
81 default: 'us-east-1'
82 bucket_name:
83 description: The name of the S3 bucket used for file transfers.
84 vars:
85 - name: ansible_aws_ssm_bucket_name
86 bucket_endpoint_url:
87 description: The S3 endpoint URL of the bucket used for file transfers.
88 vars:
89 - name: ansible_aws_ssm_bucket_endpoint_url
90 version_added: 5.3.0
91 plugin:
92 description:
93 - This defines the location of the session-manager-plugin binary.
94 - Support for environment variable was added in version 9.1.0.
95 - The plugin will first check the V('/usr/local/bin/session-manager-plugin') as the default path of the SSM plugin
96 if this does not exist, it will find the session-manager-plugin from the PATH environment variable. Added in version 9.1.0.
97 vars:
98 - name: ansible_aws_ssm_plugin
99 env:
100 - name: AWS_SESSION_MANAGER_PLUGIN
101 profile:
102 description: Sets AWS profile to use.
103 vars:
104 - name: ansible_aws_ssm_profile
105 env:
106 - name: AWS_PROFILE
107 version_added: 1.5.0
108 reconnection_retries:
109 description: Number of attempts to connect.
110 default: 3
111 type: integer
112 vars:
113 - name: ansible_aws_ssm_retries
114 ssm_timeout:
115 description: Connection timeout seconds.
116 default: 60
117 type: integer
118 vars:
119 - name: ansible_aws_ssm_timeout
120 bucket_sse_mode:
121 description: Server-side encryption mode to use for uploads on the S3 bucket used for file transfer.
122 choices: [ 'AES256', 'aws:kms' ]
123 required: false
124 version_added: 2.2.0
125 vars:
126 - name: ansible_aws_ssm_bucket_sse_mode
127 bucket_sse_kms_key_id:
128 description: KMS key id to use when encrypting objects using C(bucket_sse_mode=aws:kms). Ignored otherwise.
129 version_added: 2.2.0
130 vars:
131 - name: ansible_aws_ssm_bucket_sse_kms_key_id
132 ssm_document:
133 description:
134 - SSM Session document to use when connecting.
135 - To configure the remote_user (when C(become=False), it is possible to use an SSM Session
136 document and define the C(runAsEnabled) and C(runAsDefaultUser) parameters. See also
137 U(https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-schema.html)
138 vars:
139 - name: ansible_aws_ssm_document
140 version_added: 5.2.0
141 s3_addressing_style:
142 description:
143 - The addressing style to use when using S3 URLs.
144 - When the S3 bucket isn't in the same region as the Instance
145 explicitly setting the addressing style to 'virtual' may be necessary
146 U(https://repost.aws/knowledge-center/s3-http-307-response) as this forces
147 the use of a specific endpoint.
148 choices: [ 'path', 'virtual', 'auto' ]
149 default: 'auto'
150 version_added: 5.2.0
151 vars:
152 - name: ansible_aws_ssm_s3_addressing_style
153 """
154
155 EXAMPLES = r"""
156 ---
157 # Wait for SSM Agent to be available on the Instance
158 - name: Wait for connection to be available
159 vars:
160 ansible_connection: aws_ssm
161 ansible_aws_ssm_bucket_name: nameofthebucket
162 ansible_aws_ssm_region: us-west-2
163 # When the S3 bucket isn't in the same region as the Instance
164 # Explicitly setting the addressing style to 'virtual' may be necessary
165 # https://repost.aws/knowledge-center/s3-http-307-response
166 ansible_aws_ssm_s3_addressing_style: virtual
167 tasks:
168 - name: Wait for connection
169 wait_for_connection:
170
171 # Stop Spooler Process on Windows Instances
172 - name: Stop Spooler Service on Windows Instances
173 vars:
174 ansible_connection: aws_ssm
175 ansible_shell_type: powershell
176 ansible_aws_ssm_bucket_name: nameofthebucket
177 ansible_aws_ssm_region: us-east-1
178 tasks:
179 - name: Stop spooler service
180 win_service:
181 name: spooler
182 state: stopped
183
184 # Install a Nginx Package on Linux Instance
185 - name: Install a Nginx Package
186 vars:
187 ansible_connection: aws_ssm
188 ansible_aws_ssm_bucket_name: nameofthebucket
189 ansible_aws_ssm_region: us-west-2
190 tasks:
191 - name: Install a Nginx Package
192 yum:
193 name: nginx
194 state: present
195
196 # Create a directory in Windows Instances
197 - name: Create a directory in Windows Instance
198 vars:
199 ansible_connection: aws_ssm
200 ansible_shell_type: powershell
201 ansible_aws_ssm_bucket_name: nameofthebucket
202 ansible_aws_ssm_region: us-east-1
203 tasks:
204 - name: Create a Directory
205 win_file:
206 path: C:\Windows\temp
207 state: directory
208
209 ---
210
211 # Making use of Dynamic Inventory Plugin
212 # =======================================
213 # # aws_ec2.yml (Dynamic Inventory - Linux)
214 # plugin: aws_ec2
215 # regions:
216 # - us-east-1
217 # hostnames:
218 # - instance-id
219 # # This will return the Instances with the tag "SSMTag" set to "ssmlinux"
220 # filters:
221 # tag:SSMTag: ssmlinux
222 # -----------------------
223 - name: install aws-cli
224 hosts: all
225 gather_facts: false
226 vars:
227 ansible_connection: aws_ssm
228 ansible_aws_ssm_bucket_name: nameofthebucket
229 ansible_aws_ssm_region: us-east-1
230 tasks:
231 - name: aws-cli
232 raw: yum install -y awscli
233 tags: aws-cli
234
235 # Alternatively, you can use a tag (eg. Name) as hostname instead of InstanceID.
236 # However, "ansible_host" must still be set to the instance_id
237 # =======================================
238 # # aws_ec2.yml (Dynamic Inventory - Linux)
239 # plugin: aws_ec2
240 # regions:
241 # - us-east-1
242 # hostnames:
243 # - tag:Name # will return `tag:Name` for hostname
244 # compose:
245 # ansible_host: instance_id # but connection will be done to InstanceID
246 ---
247
248 # Execution: ansible-playbook windows.yaml -i aws_ec2.yml
249 # =====================================================
250 # # aws_ec2.yml (Dynamic Inventory - Windows)
251 # plugin: aws_ec2
252 # regions:
253 # - us-east-1
254 # hostnames:
255 # - instance-id
256 # # This will return the Instances with the tag "SSMTag" set to "ssmwindows"
257 # filters:
258 # tag:SSMTag: ssmwindows
259 # -----------------------
260 - name: Create a dir.
261 hosts: all
262 gather_facts: false
263 vars:
264 ansible_connection: aws_ssm
265 ansible_shell_type: powershell
266 ansible_aws_ssm_bucket_name: nameofthebucket
267 ansible_aws_ssm_region: us-east-1
268 tasks:
269 - name: Create the directory
270 win_file:
271 path: C:\Temp\SSM_Testing5
272 state: directory
273
274 ---
275
276 # Execution: ansible-playbook win_file.yaml -i aws_ec2.yml
277 # The playbook tasks will get executed on the instance ids returned from the dynamic inventory plugin using ssm connection.
278
279 # Install a Nginx Package on Linux Instance; with specific SSE CMK used for the file transfer
280 - name: Install a Nginx Package
281 vars:
282 ansible_connection: aws_ssm
283 ansible_aws_ssm_bucket_name: nameofthebucket
284 ansible_aws_ssm_region: us-west-2
285 ansible_aws_ssm_bucket_sse_mode: 'aws:kms'
286 ansible_aws_ssm_bucket_sse_kms_key_id: alias/kms-key-alias
287 tasks:
288 - name: Install a Nginx Package
289 yum:
290 name: nginx
291 state: present
292
293 # Install a Nginx Package on Linux Instance; using the specified SSM document
294 - name: Install a Nginx Package
295 vars:
296 ansible_connection: aws_ssm
297 ansible_aws_ssm_bucket_name: nameofthebucket
298 ansible_aws_ssm_region: us-west-2
299 ansible_aws_ssm_document: nameofthecustomdocument
300 tasks:
301 - name: Install a Nginx Package
302 yum:
303 name: nginx
304 state: present
305
306 ---
307 # Execution: ansible-playbook play.yaml -i ssm_inventory.ini
308 # =====================================================
309 # ssm_inventory.ini
310 # [all]
311 # linux ansible_aws_ssm_instance_id=i-01234567829abcdef ansible_aws_ssm_region=us-east-1
312
313 # [all:vars]
314 # ansible_connection=amazon.aws.aws_ssm
315 # ansible_python_interpreter=/usr/bin/python3
316 # local_tmp=/tmp/ansible-local-ssm-0123456
317 # ansible_aws_ssm_bucket_name=my-test-bucket
318 # ansible_aws_ssm_s3_addressing_style=virtual
319 # -----------------------
320 # Transfer file and run script on remote host
321 - name: Transfer file and Run script into SSM manage node
322 hosts: all
323 gather_facts: false
324
325 tasks:
326 - name: Create shell script
327 ansible.builtin.copy:
328 mode: '0755'
329 dest: '/tmp/date.sh'
330 content: |
331 #!/usr/bin/env bash
332 date
333
334 - name: Execute script from remote host
335 ansible.builtin.shell:
336 cmd: '/tmp/date.sh'
337 """
338 import getpass
339 import os
340 import random
341 import re
342 import string
343 from typing import Any
344 from typing import Dict
345 from typing import Iterator
346 from typing import List
347 from typing import Tuple
348
349 from ansible.errors import AnsibleError
350 from ansible.errors import AnsibleFileNotFound
351 from ansible.module_utils.basic import missing_required_lib
352 from ansible.module_utils.common.process import get_bin_path
353 from ansible.module_utils.common.text.converters import to_bytes
354 from ansible.module_utils.common.text.converters import to_text
355 from ansible.plugins.connection import ConnectionBase
356 from ansible.utils.display import Display
357
358 from ansible_collections.amazon.aws.plugins.module_utils.botocore import HAS_BOTO3
359 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.base import AwsConnectionPluginBase
360 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.common import CommandResult
361 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.common import ssm_retry
362 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.filetransfermanager import FileTransferManager
363 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.s3clientmanager import S3ClientManager
364 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.sessionmanager import SSMSessionManager
365 from ansible_collections.amazon.aws.plugins.plugin_utils.ssm.terminalmanager import TerminalManager
366
367 display = Display()
368
369
370 def chunks(lst: List, n: int) -> Iterator[List[Any]]:
371 """Yield successive n-sized chunks from lst."""
372 for i in range(0, len(lst), n):
373 yield lst[i:i + n] # fmt: skip
374
375
376 def filter_ansi(line: str, is_windows: bool) -> str:
377 """Remove any ANSI terminal control codes.
378
379 :param line: The input line.
380 :param is_windows: Whether the output is coming from a Windows host.
381 :returns: The result line.
382 """
383 line = to_text(line)
384
385 if is_windows:
386 osc_filter = re.compile(r"\x1b\][^\x07]*\x07")
387 line = osc_filter.sub("", line)
388 ansi_filter = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]")
389 line = ansi_filter.sub("", line)
390
391 # Replace or strip sequence (at terminal width)
392 line = line.replace("\r\r\n", "\n")
393 if len(line) == 201:
394 line = line[:-1]
395
396 return line
397
398
399 def escape_path(path: str) -> str:
400 """
401 Converts a file path to a safe format by replacing backslashes with forward slashes.
402 :param path: The file path to escape.
403 :return: The escaped file path.
404 """
405 return path.replace("\\", "/")
406
407
408 class Connection(ConnectionBase, AwsConnectionPluginBase):
409 """AWS SSM based connections"""
410
411 transport = "amazon.aws.aws_ssm"
412 default_user = ""
413
414 allow_executable = False
415 allow_extras = True
416 has_pipelining = False
417 is_windows = False
418
419 _client = None
420 _s3_manager = None
421 _session_manager = None
422 MARK_LENGTH = 26
423
424 def __init__(self, *args: Any, **kwargs: Any) -> None:
425 super().__init__(*args, **kwargs)
426
427 if not HAS_BOTO3:
428 raise AnsibleError(missing_required_lib("boto3"))
429
430 self.host = self._play_context.remote_addr
431 self._instance_id = None
432 self.terminal_manager = TerminalManager(self)
433 self.reconnection_retries = self.get_option("reconnection_retries")
434
435 if getattr(self._shell, "SHELL_FAMILY", "") == "powershell":
436 self.delegate = None
437 self.has_native_async = True
438 self.always_pipeline_modules = True
439 self.module_implementation_preferences = (".ps1", ".exe", "")
440 self.protocol = None
441 self.shell_id = None
442 self._shell_type = "powershell"
443 self.is_windows = True
444
445 @property
446 def s3_client(self) -> None:
447 if self._s3_manager is not None:
448 return self._s3_manager.client
449 return None
450
451 @property
452 def s3_manager(self) -> None:
453 if self._s3_manager is None:
454 config = {"signature_version": "s3v4", "s3": {"addressing_style": self.get_option("s3_addressing_style")}}
455
456 bucket_endpoint_url = self.get_option("bucket_endpoint_url")
457 s3_endpoint_url, s3_region_name = S3ClientManager.get_bucket_endpoint(
458 bucket_name=self.get_option("bucket_name"),
459 bucket_endpoint_url=bucket_endpoint_url,
460 access_key_id=self.get_option("access_key_id"),
461 secret_key_id=self.get_option("secret_access_key"),
462 session_token=self.get_option("session_token"),
463 region_name=self.get_option("region"),
464 profile_name=self.get_option("profile"),
465 )
466
467 s3_client = self._get_boto_client(
468 "s3", endpoint_url=s3_endpoint_url, region_name=s3_region_name, config=config
469 )
470
471 self._s3_manager = S3ClientManager(s3_client)
472
473 return self._s3_manager
474
475 @property
476 def session_manager(self):
477 return self._session_manager
478
479 @session_manager.setter
480 def session_manager(self, value):
481 self._session_manager = value
482
483 @property
484 def ssm_client(self):
485 if self._client is None:
486 config = {"signature_version": "s3v4", "s3": {"addressing_style": self.get_option("s3_addressing_style")}}
487
488 self._client = self._get_boto_client("ssm", region_name=self.get_option("region"), config=config)
489 return self._client
490
491 @property
492 def instance_id(self) -> str:
493 if not self._instance_id:
494 self._instance_id = self.host if self.get_option("instance_id") is None else self.get_option("instance_id")
495 return self._instance_id
496
497 @instance_id.setter
498 def instance_id(self, instance_id: str) -> None:
499 self._instance_id = instance_id
500
501 def __del__(self) -> None:
502 try:
503 self.close()
504 except ReferenceError:
505 pass
506
507 def _connect(self) -> Any:
508 """connect to the host via ssm"""
509 self._play_context.remote_user = getpass.getuser()
510 if not self.session_manager:
511 self.verbosity_display(4, "NO EXISTING SESSION, STARTING NEW ONE")
512 self.start_session()
513 else:
514 self.verbosity_display(4, f"REUSING EXISTING SESSION: {self.session_manager._session_id}")
515
516 self._connected = True
517 return self
518
519 def _init_clients(self) -> None:
520 """
521 Initializes required AWS clients (SSM and S3).
522 Delegates client initialization to specialized methods.
523 """
524
525 self.verbosity_display(4, "INITIALIZE BOTO3 CLIENTS")
526
527 # Initialize S3 client
528 self.s3_manager # pylint: disable=pointless-statement
529
530 # Initialize SSM client
531 self.ssm_client # pylint: disable=pointless-statement
532
533 # Initialize FileTransferManager
534 self.file_transfer_manager = FileTransferManager(
535 bucket_name=self.get_option("bucket_name"),
536 instance_id=self.instance_id,
537 s3_client=self.s3_client,
538 reconnection_retries=self.reconnection_retries,
539 verbosity_display=self.verbosity_display,
540 close=self.close,
541 exec_command=self.exec_command,
542 )
543
544 def verbosity_display(self, level: int, message: str) -> None:
545 """
546 Displays the given message depending on the verbosity level.
547
548 :param message: The message to display.
549 :param display_level: The verbosity level (1-4).
550
551 :return: None
552 """
553 if self.host:
554 host_args = {"host": self.host}
555 else:
556 host_args = {}
557
558 verbosity_level = {1: display.v, 2: display.vv, 3: display.vvv, 4: display.vvvv}
559
560 if level not in verbosity_level.keys():
561 raise AnsibleError(f"Invalid verbosity level: {level}")
562 verbosity_level[level](to_text(message), **host_args)
563
564 def reset(self) -> None:
565 """start a fresh ssm session"""
566 self.verbosity_display(4, "reset called on ssm connection")
567 self.close()
568 self.start_session()
569
570 def get_executable(self) -> str:
571 ssm_plugin_executable = self.get_option("plugin")
572 if ssm_plugin_executable:
573 # User has provided a path to the ssm plugin, ensure this is a valid path
574 if not os.path.exists(to_bytes(ssm_plugin_executable, errors="surrogate_or_strict")):
575 raise AnsibleError(f"failed to find the executable specified {ssm_plugin_executable}.")
576 else:
577 ssm_plugin_executable = "/usr/local/bin/session-manager-plugin"
578 if not os.path.exists(to_bytes(ssm_plugin_executable, errors="surrogate_or_strict")):
579 # find executable from path 'session-manager-plugin'
580 try:
581 ssm_plugin_executable = get_bin_path("session-manager-plugin")
582 except ValueError as e:
583 raise AnsibleError(str(e))
584 return ssm_plugin_executable
585
586 def start_session(self) -> None:
587 """start ssm session"""
588
589 self.verbosity_display(3, f"ESTABLISH SSM CONNECTION TO: {self.instance_id}")
590
591 executable = self.get_executable()
592
593 self._init_clients()
594
595 if self.session_manager is None:
596 self.session_manager = SSMSessionManager(
597 self.ssm_client,
598 self.instance_id,
599 verbosity_display=self.verbosity_display,
600 ssm_timeout=self.get_option("ssm_timeout"),
601 )
602
603 self.session_manager.start_session(
604 executable=executable,
605 document_name=self.get_option("ssm_document"),
606 region_name=self.get_option("region"),
607 profile_name=self.get_option("profile") or "",
608 )
609
610 self.verbosity_display(4, f"STARTED SSM SESSION: {self.session_manager._session_id}")
611
612 # For non-windows Hosts: Ensure the session has started, and disable command echo and prompt.
613 self.terminal_manager.prepare_terminal()
614
615 def exec_communicate(self, cmd: str, mark_start: str, mark_begin: str, mark_end: str) -> Tuple[int, str, str]:
616 """Interact with session.
617 Read stdout between the markers until 'mark_end' is reached.
618
619 :param cmd: The command being executed.
620 :param mark_start: The marker which starts the output.
621 :param mark_begin: The begin marker.
622 :param mark_end: The end marker.
623 :returns: A tuple with the return code, the stdout and the stderr content.
624 """
625 # Read stdout between the markers
626 stdout = ""
627 win_line = ""
628 begin = False
629 returncode = None
630 for poll_result in self.session_manager.poll("EXEC", cmd):
631 if not poll_result:
632 continue
633
634 line = filter_ansi(self.session_manager.stdout_readline(), self.is_windows)
635 self.verbosity_display(4, f"EXEC stdout line: \n{line}")
636
637 if not begin and self.is_windows:
638 win_line = win_line + line
639 line = win_line
640
641 if mark_start in line:
642 begin = True
643 if not line.startswith(mark_start):
644 stdout = ""
645 continue
646 if begin:
647 if mark_end in line:
648 self.verbosity_display(4, f"POST_PROCESS: \n{to_text(stdout)}")
649 returncode, stdout = self._post_process(stdout, mark_begin)
650 self.verbosity_display(4, f"POST_PROCESSED: \n{to_text(stdout)}")
651 break
652 stdout = stdout + line
653
654 # see https://github.com/pylint-dev/pylint/issues/8909)
655 return (returncode, stdout, self.session_manager.flush_stderr())
656
657 @staticmethod
658 def generate_mark() -> str:
659 """Generates a random string of characters to delimit SSM CLI commands"""
660 mark = "".join([random.choice(string.ascii_letters) for i in range(Connection.MARK_LENGTH)])
661 return mark
662
663 @ssm_retry
664 def exec_command(self, cmd: str, in_data: bool = None, sudoable: bool = True) -> Tuple[int, str, str]:
665 """When running a command on the SSM host, uses generate_mark to get delimiting strings"""
666
667 super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
668
669 self.verbosity_display(3, f"EXEC: {to_text(cmd)}")
670
671 mark_begin = self.generate_mark()
672 if self.is_windows:
673 mark_start = mark_begin + " $LASTEXITCODE"
674 else:
675 mark_start = mark_begin
676 mark_end = self.generate_mark()
677
678 # Wrap command in markers accordingly for the shell used
679 cmd = self.terminal_manager.wrap_command(cmd, mark_start, mark_end)
680
681 self.session_manager.flush_stderr()
682
683 for chunk in chunks(cmd, 1024):
684 self.session_manager.stdin_write(to_bytes(chunk, errors="surrogate_or_strict"))
685
686 return self.exec_communicate(cmd, mark_start, mark_begin, mark_end)
687
688 def _post_process(self, stdout: str, mark_begin: str) -> Tuple[str, str]:
689 """extract command status and strip unwanted lines"""
690
691 if not self.is_windows:
692 # Get command return code
693 returncode = int(stdout.splitlines()[-2])
694
695 # Throw away final lines
696 for _x in range(0, 3):
697 stdout = stdout[:stdout.rfind('\n')] # fmt: skip
698
699 return (returncode, stdout)
700
701 # Windows is a little more complex
702 # Value of $LASTEXITCODE will be the line after the mark
703 trailer = stdout[stdout.rfind(mark_begin):] # fmt: skip
704 last_exit_code = trailer.splitlines()[1]
705 if last_exit_code.isdigit:
706 returncode = int(last_exit_code)
707 else:
708 returncode = -1
709 # output to keep will be before the mark
710 stdout = stdout[:stdout.rfind(mark_begin)] # fmt: skip
711
712 # If the return code contains #CLIXML (like a progress bar) remove it
713 clixml_filter = re.compile(r"#<\sCLIXML\s<Objs.*</Objs>")
714 stdout = clixml_filter.sub("", stdout)
715
716 # If it looks like JSON remove any newlines
717 if stdout.startswith("{"):
718 stdout = stdout.replace("\n", "")
719
720 return (returncode, stdout)
721
722 def generate_commands(self, in_path: str, out_path: str, ssm_action: str) -> Tuple[str, str, Dict]:
723 """
724 Generate S3 path and associated transport commands for file transfer.
725 :param in_path: The local file path to transfer from.
726 :param out_path: The remote file path to transfer to (used to build the S3 key).
727 :param ssm_action: The SSM action to perform ("get" or "put").
728 :return: A tuple containing:
729 - s3_path (str): The S3 key used for the transfer.
730 - commands (List[Dict]): A list of commands to be executed for the transfer.
731 - put_args (Dict): Additional arguments needed for a 'put' operation.
732 """
733 s3_path = escape_path(f"{self.instance_id}/{out_path}")
734 command = ""
735 put_args = []
736 command, put_args = self.s3_manager.generate_host_commands(
737 self.get_option("bucket_name"),
738 self.get_option("bucket_sse_mode"),
739 self.get_option("bucket_sse_kms_key_id"),
740 s3_path,
741 in_path,
742 out_path,
743 self.is_windows,
744 ssm_action,
745 )
746 return s3_path, command, put_args
747
748 def _exec_transport_commands(self, in_path: str, out_path: str, command: dict) -> CommandResult:
749 """
750 Execute the provided transport command.
751
752 :param in_path: The input path.
753 :param out_path: The output path.
754 :param command: A command to execute on the host.
755
756 :returns: A tuple containing the return code, stdout, and stderr.
757 """
758
759 returncode, stdout, stderr = self.exec_command(command, in_data=None, sudoable=False)
760 # Check the return code
761 if returncode != 0:
762 raise AnsibleError(f"failed to transfer file to {in_path} {out_path}:\n{stdout}\n{stderr}")
763
764 return returncode, stdout, stderr
765
766 def put_file(self, in_path: str, out_path: str) -> CommandResult:
767 """transfer a file from local to remote"""
768
769 super().put_file(in_path, out_path)
770
771 self.verbosity_display(3, f"PUT {in_path} TO {out_path}")
772 if not os.path.exists(to_bytes(in_path, errors="surrogate_or_strict")):
773 raise AnsibleFileNotFound(f"file or module does not exist: {in_path}")
774
775 s3_path, command, put_args = self.generate_commands(in_path, out_path, "put")
776 return self.file_transfer_manager._file_transport_command(in_path, out_path, "put", command, put_args, s3_path)
777
778 def fetch_file(self, in_path: str, out_path: str) -> CommandResult:
779 """fetch a file from remote to local"""
780
781 super().fetch_file(in_path, out_path)
782
783 self.verbosity_display(3, f"FETCH {in_path} TO {out_path}")
784
785 s3_path, command, put_args = self.generate_commands(in_path, out_path, "get")
786 return self.file_transfer_manager._file_transport_command(in_path, out_path, "get", command, put_args, s3_path)
787
788 def close(self) -> None:
789 """terminate the connection"""
790 if self.session_manager is not None:
791 self.verbosity_display(3, f"TERMINATE SSM SESSION: {self.session_manager._session_id}")
792
793 self.session_manager.terminate()
794 self.session_manager = None
795
796 self._connected = False