How do I create and manage AWS Systems Manager Automation Documents using local files and CLI?
I want to create AWS Systems Manager Automation Documents as local files and use AWS CLI to create, update, execute automation runbooks, and monitor their execution.
AWS Systems Manager provides a Visual Design Experience in the web console for creating Automation Documents with a drag-and-drop interface. You can also create documents as local JSON or YAML files and manage them using AWS CLI. This approach allows you to version control your automation documents, update document versions, preview executions, and monitor automation runs programmatically.
Note: The commands in this article are designed for Unix-like environments (Linux, macOS, Windows WSL/Git Bash). Command-line examples are provided for Linux and macOS. For other environments, you can manually edit the files with a text editor.
Prerequisites
Before you start, ensure your AWS Identity and Access Management (IAM) user or role has the required permissions. For more information, see Setting up Automation.
For this example, we'll use the AWS-managed AWS-HelloWorld runbook. You can find it in the Systems Manager console's Documents page under Owned by Amazon Automation documents.
-
Extract the document content and create a local file:
aws ssm get-document --name AWS-HelloWorld --document-format JSON \ --query 'Content' --output text > MyRunbook.json -
Verify the local file was created:
cat MyRunbook.jsonYou should see content similar to the following:
{ "description" : "### Document name: AWS-HelloWorld...", "schemaVersion" : "0.3", "assumeRole" : "{{ AutomationAssumeRole }}", "parameters" : { "AutomationAssumeRole" : { "type" : "String", "description" : "(Optional) The Amazon Resource Name (ARN)...", "default" : "" } }, "mainSteps" : [ { "name" : "HelloWorldScriptExecution", "action" : "aws:executeScript", "timeoutSeconds" : 100, "description" : "## HelloWorldScriptExecution...", "inputs" : { "Runtime" : "python3.8", "Handler" : "script_handler", "Script" : "def script_handler(events, context):\n print (\"Hello World. Welcome to Change Manager\")\n" } } ] }
1. Create Document
-
Create the Automation Document using your local file:
aws ssm create-document \ --content file://MyRunbook.json \ --name "MyRunbook" \ --document-type "Automation" \ --document-format JSONExample output:
{ "DocumentDescription": { "Hash": "sha256hash...", "HashType": "Sha256", "Name": "MyRunbook", "Owner": "111122223333", "CreatedDate": "2024-01-15T10:00:00.000Z", "Status": "Creating", "DocumentVersion": "1", "DocumentType": "Automation", "DocumentFormat": "JSON" } } -
Verify the document was created successfully:
aws ssm describe-document --name MyRunbook -
You can also verify the document in the Systems Manager console's Documents page under Owned by me Automation documents.
2. Update Document and Default Version
Now we'll modify the runbook to add a new Name parameter with allowedPattern validation and update the script to use this parameter. First, we'll intentionally create a JSON syntax error to demonstrate the validation process.
-
We'll add a new Name parameter to the MyRunbook.json file after the AutomationAssumeRole parameter, but intentionally omit commas to create a JSON syntax error:
{ "parameters" : { "AutomationAssumeRole" : { "type" : "String", "description" : "(Optional) The Amazon Resource Name (ARN) of the role that allows AWS Systems Manager Automation to perform the actions on your behalf.", "default" : "" } + "Name" : { + "type" : "String", + "description" : "Name to include in the greeting message.", + "default" : "World" + "allowedPattern": "^[a-zA-Z0-9_/.-]+$" + } } }-
Add the Name parameter while intentionally omitting the comma to create a syntax error:
Note: The following commands add the Name parameter but create a syntax error by adding a closing brace without the required comma after the AutomationAssumeRole parameter.
# Linux/WSL sed -i '/"default" : ""/a\ }\n "Name" : {\n "type" : "String",\n "description" : "Name to include in the greeting message.",\n "default" : "World",\n "allowedPattern" : "^[a-zA-Z0-9_/.-]+$"' MyRunbook.json # macOS sed -i '' '/"default" : ""/a\ }\ "Name" : {\ "type" : "String",\ "description" : "Name to include in the greeting message.",\ "default" : "World",\ "allowedPattern" : "^[a-zA-Z0-9_/.-]+$"\ ' MyRunbook.json -
Attempt to update the document with the syntax error:
aws ssm update-document --content file://MyRunbook.json --name MyRunbook --document-format JSON --document-version '$LATEST'Expected error:
An error occurred (InvalidDocumentContent) when calling the UpdateDocument operation: JSON not well-formed. at Line: 11, Column: 5Note: The exact line and column numbers may vary depending on your JSON structure and formatting.
-
-
Now fix the syntax error. The corrected structure should look like this:
{ "parameters" : { "AutomationAssumeRole" : { "type" : "String", "description" : "(Optional) The Amazon Resource Name (ARN) of the role that allows AWS Systems Manager Automation to perform the actions on your behalf.", "default" : "" - } + }, "Name" : { "type" : "String", "description" : "Name to include in the greeting message.", "default" : "World", "allowedPattern" : "^[a-zA-Z0-9_/.-]+$" } }, "mainSteps" : [ { "inputs" : { "Runtime" : "python3.8", "Handler" : "script_handler", - "Script" : "def script_handler(events, context):\n print (\"Hello World. Welcome to Change Manager\")\n" + "Script" : "def script_handler(events, context):\n print (f\"Hello {events.get('Name', 'World')}\")\n" } } ] }-
Fix the JSON syntax by adding the missing comma and updating the script:
# Linux/WSL sed -i '/\"default\" : \"\"/{N;s/\( \)}$/\1},/;}' MyRunbook.json # macOS sed -i '' '/\"default\" : \"\"/{N;s/\( \)}$/\1},/;}' MyRunbook.json# Linux/WSL sed -i 's/print (\\\"Hello World\. Welcome to Change Manager\\\")/print (f\\\"Hello {events.get('\''Name'\'', '\''World'\'')}\\\")/' MyRunbook.json # macOS sed -i '' 's/print (\\\"Hello World\. Welcome to Change Manager\\\")/print (f\\\"Hello {events.get('\''Name'\'', '\''World'\'')}\\\")/' MyRunbook.jsonAlternatively, you can manually edit the file with a text editor or recreate it with the correct structure:
cat > MyRunbook.json << 'EOF' { "description" : "### Document name: AWS-HelloWorld\n## What does this document do?\nThis document is a sample HelloWorld runbook to use with the AWS-HelloWorldChangeTemplate document when trying out Change Manager. The document prints a simple message when it runs.\n\n## Input Parameters\n* AutomationAssumeRole: (Optional) The Amazon Resource Name (ARN) of the role that allows AWS Systems Manager Automation to perform the actions on your behalf.\n* Name: Name to include in the greeting message.\n\n## Output Parameters\nThis document has no outputs\n", "schemaVersion" : "0.3", "assumeRole" : "{{ AutomationAssumeRole }}", "parameters" : { "AutomationAssumeRole" : { "type" : "String", "description" : "(Optional) The Amazon Resource Name (ARN) of the role that allows AWS Systems Manager Automation to perform the actions on your behalf.", "default" : "" }, "Name" : { "type" : "String", "description" : "Name to include in the greeting message.", "default" : "World", "allowedPattern" : "^[a-zA-Z0-9_/.-]+$" } }, "mainSteps" : [ { "name" : "HelloWorldScriptExecution", "action" : "aws:executeScript", "timeoutSeconds" : 100, "description" : "## HelloWorldScriptExecution\nPrints a personalized hello message.\n", "inputs" : { "Runtime" : "python3.8", "Handler" : "script_handler", "Script" : "def script_handler(events, context):\n print (f\"Hello {events.get('Name', 'World')}\")\n", "InputPayload" : { "Name" : "{{ Name }}" } } } ] } EOFNote: Choose the sed command, manual text editor, or file recreation method based on your preference and environment.
-
-
Update the document:
aws ssm update-document --content file://MyRunbook.json --name MyRunbook --document-format JSON --document-version '$LATEST'Example output:
{ "DocumentDescription": { "Hash": "sha256hash...", "HashType": "Sha256", "Name": "MyRunbook", "Owner": "111122223333", "CreatedDate": "2024-01-15T10:00:00.000Z", "Status": "Updating", "DocumentVersion": "2", "LatestVersion": "2", "DefaultVersion": "1", "DocumentType": "Automation", "DocumentFormat": "JSON" } } -
Important: Set the latest version as the default version. Otherwise, the previous version will be used as the default.
First, get the document's latest version:
# Get the latest version number LATEST_VERSION=$(aws ssm describe-document --name MyRunbook --query 'Document.LatestVersion' --output text) echo "Latest version: $LATEST_VERSION"-
Set the latest version as the default version:
aws ssm update-document-default-version --name MyRunbook --document-version $LATEST_VERSIONExample output:
{ "Description": { "Name": "MyRunbook", "DefaultVersion": "2" } }
-
3. Preview and Execution
Now we'll execute the runbook. First, let's preview the execution before actually running it.
-
Preview the execution:
aws ssm start-execution-preview --document-name MyRunbookExample output:
{ "ExecutionPreviewId": "12345678-1234-1234-1234-123456789012" } -
Get the preview results using the returned ExecutionPreviewId:
aws ssm get-execution-preview --execution-preview-id 12345678-1234-1234-1234-123456789012Example output:
{ "ExecutionPreviewId": "12345678-1234-1234-1234-123456789012", "EndedAt": "2024-01-15T10:35:00.000Z", "Status": "Success", "ExecutionPreview": { "Automation": { "StepPreviews": { "Undetermined": 1 }, "Regions": [ "us-east-1" ], "TotalAccounts": 1 } } }The execution preview analyzes your automation without actually running it. The ExecutionPreview object contains an AutomationExecutionPreview structure that provides insights into what the automation will do.
Key components of AutomationExecutionPreview:
- StepPreviews: Shows the number of steps categorized by their impact type:
- Mutating: Steps that make changes to targets (create, modify, or delete resources)
- NonMutating: Steps that only retrieve data (Describe*, List*, Get* actions)
- Undetermined: Steps that invoke external services (Lambda, Step Functions, Run Command) or third-party APIs where the outcome cannot be predicted
- Regions: List of AWS regions where the automation will execute
- TotalAccounts: Number of AWS accounts that will be affected by the automation
Note: In this example, the
aws:executeScriptaction shows as "Undetermined" because the script's behavior cannot be predicted without execution.For complete details, see the AutomationExecutionPreview API Reference and GetExecutionPreview API Reference.
- StepPreviews: Shows the number of steps categorized by their impact type:
-
Execute the automation:
aws ssm start-automation-execution --document-name MyRunbookExample output:
{ "AutomationExecutionId": "12345678-1234-1234-1234-123456789012" } -
Check the execution status using the returned AutomationExecutionId:
aws ssm describe-automation-executions --filters Key=ExecutionId,Values=12345678-1234-1234-1234-123456789012Example output:
{ "AutomationExecutionMetadataList": [ { "AutomationExecutionId": "12345678-1234-1234-1234-123456789012", "DocumentName": "MyRunbook", "DocumentVersion": "2", "AutomationExecutionStatus": "Success", "ExecutionStartTime": "2024-01-15T10:30:00.000Z", "ExecutionEndTime": "2024-01-15T10:31:00.000Z", "ExecutedBy": "arn:aws:sts::111122223333:assumed-role/AutomationRole/user", "Outputs": {} } ] } -
Get detailed information about each step (StepStatus, Inputs, Outputs):
aws ssm describe-automation-step-executions --automation-execution-id 12345678-1234-1234-1234-123456789012Example output:
{ "StepExecutions": [ { "StepName": "HelloWorldScriptExecution", "Action": "aws:executeScript", "TimeoutSeconds": 100, "ExecutionStartTime": "2024-01-15T10:30:15.000Z", "ExecutionEndTime": "2024-01-15T10:30:45.000Z", "StepStatus": "Success", "Inputs": { "Handler": "\"script_handler\"", "Runtime": "\"python3.8\"", "Script": "\"def script_handler(events, context):\\n print (f\\\"Hello {events.get('Name', 'World')}\\\")\\n\"" }, "Outputs": { "OutputPayload": [ "{\"ExecutionLog\":\"Hello World\\n\"}" ] } } ] }This demonstrates how you can execute automation documents and monitor their results in detail, including step-by-step execution status and outputs.
Test Parameter Validation
Let's test that the allowedPattern validation works correctly.
-
Test with invalid parameters containing special characters:
aws ssm start-automation-execution --document-name MyRunbook --parameters "Name=**invalid**"Expected error:
An error occurred (InvalidAutomationExecutionParametersException) when calling the StartAutomationExecution operation: Parameter "Name" has value "**invalid**" not matching "^[a-zA-Z0-9_/.-]+$".This confirms the allowedPattern validation is working correctly and prevents invalid characters.
-
Test with a valid parameter:
aws ssm start-automation-execution --document-name MyRunbook --parameters "Name=Alice"This executes successfully and outputs "Hello Alice" because it matches the allowed pattern.
-
Test with the default value (no parameters):
aws ssm start-automation-execution --document-name MyRunbookThis executes successfully and outputs "Hello World" using the default parameter value.
4. Cleanup
After testing is complete, clean up by deleting the created document:
aws ssm delete-document --name MyRunbook rm ./MyRunbook.json
Related information
- Language
- English
Relevant content
AWS OFFICIALUpdated 2 years ago- Accepted Answer
asked a year ago
AWS OFFICIALUpdated 2 years ago