© Brian Beach, Steven Armentrout, Rodney Bozo, Emmanuel Tsouris 2019
B. Beach et al.Pro PowerShell for Amazon Web Serviceshttps://doi.org/10.1007/978-1-4842-4850-8_16

16. Systems Manager: Run Command, Automation, and State Manager

Brian Beach1 , Steven Armentrout2, Rodney Bozo3 and Emmanuel Tsouris4
(1)
Raleigh, NC, USA
(2)
Mountlake Terrace, WA, USA
(3)
Sterling, VA, USA
(4)
North Bend, WA, USA
 

AWS Systems Manager includes several powerful features which can help you manage fleets of Amazon EC2 instances. In this chapter, we’ll take a look at AWS Systems Manager Run Command, Automation, and State Manager which are all built upon an common object known as Systems Manager (SSM) documents. Since SSM documents are a common thread between all these features, it makes sense to dive into them first. So we’ll look at what documents are and how to work with them, and then we’ll see how they are used with Run Command, Automation, and State Manager.

Finally, we’ll end the chapter with an exercise that shows you how to start an automation that builds an updated Windows AMI.

Note

The previous chapter covered AWS Systems Manager basics which also included an important prerequisite, the IAM instance profile. By default, AWS Systems Manager isn’t able to do anything with your EC2 Instances, so to enable connectivity between the AWS Systems Manager and the Amazon SSM Agent on your EC2 instances, you’ll need that IAM instance profile discussed in the previous chapter, with the correct IAM role attached.

AWS Systems Manager (SSM) Documents

Before we dive into Run Command, Automation, and State Manager, let’s go over AWS Systems Manager (SSM) documents. SSM documents are a JSON based object used by the various features within AWS Systems Manager and define how actions are performed by Systems Manager.

There are a good number of predefined documents provided by Amazon which can help you manage your fleet of Amazon EC2 instances and perform all sorts of activities. SSM documents also have the ability to use parameters which allow you to pass configuration settings at runtime. Let’s talk about the different document types and then look at how to work with these documents using either the AWS Systems Manager Console or PowerShell.

SSM Document Types

SSM documents come in a few different types which correspond to specific Systems Manager features. Document types can include command documents, policy documents, and automation documents which we’ll be learning about later in this chapter.

A printed list of document types might never be up to date since Systems Manager, like many AWS Services, grows and has new feature added. These features might introduce new document types or use existing ones. As new features are added, you can always take a look at the “AWS Systems Manager User Guide” https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html which gives you information on the various document types.

Command Documents

Command documents define the commands that the SSM Agent should run on a targeted instance. Both Run Command and State Manager use these types of documents. The command document AWS-RunPowerShellScript, for example, allows you to execute PowerShell commands on one or more instances in your fleet.

Policy Documents

Policy documents are used by State Manager to enforce policies on your targeted instances. A policy is basically a configuration that you define, and Systems Manager makes sure that your instances match that configuration. An example use of policy documents would be to configure newly launched instances to match a standard configuration, optimize instances in an Auto Scaling group with a certain configuration, or even join Windows instances to a domain.

Automation Documents

Automation documents are used by Systems Manager Automation, a feature that you can use to automate systems management workflows. One popular use of Systems Manager Automation is to create custom AMIs by defining steps that can launch the latest Windows AMI from Amazon, add your custom software to it, update it, and then create a new AMI from that updated instance.

Working with Documents in the AWS Systems Manager Console

Let’s open up the AWS Systems Manager Console using our web browser and going to https://console.aws.amazon.com/systems-manager . If we look under Shared Resources, we’ll see a link to the Documents page, where we can browse any documents we’ve created as well as those created by Amazon (Figure 16-1). From here we can also create a new document by clicking the Create document button.
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig1_HTML.jpg
Figure 16-1

Documents in the AWS Systems Manager Console

When we click the name of a document in the list, such as AWS-AttachEBSVolume, we’ll be taken to a details page for that document (Figure 16-2). This details page shows us the Description, Parameters, Permissions, Content, Versions, and Tags for the document.
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig2_HTML.jpg
Figure 16-2

Automation Document Parameters in the AWS Systems Manager Console

If we click the Parameters tab, we can see the parameters that the document accepts. Some parameters might be required, while others are optional. These are defined by the document author within the document’s content. In this case, we’re looking at an automation document created by Amazon. Automation documents (to little surprise) are used by Systems Manager Automation. Now let’s take a look at the Content tab (Figure 16-3).
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig3_HTML.jpg
Figure 16-3

