[JAWS-UG CLI] Amazon EC2 Systems Manager 入門 (4) MaintenanceWindowsとPatchBaseline

# この記事について

[JAWS-UG CLI専門支部 #81 Amazon EC2 Systems Manager 入門](https://jawsug-cli.doorkeeper.jp/events/57576)で実施するハンズオン用の手順書です。


# 前提条件

## 必要な権限

作業にあたっては、以下の権限を有したIAMユーザもしくはIAMロールを利用してください。

- EC2 Systems Manager(ssm)のフルコントロール権限
- EC2のフルコントロール権限
- CloudFormationの関するフルコントロール権限
- IAMの関するフルコントロール権限
- Configの関するフルコントロール権限
- S3の関するフルコントロール権限
- SNSの関するフルコントロール権限


# 0. 準備

## 0.1. リージョンを指定

ハンズオンでは東京リージョンを利用しますが、必要に応じて他のリージョンに変更してご利用ください。（東京リージョンを他の検証目的で利用している、など）

```bash:コマンド
export AWS_DEFAULT_REGION="ap-northeast-1"
```

## 0.2. 資格情報を確認

```bash:コマンド
aws configure list
```

インスタンスプロファイルを設定したEC2インスタンスでアクセスキーを設定せずに実行した場合、以下のようになります。

```text:結果
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile                <not set>             None    None
access_key     ****************QSAA         iam-role
secret_key     ****************c1xY         iam-role
    region                us-west-2              env    AWS_DEFAULT_REGION
```

## 0.3. バージョン確認

```bash:コマンド
aws --version
```

```text:結果
（可能な限り最新版を利用しましょう）
```

## 0.4. バージョンアップ（必要に応じて）

```bash:コマンド
sudo pip install -U awscli
```


# 1. PatchBaselineの作成

パッチベースラインは、適用させたい更新プログラムの種類および重要度を定義するリソースです。

適用したくない更新プログラムを指定することも可能です。

※このハンズオンでは、デフォルトのパッチベースラインを利用します。

## 1.1. デフォルトPatchBaselineの確認

### デフォルトPatchBaselineのIDを取得

```bash:コマンド
BASELINE_ID=$(aws ssm describe-patch-baselines \
    --query "BaselineIdentities[?DefaultBaseline==\`"true"\`].BaselineId" \
    --output text) \
    && echo ${BASELINE_ID}
```

### デフォルトPatchBaselineの内容を確認

```bash:コマンド
aws ssm get-patch-baseline \
    --baseline-id ${BASELINE_ID}
```

```json:結果
{
    "BaselineId": "arn:aws:ssm:ap-northeast-1:486716784251:patchbaseline/pb-04ba050f612fba3a6",
    "Name": "AWS-DefaultPatchBaseline",
    "PatchGroups": [],
    "RejectedPatches": [],
    "GlobalFilters": {
        "PatchFilters": [
            {
                "Values": [
                    "Windows7",
                    "Windows8",
                    "Windows8.1",
                    "Windows10",
                    "Windows10LTSB",
                    "WindowsServer2008",
                    "WindowsServer2008R2",
                    "WindowsServer2012",
                    "WindowsServer2012R2",
                    "WindowsServer2016"
                ],
                "Key": "PRODUCT"
            }
        ]
    },
    "ApprovalRules": {
        "PatchRules": [
            {
                "PatchFilterGroup": {
                    "PatchFilters": [
                        {
                            "Values": [
                                "CriticalUpdates",
                                "SecurityUpdates"
                            ],
                            "Key": "CLASSIFICATION"
                        },
                        {
                            "Values": [
                                "Critical",
                                "Important"
                            ],
                            "Key": "MSRC_SEVERITY"
                        }
                    ]
                },
                "ApproveAfterDays": 7
            }
        ]
    },
    "ModifiedDate": 1481687616.193,
    "CreatedDate": 1481687616.193,
    "ApprovedPatches": [],
    "Description": "Default Patch Baseline Provided by AWS."
}
```



# 2. MaintenanceWindowの作成

## 2.1. MaintenanceWindowの作成

### パラメータの指定

※月曜のPM8:00（日本時間）にメンテナンスタスクが実行されるスケジュールを設定します。
進捗に応じて、開始時刻を調整してください。

```bash:コマンド
MAINTENANCE_WINDOW_NAME="test-maintenance-window"
MAINTENANCE_WINDOW_SCHEDULE="cron(0 11 ? * MON *)"
MAINTENANCE_WINDOW_DURATION="2"
MAINTENANCE_WINDOW_CUTOFF="1"
```

### 同名のMaintenanceWindowの不存在を確認

```bash:コマンド
aws ssm describe-maintenance-windows \
    --filters Key="Name",Values="${MAINTENANCE_WINDOW_NAME}"
```

```json:結果
{
    "WindowIdentities": []
}
```

### MaintenanceWindowの作成

```bash:コマンド
aws ssm create-maintenance-window \
    --name ${MAINTENANCE_WINDOW_NAME} \
    --schedule "${MAINTENANCE_WINDOW_SCHEDULE}" \
    --duration ${MAINTENANCE_WINDOW_DURATION} \
    --cutoff ${MAINTENANCE_WINDOW_CUTOFF} \
    --no-allow-unassociated-targets
```

```json:結果
{
    "WindowId": "mw-*****************"
}
```

### MaintenanceWindowの確認

```bash:コマンド
aws ssm describe-maintenance-windows \
    --filters Key="Name",Values="${MAINTENANCE_WINDOW_NAME}"
```

```json:結果
{
    "WindowIdentities": [
        {
            "Duration": 2,
            "Cutoff": 1,
            "WindowId": "mw-*****************",
            "Enabled": true,
            "Name": "test-maintenance-window"
        }
    ]
}
```

### MaintenanceWindowIDの取得

```bash:コマンド
MAINTENANCE_WINDOW_ID=$(aws ssm describe-maintenance-windows \
    --filters Key="Name",Values="${MAINTENANCE_WINDOW_NAME}" \
    --query "WindowIdentities[0].WindowId" \
    --output text) \
    && echo ${MAINTENANCE_WINDOW_ID}
```

### MaintenanceWindowの詳細を確認

```bash:コマンド
aws ssm get-maintenance-window \
    --window-id ${MAINTENANCE_WINDOW_ID}
```

```json:結果
{
    "Cutoff": 1,
    "Name": "test-maintenance-window",
    "Schedule": "cron(0 11 ? * MON *)",
    "Enabled": true,
    "AllowUnassociatedTargets": false,
    "WindowId": "mw-*****************",
    "ModifiedDate": 1490534750.991,
    "CreatedDate": 1490534750.991,
    "Duration": 2
}
```

## 2.2. ターゲットの登録

### MaintenanceWindowが適用されているインスタンスを確認

```bash:コマンド
aws ssm describe-maintenance-window-targets \
    --window-id ${MAINTENANCE_WINDOW_ID}
```

```json:コマンド
{
    "Targets": []
}
```

### MaintenanceWindowにインスタンスを登録

```bash:コマンド
aws ssm register-target-with-maintenance-window \
    --window-id ${MAINTENANCE_WINDOW_ID} \
    --resource-type "INSTANCE" \
    --targets "Key=InstanceIds,Values=${INSTANCE_ID}"
```

```json:結果
{
    "WindowTargetId": "********-****-****-****-************"
}
```

### MaintenanceWindowにインスタンスが登録されたことを確認

```bash:コマンド
aws ssm describe-maintenance-window-targets \
    --window-id ${MAINTENANCE_WINDOW_ID}
```

```json:結果
{
    "Targets": [
        {
            "ResourceType": "INSTANCE",
            "WindowId": "mw-*****************",
            "Targets": [
                {
                    "Values": [
                        "i-*****************"
                    ],
                    "Key": "InstanceIds"
                }
            ],
            "WindowTargetId": "********-****-****-****-************"
        }
    ]
}
```

## 2.3. Service Roleの作成

### ロール名の指定

```bash:コマンド
ROLE_NAME_FOR_MAINTENANCE_WINDOW="ServiceRoleForMaintenanceWindow"
```

### 同名ロールの不存在を確認

```bash:コマンド
aws iam get-role \
    --role-name ${ROLE_NAME_FOR_MAINTENANCE_WINDOW}
```

```text:結果
An error occurred (NoSuchEntity) when calling the GetRole operation: Role not found for ServiceRoleForMaintenanceWindow
```

### 信頼関係を定義

```bash:コマンド
TRUST_POLICY_FILE='Trust-Policy-for-MaintenanceWindow.json'
```

```bash:コマンド
cat << EOF > ${TRUST_POLICY_FILE}
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "ssm.amazonaws.com"
                ]
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
EOF

cat ${TRUST_POLICY_FILE}
```

```bash:コマンド
jsonlint -q ${TRUST_POLICY_FILE}
```

### パラメータを確認

```bash:コマンド
cat << ETX

    ROLE_NAME_FOR_MAINTENANCE_WINDOW: ${ROLE_NAME_FOR_MAINTENANCE_WINDOW}
    TRUST_POLICY_FILE: ${TRUST_POLICY_FILE}

ETX
```

```text:結果

    ROLE_NAME_FOR_MAINTENANCE_WINDOW: ServiceRoleForMaintenanceWindow
    TRUST_POLICY_FILE: Trust-Policy-for-MaintenanceWindow.json

```

### ロールを作成

```bash:コマンド
aws iam create-role \
    --role-name ${ROLE_NAME_FOR_MAINTENANCE_WINDOW} \
    --assume-role-policy-document file://${TRUST_POLICY_FILE}
```

```json:結果
{
    "Role": {
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "sts:AssumeRole",
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "ssm.amazonaws.com"
                        ]
                    }
                }
            ]
        },
        "RoleId": "*********************",
        "CreateDate": "2017-03-26T14:40:35.623Z",
        "RoleName": "ServiceRoleForMaintenanceWindow",
        "Path": "/",
        "Arn": "arn:aws:iam::************:role/ServiceRoleForMaintenanceWindow"
    }
}
```

### ロールにアタッチするポリシーを指定

```bash:コマンド
POLICY_ARN_FOR_MAINTENANCE_WINDOW="arn:aws:iam::aws:policy/service-role/AmazonSSMMaintenanceWindowRole"
```

### ロールにポリシーをアタッチ

```bash:コマンド
aws iam attach-role-policy \
    --role-name ${ROLE_NAME_FOR_MAINTENANCE_WINDOW} \
    --policy-arn ${POLICY_ARN_FOR_MAINTENANCE_WINDOW}
```

### ロールにポリシーがアタッチされたことを確認

```bash:コマンド
aws iam list-attached-role-policies \
    --role-name ${ROLE_NAME_FOR_MAINTENANCE_WINDOW}
```

```json:結果
{
    "AttachedPolicies": [
        {
            "PolicyName": "AmazonSSMMaintenanceWindowRole",
            "PolicyArn": "arn:aws:iam::aws:policy/service-role/AmazonSSMMaintenanceWindowRole"
        }
    ]
}
```

### ARNの取得

```bash:コマンド
ROLE_ARN_FOR_MAINTENANCE_WINDOW=$(aws iam get-role \
    --role-name ${ROLE_NAME_FOR_MAINTENANCE_WINDOW} \
    --query "Role.Arn" \
    --output text) \
    && echo ${ROLE_ARN_FOR_MAINTENANCE_WINDOW}
```

```text:結果
arn:aws:iam::************:role/ServiceRoleForMaintenanceWindow
```

## 2.4. タスクの登録

### ドキュメントの指定

```bash:コマンド
DOCUMENT_NAME="AWS-ApplyPatchBaseline"
```

### ドキュメントで指定できるパラメータを確認

```bash:コマンド
aws ssm describe-document \
    --name ${DOCUMENT_NAME} \
    --query "Document.Parameters"
```

```json:コマンド
[
    {
        "Type": "String",
        "Name": "Operation",
        "Description": "(Required) The update or configuration to perform on the instance. The system checks if the baseline patches are installed. The install operation installs all patches in the baseline."
    },
    {
        "DefaultValue": "",
        "Type": "String",
        "Name": "SnapshotId",
        "Description": "(Optional) The snapshot Id to retrieve a patch baseline snapshot with."
    }
]
```

### ドキュメントの実行内容を確認

```bash:コマンド
aws ssm get-document \
    --name ${DOCUMENT_NAME}
```

```json:結果
{
    "Content": "{\n    \"schemaVersion\": \"1.2\",\n    \"description\": \"Scans for or installs patches from a patch baseline.\",\n    \"parameters\": {\n        \"Operation\": {\n            \"type\": \"String\",\n            \"description\": \"(Required) The update or configuration to perform on the instance. The system checks if the baseline patches are installed. The install operation installs all patches in the baseline.\", \n            \"allowedValues\": [\n                \"Scan\",\n                \"Install\"\n            ]\n        },\n        \"SnapshotId\": {\n            \"type\": \"String\",\n            \"description\": \"(Optional) The snapshot Id to retrieve a patch baseline snapshot with.\",\n            \"allowedPattern\": \"(^$)|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\",\n            \"default\" : \"\"\n        }\n    },\n    \"runtimeConfig\": {\n        \"aws:runPowerShellScript\": {\n            \"properties\": [{\n                \"id\": \"0.aws:runPowerShellScript\",\n                \"timeoutSeconds\": 7200,\n                \"runCommand\": [\n                    \"# Check the OS version\",\n                    \"if ([Environment]::OSVersion.Version.Major -le 5) {\",\n                    \"    Write-Error 'This command is not supported on Windows 2003 or lower.'\",\n                    \"    exit -1\",\n                    \"} elseif ([Environment]::OSVersion.Version.Major -ge 10) {\",\n                    \"    $sku = (Get-CimInstance -ClassName Win32_OperatingSystem).OperatingSystemSKU\",\n                    \"    if ($sku -eq 143 -or $sku -eq 144) {\",\n                    \"        Write-Host 'This command is not supported on Windows 2016 Nano Server.'\",\n                    \"        exit -1\",\n                    \"    }\",\n                    \"}\",\n                    \"# Check the SSM agent version\",\n                    \"$ssmAgentService = Get-ItemProperty 'HKLM:SYSTEM\\\\CurrentControlSet\\\\Services\\\\AmazonSSMAgent\\\\'\",\n                    \"if (-not $ssmAgentService -or $ssmAgentService.Version -lt '2.0.533.0') {\",\n                    \"    Write-Host 'This command is not supported with SSM Agent version less than 2.0.533.0.'\",\n                    \"    exit -1\",\n                    \"}\",\n                    \"\",\n                    \"# Application specific constants\",\n                    \"$appName = 'PatchBaselineOperations'\",\n                    \"$psModuleFileName = 'Amazon.PatchBaselineOperations.dll'\",\n                    \"$s3FileName = 'Amazon.PatchBaselineOperations-1.0.zip'\",\n                    \"$s3LocationUsEast = 'https://s3.amazonaws.com/aws-ssm-{0}/' + $appName.ToLower() + '/' + $s3FileName\",\n                    \"$s3LocationRegular = 'https://s3-{0}.amazonaws.com/aws-ssm-{0}/' + $appName.ToLower() + '/' + $s3FileName\",\n                    \"$s3LocationCn = 'https://s3.{0}.amazonaws.com.cn/aws-ssm-{0}/' + $appName.ToLower() + '/' + $s3FileName\",\n                    \"$s3FileHash = '1B3731B11AB9A56A8F9C89FF8008F61A0E10539DC751B1C9D3ED85A0DD3FBB4F'\",\n                    \"$psModuleHashes = @{ \",\n                    \"    'Amazon.PatchBaselineOperations.dll' = '9708C234C3DED1AF9DBCF583A2D4651E79815B4A4FFF5047CDD15151CF1945AD';\",\n                    \"    'AWSSDK.Core.dll' = 'D6E34999DBF9BE1A439E05E1B4E0D730655CE2E33000B658FBEF89AFDC1EEB99';\",\n                    \"    'AWSSDK.SimpleSystemsManagement.dll' = '58043C199D716A627D1031DFFECC88DE4EE7F91D0AE6C9110362FA520FD0E287';\",\n                    \"    'Newtonsoft.Json.dll' = '0516D4109263C126C779E4E8F5879349663FA0A5B23D6D44167403E14066E6F9';\",\n                    \"    'THIRD_PARTY_LICENSES.txt' = '4C9B3A1C7C3E27676DD31AFC89FAC6584CA49FB850C9E62DDCF9E5E78F50640C'\",\n                    \"}\",\n                    \"\",\n                    \"# Folders and Logging\",\n                    \"$tempDirectory = $env:TEMP\",\n                    \"$downloadPath = [IO.Path]::Combine($tempDirectory, $s3FileName)\",\n                    \"$psModuleInstallLocation = [IO.Path]::Combine([Environment]::GetEnvironmentVariable([Environment+SpecialFolder]::ProgramFiles), 'Amazon', $appName)\",\n                    \"$psModuleInstallFile = [IO.Path]::Combine($psModuleInstallLocation, $psModuleFileName)\",\n                    \"$log = @()\",\n                    \"\",\n                    \"function CheckFileHash ($filePath, $fileHash) {\",\n                    \"    if (Test-Path($filePath)) {\",\n                    \"        $fileStream = New-Object System.IO.FileStream($filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)\",\n                    \"        $sha256 = [System.Security.Cryptography.SHA256]::Create()\",\n                    \"        $sourceHash = [System.BitConverter]::ToString($sha256.ComputeHash($fileStream), 0).Replace('-', '').ToLowerInvariant()\",\n                    \"        $sha256.Dispose()\",\n                    \"        $fileStream.Dispose()\",\n                    \"        \",\n                    \"        if ($sourceHash -ne $fileHash) {\",\n                    \"            return $false\",\n                    \"        }\",\n                    \"        else {\",\n                    \"            return $true\",\n                    \"        }\",\n                    \"    }\",\n                    \"    else {\",\n                    \"        return $false\",\n                    \"    }\",\n                    \"}\",\n                    \"\",\n                    \"function CheckPowerShellModuleInstallation {\",\n                    \"    $isInstalled = $false \",\n                    \"    # Path does not exist meaning it has never been downloaded.\",\n                    \"    if (Test-Path($psModuleInstallLocation)) {\",\n                    \"        # Check if the expected number of files and directories are in the folder\",\n                    \"        if (((Get-ChildItem $psModuleInstallLocation -Directory | Measure-Object | %{$_.Count}) -eq 0) -and \",\n                    \"            ((Get-ChildItem $psModuleInstallLocation -File | Measure-Object | %{$_.Count}) -eq $psModuleHashes.Count)) {\",\n                    \"            $validFileHashes = $true\",\n                    \"\",\n                    \"            # Check each file for their expected file hash.\",\n                    \"            Get-ChildItem $psModuleInstallLocation -File | ForEach-Object {\",\n                    \"                if ($psModuleHashes.ContainsKey($_.Name)) {\",\n                    \"                    $installFile = [IO.Path]::Combine($psModuleInstallLocation, $_.Name)\",\n                    \"                    if (-Not (CheckFileHash $installFile $psModuleHashes[$_.Name])) {\",\n                    \"                        $log += ('The SHA hash of the {0} file does not match the expected value.' -f $_.Name)\",\n                    \"                        $validFileHashes = $false\",\n                    \"                    }\",\n                    \"                } else {\",\n                    \"                    $log += ('The PowerShellModule installation folder contains an unexpected file with name {0}.' -f $_.Name)\",\n                    \"                    $validFileHashes = $false\",\n                    \"                }\",\n                    \"            }\",\n                    \"\",\n                    \"            $isInstalled = $validFileHashes\",\n                    \"        } else {\",\n                    \"            $log += ('An incorrect number of files were present in the PowerShellModule installation folder. The contents will be deleted.')\",\n                    \"        }\",\n                    \"\",\n                    \"        if (-Not $isInstalled) {\",\n                    \"            # Remove all files and folders as the folder contains potentially malicious software.\",\n                    \"            Remove-Item $psModuleInstallLocation -Recurse\",\n                    \"        }\",\n                    \"    }\",\n                    \"   \",\n                    \"    return $isInstalled\",\n                    \"}\",\n                    \"\",\n                    \"function InstallPowerShellModule {\",\n                    \"    if (-Not (CheckPowerShellModuleInstallation)) {\",\n                    \"        $log += (\\\"Preparing to download {0} PowerShell module from S3.`r`n\\\" -f $appName)\",\n                    \"\",\n                    \"        #Setup the directories if they do not exist.\",\n                    \"        if (-Not (Test-Path($psModuleInstallLocation))) {\",\n                    \"            $noOp = New-Item $psModuleInstallLocation -ItemType Directory\",\n                    \"        } \",\n                    \"\",\n                    \"        if (-Not (Test-Path($tempDirectory))) {\",\n                    \"            $noOp = New-Item $tempDirectory -ItemType Directory\",\n                    \"        }\",\n                    \"        $region = $env:AWS_SSM_REGION_NAME \",\n                    \"        if ($region -eq 'us-east-1') {\",\n                    \"            $s3Location = $s3LocationUsEast -f $region\",\n                    \"        } elseif ($region -eq 'cn-north-1') {\",\n                    \"            $s3Location = $s3LocationCn -f $region\",\n                    \"        } else {\",\n                    \"            $s3Location = $s3LocationRegular -f $region\",\n                    \"        }\",\n                    \"\",\n                    \"        $log += (\\\"Downloading {0} PowerShell module from {1} to {2}.`r`n\\\" -f $appName, $s3Location, $downloadPath)\",\n                    \"        (New-Object Net.WebClient).DownloadFile($s3Location, $downloadPath)\",\n                    \"\",\n                    \"        if (CheckFileHash $downloadPath $s3FileHash ) {\",\n                    \"            $log += (\\\"Extracting {0} zip file contents to temporary folder.`r`n\\\" -f $appName)\",\n                    \"            (New-Object -Com Shell.Application).namespace($psModuleInstallLocation).CopyHere((New-Object -Com Shell.Application).namespace($downloadPath).Items(), 16)\",\n                    \"        }\",\n                    \"        else {\",\n                    \"            throw ('The SHA hash of the {0} S3 source file does not match the expected value.' -f $appName)\",\n                    \"        }\",\n                    \"\",\n                    \"        $log += (\\\"Verifying SHA 256 of the {0} PowerShell module files.`r`n\\\" -f $appName)\",\n                    \"        if (-Not (CheckPowerShellModuleInstallation)) {\",\n                    \"            throw ('The verification of the {0} PowerShell module did not pass.' -f $appName)\",\n                    \"        }\",\n                    \"\",\n                    \"        $log += (\\\"Successfully downloaded and installed the {0} PowerShell module.`r`n\\\" -f $appName)\",\n                    \"    }\",\n                    \"}\",\n                    \"\",\n                    \"try {\",\n                    \"    InstallPowerShellModule\",\n                    \"} catch [Exception] {\",\n                    \"    $msg = \\\"An error occurred when executing {0}: {1}`r`nDetails:`r`n{2}\\\" -f $appName, $_.Exception.Message, $log\",\n                    \"    Write-Error $msg\",\n                    \"    exit -1\",\n                    \"}\",\n                    \"finally {\",\n                    \"    if (Test-Path $downloadPath) {\",\n                    \"        rm $downloadPath\",\n                    \"    }\",\n                    \"}\",\n                    \"\",\n                    \"# Setup the command\",\n                    \"Import-Module $psModuleInstallFile\",\n                    \"$response = Invoke-PatchBaselineOperation -Operation {{Operation}} -SnapshotId '{{SnapshotId}}' -InstanceId $env:AWS_SSM_INSTANCE_ID -Region $env:AWS_SSM_REGION_NAME\",\n                    \"\",\n                    \"if ($response.ExitCode -ne 3010)\",\n                    \"{\",\n                    \"    $response.ToString()\",\n                    \"}\",\n                    \"\",\n                    \"exit $response.ExitCode\"\n                ]\n            }]\n        }\n    }\n}\n",
    "Name": "AWS-ApplyPatchBaseline"
}
```

### ドキュメントのパラメータを指定

```bash:コマンド
PATCH_BASELINE_PARAMETER_FILE_NAME="patch_baseline_parameter.json"
```

```bash:コマンド
cat << EOF > ${PATCH_BASELINE_PARAMETER_FILE_NAME}
{
    "Operation": {
        "Values": [
            "Install"
        ]
    }
}
EOF

cat ${PATCH_BASELINE_PARAMETER_FILE_NAME}
```

```bash:コマンド
jsonlint -q ${PATCH_BASELINE_PARAMETER_FILE_NAME}
```

### 実行結果の出力先を指定

```bash:コマンド
PATCH_BASELINE_LOGGING_FILE_NAME="patch_baseline_logging.json"
```

```bash:コマンド
cat << EOF > ${PATCH_BASELINE_LOGGING_FILE_NAME}
{
    "S3BucketName": "${BUCKET_NAME}",
    "S3KeyPrefix": "",
    "S3Region": "${AWS_DEFAULT_REGION}"
}
EOF

cat ${PATCH_BASELINE_LOGGING_FILE_NAME}
```

```bash:コマンド
jsonlint -q ${PATCH_BASELINE_LOGGING_FILE_NAME}
```

### その他パラメータの指定

```bash:コマンド
TASK_TYPE="RUN_COMMAND"
PRIORITY="1"
MAX_COCCURRENCY="1"
MAX_ERRORS="1"
```

### タスクを登録

```bash:コマンド
aws ssm register-task-with-maintenance-window \
    --window-id ${MAINTENANCE_WINDOW_ID} \
    --targets "Key=InstanceIds,Values=${INSTANCE_ID}" \
    --task-arn ${DOCUMENT_NAME} \
    --service-role-arn ${ROLE_ARN_FOR_MAINTENANCE_WINDOW} \
    --task-type ${TASK_TYPE} \
    --task-parameters file://${PATCH_BASELINE_PARAMETER_FILE_NAME} \
    --priority ${PRIORITY} \
    --max-concurrency ${MAX_COCCURRENCY} \
    --max-errors ${MAX_ERRORS} \
    --logging-info file://${PATCH_BASELINE_LOGGING_FILE_NAME}
```

```json:結果
{
    "WindowTaskId": "********-****-****-****-************"
}
```

### タスクが登録されたことを確認

```bash:コマンド
aws ssm describe-maintenance-window-tasks \
    --window-id ${MAINTENANCE_WINDOW_ID}
```

```json:結果
{
    "Tasks": [
        {
            "LoggingInfo": {
                "S3KeyPrefix": "",
                "S3BucketName": "ec2-systems-manager-************",
                "S3Region": "ap-northeast-1"
            },
            "ServiceRoleArn": "arn:aws:iam::************:role/ServiceRoleForMaintenanceWindow",
            "MaxErrors": "1",
            "TaskArn": "AWS-ApplyPatchBaseline",
            "MaxConcurrency": "1",
            "WindowTaskId": "********-****-****-****-************",
            "TaskParameters": {
                "Operation": {
                    "Values": [
                        "Scan"
                    ]
                }
            },
            "Priority": 1,
            "WindowId": "mw-*****************",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Values": [
                        "i-*****************"
                    ],
                    "Key": "InstanceIds"
                }
            ]
        }
    ]
}
```


# 3. 動作確認

## 3.1. メンテナンスウィンドウの実行履歴を確認

設定した時刻以降に実行してください。

### メンテナンスウィンドウの実行履歴の一覧を確認

```bash:コマンド
aws ssm describe-maintenance-window-executions \
    --window-id ${MAINTENANCE_WINDOW_ID}
```

```json:結果
{
    "WindowExecutions": [
        {
            "Status": "IN_PROGRESS",
            "WindowId": "mw-0246784fcac329f62",
            "WindowExecutionId": "0be4db9a-41f3-4a65-b611-34fbf433cc99",
            "StartTime": 1490883027.414
        }
    ]
}
```

### メンテナンスウィンドウの実行結果の確認

```bash:コマンド
EXECUTION_ID=$(aws ssm describe-maintenance-window-executions \
    --window-id ${MAINTENANCE_WINDOW_ID} \
    --query "sort_by(WindowExecutions,&StartTime)[-1].WindowExecutionId" \
    --output text) \
    && echo ${EXECUTION_ID}
```

```bash:コマンド
aws ssm describe-maintenance-window-execution-tasks \
    --window-execution-id ${EXECUTION_ID}
```

```json:結果
{
    "WindowExecutionTaskIdentities": [
        {
            "Status": "SUCCESS",
            "TaskArn": "AWS-ApplyPatchBaseline",
            "StartTime": 1490883027.89,
            "TaskType": "RUN_COMMAND",
            "EndTime": 1490883485.858,
            "WindowExecutionId": "0be4db9a-41f3-4a65-b611-34fbf433cc99",
            "TaskExecutionId": "3ec28799-6f42-4a3a-a503-2b708dc9b3c8"
        }
    ]
}
```

### タスクの実行結果の確認

```bash:コマンド
TASK_ID=$(aws ssm describe-maintenance-window-execution-tasks \
    --window-execution-id ${EXECUTION_ID} \
    --query "WindowExecutionTaskIdentities[0].TaskExecutionId" \
    --output text) \
    && echo ${TASK_ID}
```

```bash:コマンド
aws ssm describe-maintenance-window-execution-task-invocations \
    --window-execution-id ${EXECUTION_ID} \
    --task-id ${TASK_ID}
```

```json:結果
{
    "WindowExecutionTaskInvocationIdentities": [
        {
            "Status": "SUCCESS",
            "Parameters": "{\"documentName\":\"AWS-ApplyPatchBaseline\",\"instanceIds\":[\"i-*****************\"],\"parameters\":{\"SnapshotId\":[\"0be4db9a-41f3-4a65-b611-34fbf433cc99\"],\"Operation\":[\"Scan\"]},\"maxConcurrency\":\"1\",\"maxErrors\":\"1\",\"outputS3BucketName\":\"ec2-systems-manager-************\",\"outputS3Region\":\"ap-northeast-1\",\"outputS3KeyPrefix\":\"\"}",
            "ExecutionId": "ec20c45e-631d-4802-8e38-5e1729336137",
            "InvocationId": "9887654e-bfc1-49ae-87e9-2e8d750f3613",
            "StartTime": 1490883027.962,
            "EndTime": 1490883485.704,
            "WindowExecutionId": "0be4db9a-41f3-4a65-b611-34fbf433cc99",
            "StatusDetails": "Success",
            "TaskExecutionId": "3ec28799-6f42-4a3a-a503-2b708dc9b3c8"
        }
    ]
}
```

### 実行ログの確認

```bash:コマンド
EXECUTION_ID=$(aws ssm describe-maintenance-window-execution-task-invocations \
    --window-execution-id ${EXECUTION_ID} \
    --task-id ${TASK_ID} \
    --query "WindowExecutionTaskInvocationIdentities[0].ExecutionId" \
    --output text) \
    && echo ${EXECUTION_ID}
```

```bash:コマンド
OBJECT_KEY=$(aws s3 ls ${BUCKET_NAME} \
    --recursive \
    | grep ${EXECUTION_ID} \
    | grep "stdout" \
    | sed 's/[\t ]\+/\t/g' \
    |  cut -f4) \
    && echo ${OBJECT_KEY}
```

```text:結果
ec20c45e-631d-4802-8e38-5e1729336137/i-*****************/awsrunPowerShellScript/0.awsrunPowerShellScript/stdout
```

```bash:コマンド
aws s3 cp s3://${BUCKET_NAME}/${OBJECT_KEY} stdout && cat stdout
```

```
download: s3://ec2-systems-manager-************/ec20c45e-631d-4802-8e38-5e1729336137/i-*****************/awsrunPowerShellScript/0.awsrunPowerShellScript/stdout to ./stdout

Patch Summary for i-*****************
PatchGroup          :
BaselineId          : pb-04ba050f612fba3a6
SnapshotId          : de205080-287e-4a77-b17f-752a30f5b671
OwnerInformation    :
OperationType       : Install
OperationStartTime  : 2017-04-02T14:20:50.0000000Z
OperationEndTime    : 2017-04-02T14:37:17.5713419Z
InstalledCount      : 70
InstalledOtherCount : 179
FailedCount         : 0
MissingCount        : 0
NotApplicableCount  : 1743

WIN-ND2FOTNT7HF - PatchBaselineOperations Installation Results - 2017-04-02T14:37:19.235

KbArticleId Installed   Message
----------- ----------- -----------
KB2966826   Yes         Success
KB2973114   Yes         Success
KB2972213   Yes         Success
KB2966828   Yes         Success
KB2968296   Yes         Success
KB2972103   Yes         Success
KB2982998   Yes         Success
KB2978122   Yes         Success
KB3037576   Yes         Success
KB3023219   Yes         Success
KB3072307   Yes         Success
KB3074545   Yes         Success
KB3097992   Yes         Success
KB3127222   Yes         Success
KB3122651   Yes         Success
KB3135985   Yes         Success
KB3142026   Yes         Success
KB4012216   Yes         Success
KB3205404   Yes         Success



```

### WindowsUpdateの一覧

```bash:コマンド
aws ssm list-inventory-entries \
    --instance-id ${INSTANCE_ID} \
    --type-name AWS:WindowsUpdate
```

```json:結果
{
    "InstanceId": "i-*****************",
    "TypeName": "AWS:WindowsUpdate",
    "Entries": [
        {
            "HotFixId": "KB2978122",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB2982998",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3135985",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB2973114",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB2968296",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB2972103",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB2972213",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3097992",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3023219",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3127222",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3037576",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3122651",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3074545",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3072307",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3142026",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB4012216",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB2966826",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3210132",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB2966828",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2017-04-02T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3210135",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-12-14T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3195387",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-11-22T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3179948",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-10-11T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3182203",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-10-11T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3179574",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3185911",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3184122",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3177186",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3174644",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3175024",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3178539",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3185319",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3184943",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-09-14T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3175443",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-08-13T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3172729",
            "InstalledBy": "WIN-ND2FOTNT7HF\\Administrator",
            "InstalledTime": "2016-08-13T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3173424",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-08-13T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3172614",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-08-13T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3169704",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-08-13T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3170455",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-08-13T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3161949",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3162343",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3160005",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3159398",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3161958",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3164035",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3162835",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3164294",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Security Update"
        },
        {
            "HotFixId": "KB3156418",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-06-15T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3145432",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-05-12T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3145384",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-05-12T00:00:00Z",
            "Description": "Update"
        },
        {
            "HotFixId": "KB3146604",
            "InstalledBy": "NT AUTHORITY\\SYSTEM",
            "InstalledTime": "2016-05-12T00:00:00Z",
            "Description": "Update"
        }
    ],
    "SchemaVersion": "1.0",
    "NextToken": "AAEAATZ7h5MZSBZax3pNRMn5LTF/aOIbylNJxj/5LJbttCDqaFPutnVAhLKwvHtSX86sgzlfcwrsVaxEMVktcbn/x65PStfisYBgO9PVJx6sUX6+sARWDMVOg6F8eY+m8BpLrNWw3Lm5qSA5cp5lhUv04GXkbwxBbkjWFxtrzd8fLfApcVao1b/U07WofxCF8H0UyX6cEZ+GNikKbAQVBqOlEa8ovNSyg+zLgdPU+cEzWDDT9X+o/B0ODAAvtUDaWhP0Am/mHPAufTkvFgpvGdF28yM=",
    "CaptureTime": "2017-04-02T14:34:19Z"
}
```


### パッチベースラインへの準拠状況（？）

```bash:コマンド
aws ssm list-inventory-entries \
    --instance-id ${INSTANCE_ID} \
    --type-name AWS:PatchCompliance
```

```json:結果
{
    "InstanceId": "i-*****************",
    "TypeName": "AWS:PatchCompliance",
    "Entries": [
        {
            "KBId": "KB2919355",
            "Severity": "Critical",
            "Classification": "SecurityUpdates",
            "Title": "Windows 8.1 Update for x64-based Systems (KB2919355)",
            "State": "Installed",
            "InstalledTime": "2014-03-18T00:00:00.0000000Z"
        },
        {
            "KBId": "KB2966826",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 and Windows Server 2012 R2 for x64-based Systems (KB2966826)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB2966828",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 and Windows Server 2012 R2 for x64-based Systems (KB2966828)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB2968296",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 and Windows Server 2012 R2 for x64-based Systems (KB2968296)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB2972103",
            "Severity": "Critical",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 (KB2972103)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB2972213",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 and Windows Server 2012 R2 for x64-based Systems (KB2972213)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB2973114",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 (KB2973114)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB2978122",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 and Windows Server 2012 R2 for x64-based Systems (KB2978122)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB2982998",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 (KB2982998)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3000483",
            "Severity": "Critical",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 7 for x64-based Systems (KB3000483)",
            "State": "Installed",
            "InstalledTime": "2016-05-12T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3004361",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 8.1 for x64-based Systems (KB3004361)",
            "State": "Installed",
            "InstalledTime": "2015-02-10T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3004365",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 8.1 (KB3004365)",
            "State": "Installed",
            "InstalledTime": "2015-08-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3019978",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 8 (KB3019978)",
            "State": "Installed",
            "InstalledTime": "2015-01-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3022777",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 R2 x64 Edition (KB3022777)",
            "State": "Installed",
            "InstalledTime": "2015-01-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3023219",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 (KB3023219)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3023266",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 8.1 for x64-based Systems (KB3023266)",
            "State": "Installed",
            "InstalledTime": "2015-01-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3030377",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 R2 for Itanium-based Systems (KB3030377)",
            "State": "Installed",
            "InstalledTime": "2015-03-10T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3035126",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 (KB3035126)",
            "State": "Installed",
            "InstalledTime": "2015-03-10T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3037576",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 and Windows Server 2012 R2 for x64-based Systems (KB3037576)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3045685",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 (KB3045685)",
            "State": "Installed",
            "InstalledTime": "2015-04-15T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3045999",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 8.1 (KB3045999)",
            "State": "Installed",
            "InstalledTime": "2015-04-15T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3046017",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 (KB3046017)",
            "State": "Installed",
            "InstalledTime": "2015-08-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3055642",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 R2 (KB3055642)",
            "State": "Installed",
            "InstalledTime": "2015-05-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3059317",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 (KB3059317)",
            "State": "Installed",
            "InstalledTime": "2015-08-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3061512",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 R2 (KB3061512)",
            "State": "Installed",
            "InstalledTime": "2015-08-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3071756",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 7 for x64-based Systems (KB3071756)",
            "State": "Installed",
            "InstalledTime": "2015-08-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3072307",
            "Severity": "Critical",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 and Windows Server 2012 R2 for x64-based Systems (KB3072307)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3074545",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 (KB3074545)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3075220",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 (KB3075220)",
            "State": "Installed",
            "InstalledTime": "2015-08-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3082089",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 8.1 for x64-based Systems (KB3082089)",
            "State": "Installed",
            "InstalledTime": "2015-09-09T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3084135",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 R2 (KB3084135)",
            "State": "Installed",
            "InstalledTime": "2015-09-09T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3092601",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 for Itanium-based Systems (KB3092601)",
            "State": "Installed",
            "InstalledTime": "2015-11-12T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3097992",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 for x86-based Systems (KB3097992)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3109103",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 (KB3109103)",
            "State": "Installed",
            "InstalledTime": "2015-12-09T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3110329",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 7 for x64-based Systems (KB3110329)",
            "State": "Installed",
            "InstalledTime": "2016-01-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3121461",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 7 (KB3121461)",
            "State": "Installed",
            "InstalledTime": "2016-01-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3121918",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 R2 (KB3121918)",
            "State": "Installed",
            "InstalledTime": "2016-01-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3122651",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 (KB3122651)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3124275",
            "Severity": "Critical",
            "Classification": "SecurityUpdates",
            "Title": "Cumulative Security Update for Internet Explorer 8 for Windows 7 for x64-based Systems (KB3124275)",
            "State": "Installed",
            "InstalledTime": "2016-01-13T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3126434",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows 8.1 for x64-based Systems (KB3126434)",
            "State": "Installed",
            "InstalledTime": "2016-02-11T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3126587",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 R2 (KB3126587)",
            "State": "Installed",
            "InstalledTime": "2016-02-11T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3126593",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 (KB3126593)",
            "State": "Installed",
            "InstalledTime": "2016-02-11T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3127222",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 (KB3127222)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3133043",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 R2 x64 Edition (KB3133043)",
            "State": "Installed",
            "InstalledTime": "2016-02-11T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3135985",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 (KB3135985)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3139398",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 R2 for Itanium-based Systems (KB3139398)",
            "State": "Installed",
            "InstalledTime": "2016-03-08T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3139914",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 R2 (KB3139914)",
            "State": "Installed",
            "InstalledTime": "2016-03-08T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3142026",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Microsoft .NET Framework 3.5 on Windows 8.1 and Windows Server 2012 R2 for x64 (KB3142026)",
            "State": "Installed",
            "InstalledTime": "2017-04-02T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3146723",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2012 R2 (KB3146723)",
            "State": "Installed",
            "InstalledTime": "2016-04-12T00:00:00.0000000Z"
        },
        {
            "KBId": "KB3149090",
            "Severity": "Important",
            "Classification": "SecurityUpdates",
            "Title": "Security Update for Windows Server 2008 for Itanium-based Systems (KB3149090)",
            "State": "Installed",
            "InstalledTime": "2016-04-12T00:00:00.0000000Z"
        }
    ],
    "SchemaVersion": "1.0",
    "NextToken": "AAEAATexnyIR4JxtsdR11dWfIyDJJyym4x7iUGG0NT3QkTMSzznfW3U95SPg+cYmw7RfiRc0CKh4p6Zzx1mJjssXAe3MqPx3VOEKkYfETykHl1NT90duHwH3LAHbRut7lzzPe9vQKcPSz/h8XkPK+PVv6EuyGgEJ8X+2YF05pdLYDlK8Jbb3XbyOrgNaP4RRZE4bGjFFF9DM93eG0O3Let2/5v1yDkt7mbVDYL4T3YD9CEnnyxcROPaiNzfsq82ForVn0yYkPa7OpFG0kzCwiiwzfyc=",
    "CaptureTime": "2017-04-02T02:37:17Z"
}
```


### パッチの適用状況（概況）

```bash:コマンド
aws ssm list-inventory-entries \
    --instance-id ${INSTANCE_ID} \
    --type-name AWS:PatchSummary
```

```json:結果
{
    "InstanceId": "i-*****************",
    "TypeName": "AWS:PatchSummary",
    "Entries": [
        {
            "BaselineId": "pb-04ba050f612fba3a6",
            "InstalledOtherCount": "179",
            "FailedCount": "0",
            "MissingCount": "0",
            "NotApplicableCount": "1743",
            "OperationEndTime": "2017-04-02T14:37:17.5713419Z",
            "PatchGroup": "",
            "OperationType": "Install",
            "OwnerInformation": "",
            "OperationStartTime": "2017-04-02T14:20:50.0000000Z",
            "InstalledCount": "70",
            "SnapshotId": "de205080-287e-4a77-b17f-752a30f5b671"
        }
    ],
    "SchemaVersion": "1.0",
    "CaptureTime": "2017-04-02T02:37:17Z"
}
```

# 4. メンテナンスウィンドウの削除

## 4.1. メンテナンスウィンドウの削除

### パラメータの確認

```bash:コマンド
cat << ETX

    MAINTENANCE_WINDOW_ID: ${MAINTENANCE_WINDOW_ID}

ETX
```

```text:結果

    MAINTENANCE_WINDOW_ID: mw-*****************

```

### メンテナンスウィンドウの削除

```bash:コマンド
aws ssm delete-maintenance-window \
    --window-id ${MAINTENANCE_WINDOW_ID}
```

```json:結果
{
    "WindowId": "mw-*****************"
}
```

### メンテナンスウィンドウが削除されたことを確認

```bash:コマンド
aws ssm get-maintenance-window \
    --window-id ${MAINTENANCE_WINDOW_ID}
```

```text:結果
An error occurred (DoesNotExistException) when calling the GetMaintenanceWindow operation: Maintenance window mw-***************** does not exist
```


以上