Kanji
・Cloud Engineer / Freelance ・Geboren 1993 ・Aus Ehime / Wohnhaft in Shibuya, Tokio ・5 Jahre AWS-Erfahrung Profildetails
Inhaltsverzeichnis
– Durch Ausführen des in diesem Artikel beschriebenen Python-Skripts können Sie den Inhalt der in der Eigenschaft „Script“ der Ressource „AWS::SSM::Document“ angegebenen Datei in eine CloudFormation-Vorlage einbetten. - Für Python-Skripte können nur die in der Standard-Lambda-Umgebung verfügbaren Module verwendet werden.Wenn Sie Module außerhalb der Standard-Lambda-Module verwenden müssen, kann dieses Python-Skript diese nicht verarbeiten. - Standardmodule wie „os“, „argparse“, „boto3“, „json“, „logging“, „time“ und „datetime“ sind verfügbar. – Wenn Sie andere Module als die Standard-Lambda-Module verwenden müssen, müssen Sie manuell eine ZIP-Datei mit dem Python-Skript und den Paketen in einen S3-Bucket hochladen und dann die CloudFormation-Vorlage bereitstellen.
– Das Python-Skript in diesem Artikel folgt PEP8. - Die Syntaxprüfung erfolgt mit „flake8“, die automatische Formatierung erfolgt mit „black“. – Für Code, der Prüfungen aufgrund von Verarbeitungsanforderungen ignorieren muss, wird „# noqa“ hinzugefügt. - Die maximale Zeilenlänge („max-line-length“) ist auf 200 Zeichen festgelegt.
– Die zur Validierung verwendete Python-Laufzeitversion ist 3.12.1.
ruamel.yaml
– Das folgende Python-Skript bettet den Inhalt der in der Eigenschaft „Script“ von „AWS::SSM::Document“ angegebenen Datei in eine CloudFormation-Vorlage ein.Speichern Sie es unter einem geeigneten Python-Dateinamen (z. B. „package-ssm-document.py“). – Wie der Befehl „aws cloudformation package“ muss er vor der Bereitstellung der CloudFormation-Vorlage ausgeführt werden.Nutzen Sie es als Teil Ihrer Bereitstellungsschritte oder integrieren Sie es in Ihre CI/CD-Pipeline.
import argparse import os from ruamel.yaml import YAML from ruamel.yaml.scalarstring import LiteralScalarString yaml = YAML() yaml.default_flow_style = False yaml.sort_keys = False def replace_script_with_inline_code(input_file, output_file): base_dir = os.path.dirname(input_file) with open(input_file, "r") as file: yaml_content = yaml.load(file) def process_main_steps(main_steps): for step in main_steps: if step.get("action") == "aws:executeScript" and "Script" in step["inputs"]: script_path = step["inputs"]["Script"] full_script_path = os.path.normpath(os.path.join(base_dir, script_path)) if os.path.exists(full_script_path): with open(full_script_path, "r") as script_file: script_content = script_file.read() step["inputs"]["Script"] = apply_literal_block_style(script_content) else: print(f"Warning: Script file not found at {full_script_path}") elif step.get("action") == "aws:loop" and "Steps" in step["inputs"]: process_main_steps(step["inputs"]["Steps"]) if "nextStep" in step: process_main_steps(step.get("nextStep", [])) def apply_literal_block_style(script_content): return LiteralScalarString(script_content) for resource in yaml_content.get("Resources", {}).values(): if resource.get("Type") == "AWS::SSM::Document": content = resource.get("Properties", {}).get("Content", {}) if "mainSteps" in content: process_main_steps(content["mainSteps"]) output_dir = os.path.dirname(output_file) if output_dir and not os.path.exists(output_dir): os.makedirs(output_dir) with open(output_file, "w") as file: yaml.dump(yaml_content, file) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Transform parameter overrides in a YAML file.") parser.add_argument("--input-file", help="Path to the input YAML file.", default="template.original.yml") parser.add_argument("--output-file", help="Path to the output YAML file.", default="template.yml") args = parser.parse_args() replace_script_with_inline_code(args.input_file, args.output_file)
python package-ssm-document.py \ --input-file tests/template1.original.yml \ --output-file .alcache/template.yml
AWSTemplateFormatVersion: 2010-09-09 Description: template.yml Resources: TestRunbook: Type: AWS::SSM::Document Properties: Name: Sample-TestRunbook DocumentType: Automation DocumentFormat: YAML UpdateMethod: NewVersion Content: schemaVersion: '0.3' mainSteps: - name: SampleStep action: aws:executeScript isEnd: true inputs: Runtime: python3.11 Handler: main Script: src/sample1.py
AWSTemplateFormatVersion: 2010-09-09 Description: template.yml Resources: TestRunbook: Type: AWS::SSM::Document Properties: Name: Sample-TestRunbook DocumentType: Automation DocumentFormat: YAML UpdateMethod: NewVersion Content: schemaVersion: '0.3' mainSteps: - name: SampleStep action: aws:executeScript isEnd: true inputs: Runtime: python3.11 Handler: main Script: | def main(event, context): print("[sample1] Hello, World!") if __name__ == "__main__": main(None, None)