Automation Document Content in the AWS Systems Manager Console

We can see that the Content tab shows us a document version (not to be confused with the schema version), along with a blob of JSON.

The JSON content defines parameters and actions for the document and include a schema version. This schema version is important since the document schema might change with newer versions of Systems Manager to support new features. So if you’re looking at two documents and notice the formats are different, look at the document type and the schema version.

Now, scroll down through the JSON, you’ll see a section where the steps of the document are defined (Figure 16-4). For automation documents with a schema version of 0.3, each step is made up of a step name, actions, and inputs. If we go back and look at a command document with a version of 1.2, AWS-ApplyPatchBaseline, for example, we’ll see it not only has different schema version, but the JSON structure is also a bit different.
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig4_HTML.jpg
Figure 16-4

Command Document Content in the AWS Systems Manager Console

Documents can have different schema versions, and each version can be used with a specific document type; we can see a mapping of document types and the schemas that they can use in Table 16-1.
Table 16-1

AWS Systems Manager Document Schema Versions

Document Type

Uses Schema Versions

Command

1.2, 2.0, 2.2

Automation

0.3

Policy

2.0

Each schema version may have a different structure, support different features, and may use different section names in the content. You can read more about these document schemas and their features on the “AWS Systems Manager User Guide” https://docs.aws.amazon.com/systems-manager/latest/userguide/document-schemas-features.html .

Working with Documents Using PowerShell

While the AWS Systems Manager Console provides a rich GUI interface to browse and work with documents, often we’ll want a programmatic way to automate our work with PowerShell scripts.

Listing SSM Documents

We can easily list documents using Get-SSMDocumentList, which returns a list of documents and includes properties such as document name, owner, and the type of document.
$documents = Get-SSMDocumentList -Region us-east-1
To see only the different types of documents available, we can use Group-Object along with the output of Get-SSMDocumentList.
$documents | Group-Object -Property DocumentType | Select-Object Name, Count

Listing SSM Documents with Document Filters

If we want to get a list of documents that match certain filter criteria, we can do so with a document filter. For example, to get all the command documents, create an Amazon.SimpleSystemsManagement.Model.DocumentFilter object. Then set the key to DocumentType, and set the value to Command. When we use –DocumentFilterList to pass the document filter to Get-SSMDocumentList, we’ll only see command documents.
$documentFilter = New-Object Amazon.SimpleSystemsManagement.Model.DocumentFilter
$documentFilter.Key = "DocumentType"
$documentFilter.Value = "Command"
Get-SSMDocumentList -DocumentFilterList $documentFilter -Region us-east-1
We can also combine document filters in an array. This allows us to filter on multiple properties. Say, for instance, we want to list all command documents that begin with “AWSSupport”.
$docTypeFilter = New-Object Amazon.SimpleSystemsManagement.Model.DocumentFilter
$docTypeFilter.Key = "DocumentType"
$docTypeFilter.Value = "Command"
$docNameFilter = New-Object Amazon.SimpleSystemsManagement.Model.DocumentFilter
$docNameFilter.Key = "Name"
$docNameFilter.Value = "AWSSupport"
$docFilters = @($docTypeFilter,$docNameFilter)
$documents = Get-SSMDocumentList -DocumentFilterList $docFilters -Region us-east-1

Getting an SSM Document Object

To take a closer look at a document, we can use Get-SSMDocument and pass it the name of a document, in this case we’ll look at AWS-RunPowerShellScript. One detail we can see is that the content property is the same JSON string containing details that define the document actions similar to what we saw on the Content tab in the console.
$ssmDoc = Get-SSMDocument -Name "AWS-RunPowerShellScript" -Region us-east-1
$ssmDoc.Content
If you’d prefer to see the content formatted as YAML instead of JSON, you can set the -DocumentType parameter to YAML.
Get-SSMDocument -Name "AWS-RunPowerShellScript" -DocumentFormat "YAML" -Region us-east-1

Creating a New SSM Document

When we want to create a new SSM Document, we must first create the document JSON content. A command document with a schema version of 2.2 looks something like this:
{
    "schemaVersion": "2.2",
    "description": "This is an example Run Command document.",
    "parameters": {
        "MyParameter": {
            "type": "String",
            "description": "(Optional) An example parameter.",
            "default": "Hello World!",
            "maxChars": 256
        }
    },
    "mainSteps": [
        {
            "name": "MyNewCommandDocument",
            "action": "aws:runPowerShellScript",
            "precondition": {
                "StringEquals": [
                    "platformType",
                    "Windows"
                ]
            },
            "inputs": {
                "timeoutSeconds": 300,
                "runCommand": [
                    "Write-Host '{{MyParameter}}'",
                    "Write-Host 'This is a new Run Command document'"
                ]
            }
        }
    ]
}
Then using New-SSMDocument, we would create a new document with our JSON content and set the name of the document and the correct document type (in this case, we are creating a Run command document, so we’ll set it to Command).
$docJson = Get-Content .MyNewCommandDocument.json | Out-String
New-SSMDocument -Content $docJson -DocumentType Command -Name "MyNewCommandDocument"

Run Command

Run Command is one of the oldest and original AWS Systems Manager features. It’s both powerful and secure, giving you the ability to run commands on your Amazon EC2 Instances and on-premises computers. A Run command document simply includes the details and instructions needed for the Amazon SSM Agent to perform actions on your behalf. As we’ll learn later, Automation, State Manager, and other Systems Manager features build upon Run Command as a foundation. You’ll find there are many documents predefined and published by Amazon. We also saw how you can create your own documents to meet your specific needs. You might want to use Run Command to enable server roles, install applications, perform routine maintenance, or even troubleshoot issues.

Note

The following sections require your EC2 Windows Instance have an IAM instance profile with the appropriate roles and trust in order for AWS Systems Manager to function. If you skipped the previous chapters on IAM and Systems Manager Basics, it might be a good idea to go back and review those. Without the IAM instance profile, the Amazon SSM Agent on your EC2 instances won’t be able to communicate with the backend services.

Run Command Using the AWS Systems Manager Console

If we go back to the AWS Systems Manager Console, under the Actions sub-heading, we’ll find Run Command (Figure 16-5).
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig5_HTML.jpg
Figure 16-5

Run Command in the AWS Systems Manager Console

On the Run Command page, we can run a new command, view currently running commands, and view command history. To run a new command, we simply click the Run command button and we’ll be taken to the next page which shows us a list of command documents that we can select from (Figure 16-6).
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig6_HTML.jpg
Figure 16-6

Running a command in the AWS Systems Manager Console

As we learned earlier, we can click the Name of a command document, and we will see a details page. Now if we want to run a command document, we must click the radio button to select it. Let us look closer at AWS-FindWindowsUpdates, a document which searches for missing Windows Updates on an instance we choose. Once selected, we can scroll down the page and see document details including its Command parameters (Figure 16-7).
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig7_HTML.jpg
Figure 16-7

Command parameters for running a command

These Command parameters map to the command document’s parameters we discussed earlier in the section on SSM Documents. The AWS Systems Manager Console shows parameters as input fields. For this document, we can see that the document author has added two parameters, one sets the Update Level and the other specifies Microsoft Knowledge Base (KB) articles. Continuing to scroll down, we’ll see the Targets section (Figure 16-8).
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig8_HTML.jpg
Figure 16-8

Targets for running a command

This is where we define which instances (or targets) we want to run the command on. We can use two methods for selecting targets. We can use a tag, and any instances with that tag will be selected, or we can manually choose manually using instance ID, activation ID, Amazon SSM Agent version, IAM role name, platform, or even resource type.

In the other parameters section, we can optionally enter a comment or set the timeout for the command. We’ll also find a rate control section, which gives us options to limit the number of concurrent targets (this is useful if we are to throttle our command and have only a few run the command at a time). Error threshold also gives us the ability to stop running the command if we get a set number of errors (or percentage).

From here, we also get output options which can enable writing command output to an S3 bucket, CloudWatch Logs, and even trigger an SNS notification that we can use to kick off other workflows or connect to other AWS services.

Finally, there’s a Run button at the bottom of the page that runs the command. Once running, we can view the status of the command from the console, and eventually when it’s done running, we can look at the output.

Run Command Using PowerShell

Since this is a PowerShell book, let’s take a deeper look at how we can use Run Command from our PowerShell scripts. There’s one particular command document that we should look at, and that’s AWS-RunPowerShellScript. As the name implies, this document lets you run PowerShell scripts on your target instances. If you want to run shell commands on Linux, there’s a document for that too!

Now we can run this command document using the console just as we learned a little bit ago, but let’s look at how we can run it using PowerShell.

The document has a few parameters which can be seen in the content section of the document properties either by reading the JSON content or by converting it to an object using ConvertFrom-JSON.
$ssmDoc = Get-SSMDocument -Name "AWS-RunPowerShellScript" -Region us-east-1
$ssmDoc.Content | ConvertFrom-Json | Select-Object parameters
The parameters you’ll find in the content property match up with those parameters you’ll find in AWS Systems Manager Console (Figure 16-9).
../images/319650_2_En_16_Chapter/319650_2_En_16_Fig9_HTML.jpg
Figure 16-9

Parameters for AWS-RunPowerShellScript

We can see that the only required parameter is the one named commands. This is a string list (or array) of PowerShell commands. There are also two optional parameters, workingDirectory and executionTimeout. Working directory is simply the path to a working directory on your instance. So if you want your script to start in a specific directory, you will set that here. Execution timeout has a default value of 1 hour, which means if your script is going to run longer than an hour, you’ll need to set this accordingly; otherwise, execution of the command might timeout. The maximum timeout you can set is 48 hours.

Sending an SSM Command

Now, let’s send an SSM command that tells the Amazon SSM Agent to run some PowerShell script using, you guessed it, the AWS-RunPowerShellScript document.

For convenience, let’s define an instance ID in a PowerShell variable. Remember, you must use an instance ID that’s running and has an appropriate IAM instance profile attached. Then we’ll define a variable which represents the document parameters. The only required one is commands, and we’ll use it to pass Get-Date and Get-Service.
$instanceId = "your instance id"
$parameter = @{'commands'=@('Get-Date', 'Get-Service')}
Next, let’s use Send-SSMCommand to run the PowerShell commands on your instance. Pay close attention to the region parameter; it must be the same region as your instance. Also, by returning the result into a variable, you can easily use the CommandId later to get status of the command. In addition, if you pass an array of instance ids, you will run the command on all of them.
$ssmCommand = Send-SSMCommand -DocumentName AWS-RunPowerShellScript -Parameter $parameter -Comment 'Testing Run Command' -InstanceId $instanceId -Region us-east-1
Examine the command output by printing the contents of the $ssmCommand variable. You’ll see the status and status details are both pending. To get the status, we would use Get-SSMCommand with the CommandId property.
Get-SSMCommand -CommandId $ssmCommand.CommandId –Region us-east-1
When the Status is no longer pending, you’re able to view command invocation details with Get-SSMCommandInvocation.
$commandInvocation = Get-SSMCommandInvocation -CommandId $ssmCommand.CommandId -Detail $true -Region us-east-1
The command invocation details have a property named CommandPlugins; if we expand the property, we can see the output returned by our PowerShell commands.
$commandInvocation | Select-Object -ExpandProperty CommandPlugins
Handling Run Command Output

If output is longer than 2500 characters, it’ll be truncated. You’ll know it was truncated because Systems Manager adds ---Output truncated--- as the last entry in the output to let you know. You can get the full output in a couple of ways, either by using an S3 bucket or with CloudWatch Logs. Both of these methods require that your IAM instance profile have the appropriate access roles to allow writing to the S3 bucket or CloudWatch Logs depending on which you choose to use.

Sending Output to an S3 Bucket
To save the output in an S3 bucket, make sure your IAM instance profile has write access to the S3 bucket, and use the –OutputS3BucketName property with Send-SSMCommand. You’ll get the full output of the PowerShell commands stored in your bucket.
Send-SSMCommand -DocumentName AWS-RunPowerShellScript -Parameter $parameter -Comment 'Testing Run Command' -InstanceId $instanceId -OutputS3BucketName "MyTestBucket12345" -OutputS3KeyPrefix "SomeKeyPrefix" –Region us-east-1
Sending Output to CloudWatch Logs
To use CloudWatch Logs, configure the two CloudWatch properties of Send-SSMCommand -CloudWatchOutputConfig_CloudWatchOutputEnabled and -CloudWatchOutputConfig_CloudWatchLogGroupName. If we don’t pass a CloudWatch Log Group Name, Systems Manager uses the default log group name /aws/ssm/<document name>. So in this case, it would be /aws/ssm/AWS-RunPowerShellScript.
Send-SSMCommand -DocumentName AWS-RunPowerShellScript -Parameter $parameter -Comment 'Testing Run Command' -InstanceId $instanceId -CloudWatchOutputConfig_CloudWatchOutputEnabled $true -Region us-east-1

AWS Systems Manager Automation

AWS Systems Manager Automation executes automation workflows that string together actions to perform a more complex task. Automation uses SSM Documents much like Run Command, and those documents can perform a wide variety of activities such as creating a new instance, stopping that instance, updating it with the latest drivers or patches, and then creating an AMI from that newly updated instance.

User Access to Automation

If you are using an IAM user account, group, or role with administrator permissions, then you should be able to use the Automation service without any access issues; otherwise, you’ll need to grant your account, group, or role access to the Automation service. You can grant access using an AWS managed policy named AmazonSSMFullAccess.

Automation Roles

Much like Run Command, Automation needs an instance profile for any instances that you are launching or targeting with an Automation. Creating that instance profile is covered in the previous chapter under prerequisites. Remember, if you’re using CloudWatch, SNS, or other AWS services with Automation, you’ll also need to grant your instance profile access to those services. The “AWS Systems Manager User Guide” also contains information on how to configure those needed roles and even provides a CloudFormation template to get you started. See “Configuring Access for Systems Manager Automation” at https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-setup-user.html .

Listing Automation Documents

As we learned in the section on SSM documents, listing automation documents with PowerShell can be done easily using the Get-SSMDocumentList command and a document filter.
$docFilter = New-Object Amazon.SimpleSystemsManagement.Model.DocumentFilter
$docFilter.Key = "DocumentType"
$docFilter.Value = "Automation"
$documents = Get-SSMDocumentList -DocumentFilterList $ docFilter -Region us-east-1
$documents | Select-Object Name

To see the details for each document, look at “Systems Manager Automation Documents Reference” located within the “Systems Manager User Guide” https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-documents-reference-details.html .

Starting an Automation Execution

To start an Automation workflow, we can use Start-SSMAutomationExecution and pass it a document name and parameters. The specific parameters will vary depending on the document.
$params = @{'InstanceId' = "i-12345", 'InstanceType' = "t3.xlarge"}
$execId = Start-SSMAutomationExecution -DocumentName "AWS-ResizeInstance" -Parameter $params –Region us-east-1
This example uses the SSM automation document AWS-ResizeInstance which executes the following steps:
  • Creates a CloudFormation Stack

  • Changes the Instances State to stopped

  • Invokes a Lambda function that changes the Instance Size

  • Changes the Instance State to Running

  • Deletes the CloudFormation Stack

See the “Systems Manager User Guide” for details on each automation document; for example, the details on AWS-ResizeInstance can be found at https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-aws-resizeinstance.html .

Getting Automation Execution Status

We can view execution status of our automation using Get-SSMAutomationExecution and pass it the automation execution ID we got from Start-SSMAutomationExecution.
Get-SSMAutomationExecution -AutomationExecutionId $execId

AWS Systems Manager State Manager

Managing a fleet of instances, whether they are in the cloud or on-premises can be challenging. State Manager can help you define policies and enforce those policies to ensure your systems remain in the state you desire. Remember those documents we were talking about? Well State Manager allows you to associate those documents with your instances. You can add a schedule to do things like keep software up to date or perform some routine maintenance task.

Creating an Association

Let’s look at how we can use New-SSMAssociation to create an association with State Manager. We’ll define a tag which will be used for the association (so any instances with that tag will run the document), pass the document name, and create a schedule. This association will run the AWS-UpdateSSMAgent document every 24 hours and target any instances that have a tag named UpdateSSM with a value set to true.
$targetTags = @{Key = "tag:UpdateSSM"; Values = @("true")}
New-SSMAssociation -AssociationName TestAssociation1 -Name AWS-UpdateSSMAgent -Target $targetTags -ScheduleExpression "rate(24 hours)"
State Manager supports a number of cron and rate expressions. Table 16-2 outlines the field positions and possible values you can use to construct a cron expression. Cron expressions, as shown in Table 16-3, are composed of six required fields separated by spaces and can also feature a seventh optional field which represents seconds (and comes first before the other six). For a few examples of cron expressions, see Table 16-4. Rate expressions are a little different where you specify the rate and unit; to see some examples of rate expressions, take a look at Table 16-5.
Table 16-2

Cron Expression Values for Systems Manager

Field

Wildcards

Possible Values

Minutes

, - * /

0–59

Hours

, - * /

0–23

Day of the Month

, - * ? / L W

1–31

Month

, - * /

1–12 or JAN–DEC

Day of the Week

, - * ? / L

1–7 or SUN–SAT

Year

, - * /

1970–2199

Table 16-3

Cron Field Positions for Systems Manager

Minutes

Hours

Day of the Month

Month

Day of the Week

Year

*

*

*

*

*

*

Table 16-4

Cron Examples for Systems Manager

Expression

Meaning

cron(0/15 * * * ? *)

Every 15 minutes

cron(0/30 * * * ? *)

Every 30 minutes

cron(0 0/1 * * ? *)

Every hour

cron(30 5 ? * * *)

Every day at 5:30 a.m.

Table 16-5

Rate Examples for Systems Manager

Expression

Meaning

rate(30 minutes)

Every 30 minutes

rate(1 hour)

Every hour

rate(14 days)

Every 14 days

To learn more about “Cron and Rate Expressions for Systems Manager,” check out the user guide at https://docs.aws.amazon.com/systems-manager/latest/userguide/reference-cron-and-rate-expressions.html .

Exercise 16.1: Build a Windows AMI Using Automation

Amazon provides a great number of Windows AMIs that are maintained monthly and kept up to date. There are cases where you may want to build your own customized AMI and keep it up to date with the latest patches and AWS software. In this exercise, we are going to use AWS Systems Manager Automation to take an AMI as input and build us a new AMI.

Create an IAM Instance Profile

We’ll create an IAM instance profile. If you already have one created, feel free to skip this and substitute your instance profile throughout the exercise.

First, we’ll begin by defining our assume role policy, which allows the AWS Systems Manager service (ssm.amazonaws.com) to assume the role we’re going to create.
$assumeRolePolicy = @"
{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Principal": {
            "Service": [
                "ec2.amazonaws.com",
                "ssm.amazonaws.com"
            ]
        },
        "Action": "sts:AssumeRole"
    }
}
"@
Next, we’ll create a new role and apply the assume role policy document we defined in $assumeRolePolicy.
$role = New-IAMRole -RoleName "DemoSSMRole" -AssumeRolePolicyDocument $assumeRolePolicy
Now, let’s add the AmazonEC2RoleforSSM managed policy.
Register-IAMRolePolicy -RoleName $role.RoleName -PolicyArn 'arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'
To allow our managed instances to write to CloudWatch, we’ll also add the CloudWatch Managed Policy.
Register-IAMRolePolicy -RoleName $role.RoleName -PolicyArn 'arn:aws:iam::aws:policy/CloudWatchFullAccess'
Once we’ve registered all the needed policies, let’s create the instance profile. This profile will be attached to an Amazon EC2 instance and will enable the Amazon SSM Agent.
$instanceProfile = New-IAMInstanceProfile -InstanceProfileName "DemoSSMInstanceProfile"
Finally, we’ll add the role to the instance profile.
Add-IAMRoleToInstanceProfile -InstanceProfileName $instanceProfile.InstanceProfileName -RoleName $role.RoleName

Finding the Latest Windows Server 2019 AMI

While you can use your own custom AMI ID, let’s use the latest Windows Server 2019 AMI. Remember Parameter Store? We’ll go back to what we learned in the previous chapter to use Parameter Store which is kept up to date with the latest AMI ID in each region.
$parameterPath = "/aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base"
$latestImageId = (Get-SSMParameter -Name $parameterPath -Region $region).Value

Configure the Automation Document Parameters

Automation documents feature parameters, which allow you to pass values to the document. We’ll be using the automation document AWS-UpdateWindowsAmi which has a number of parameters; there are two in particular that we need to set to ensure the automation doesn’t fail. That’s the source AMI ID, which will be used to launch an instance, and the IAM instance profile we just created. The other parameters either have default values or are optional, so we’ll leave them out to keep things simple.
$parameters = @{
    SourceAmiId=$latestImageId;
    IamInstanceProfileName="DemoSSMInstanceProfile";
}

Kick Off the Automation Document

Let’s kick off the automation and pass the parameters.
$execId = Start-SSMAutomationExecution -DocumentName "AWS-UpdateWindowsAmi" -Parameter $parameters
Finally, let’s get Automation Execution Status to see progress of our automation workflow.
Get-SSMAutomationExecution -AutomationExecutionId $execId

When our automation is complete, we’ll find a new AMI that has been created which contains the latest AWS Drivers and Software, along with the latest Microsoft Updates.

Summary

In this chapter, we learned about SSM documents and how they are used with AWS Systems Manager Run Command, Automation, and State Manager. We went through the steps of taking an AMI and running it through an automation workflow that updated the operating system and AWS software. In the next chapter, we’ll wrap up our look at AWS Systems Managers with some of the remaining features we haven’t covered yet including Patch Manager.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset