演練:使用自動化、AWS Lambda 和 Parameter Store 簡化 AMI 修補
以下範例延伸說明如何更新 Windows AMI,如 逐步解說:修補 Windows Server AMI 中所述。在此範例使用的模型中,組織會維護並定期修補其自有的專屬 AMIs,而非從 Amazon Elastic Compute Cloud (Amazon EC2) AMIs 建立。
以下程序示範如何自動將作業系統 (OS) 修補程式套用至已視為是最近期或最新 AMI 的 Windows AMI。在範例中,參數 SourceAmiId
的預設值是由稱為 latestAmi
的 AWS Systems Manager Parameter Store 參數定義。latestAmi
的值是由在自動化結束時呼叫的 AWS Lambda 函數更新。此自動化程序可將耗費在修補 AMIs 的時間與心力降至最低,原因在於修補一律會套用最新的 AMI。Parameter Store 和 Automation 是 AWS Systems Manager 的功能。
開始之前
設定 Automation 角色和 (選用) Automation 的 Amazon EventBridge。如需詳細資訊,請參閱 設定自動化。
內容
任務 1:建立 Systems Manager Parameter Store 參數
在 Parameter Store 中建立字串參數,使用以下資訊:
-
Name (名稱):
latestAmi
。 -
Value (值):Windows AMI ID。例如:
ami-188d6e0e
。
如需建立 Parameter Store 字串參數的詳細資訊,請參閱 建立 Systems Manager 參數。
任務 2:建立 AWS Lambda 的 IAM 角色
使用以下程序為 AWS Lambda 建立 IAM 服務角色。這些政策會提供 Lambda 許可,以使用 Lambda 函數和 Systems Manager 來更新 latestAmi
參數的值。
建立適用於 Lambda 的 IAM 服務角色
登入 AWS Management Console,並開啟位於 https://console.aws.amazon.com/iam/
的 IAM 主控台。 -
在導覽窗格中,選擇 Policies (政策),然後選擇 Create policy (建立政策)。
-
請選擇 JSON 標籤。
-
將預設內容取代為以下內容。確定將
us-west-2
和123456789012
取代為您要使用的區域和帳戶。將updateAmiFunction
取代為您的 Lambda 函數的名稱。{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "logs:CreateLogGroup", "Resource": "arn:aws:logs:
us-west-2
:123456789012
:*" }, { "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": [ "arn:aws:logs:us-west-2
:123456789012
:log-group:/aws/lambda/updateAmiFunction
:*" ] } ] } -
選擇 Review policy (檢閱政策)。
-
在 Review Policy (檢閱政策) 頁面上 Name (名稱)中,輸入該內嵌政策的名稱,例如
amiLambda
。 -
選擇 Create policy (建立政策)。
-
重複步驟 2 和 3。
-
將預設內容取代為以下內容。確定將
us-west-2
和123456789012
取代為您要使用的區域和帳戶。{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ssm:PutParameter", "Resource": "arn:aws:ssm:
us-west-2
:123456789012
:parameter/latestAmi" }, { "Effect": "Allow", "Action": "ssm:DescribeParameters", "Resource": "*" } ] } -
選擇 Review policy (檢閱政策)。
-
在 Review Policy (檢閱政策) 頁面上 Name (名稱)中,輸入該內嵌政策的名稱,例如
amiParameter
。 -
選擇 Create policy (建立政策)。
-
在導覽窗格中,選擇 Roles (角色),然後選擇 Create role (建立角色)。
-
緊接在 Choose the service that will use this role (選擇將使用此角色的服務) 下,選擇 Lambda,然後選擇 Next: Permissions (下一步:許可)。
-
在 Attach permissions policies (連接許可政策) 頁面上,使用 Search (搜尋) 欄位找出您稍早建立的兩個政策。
-
選取政策旁的核取方塊,然後選擇 Next: Tags (下一步:標籤)。
-
(選用) 新增一或多個標籤來組織鍵值組、追蹤或控制存取此角色,然後選擇 Next: Review (下一步:檢視)。
-
對於 Role name (角色名稱),輸入新角色的名稱,例如
lambda-ssm-role
或另一個您喜好的名稱。注意 因為有各種實體可能會參照角色,所以您無法在建立角色之後變更角色名稱。
-
選擇 Create Role (建立角色)。
任務 3:建立 AWS Lambda 函數
使用以下程序建立可自動更新 latestAmi
參數值的 Lambda 函數。
若要建立 Lambda 函數
請登入 AWS Management Console,並開啟位於 https://console.aws.amazon.com/lambda/
的 AWS Lambda 主控台。 -
選擇 Create function (建立函數)。
-
在 Create function (建立函數) 頁面上,選擇 Author from scratch (從頭開始撰寫)。
-
針對 Function name (函數名稱),輸入
Automation-UpdateSsmParam
。 -
在 Runtime (執行時間) 清單中,選擇 Python 3.8。
-
在 Permissions (許可) 區段中,展開 Choose or create an execution role (選擇或建立執行角色)。
-
選擇 Use an existing role (使用現有角色),然後為您在任務 2 中建立的 Lambda 選擇服務角色。
-
選擇 Create function (建立函數)。
-
在 Function code (函數程式碼) 區域的 lambda_function 索引標籤中,刪除欄位中預先填入的程式碼,接著貼上以下範本程式碼。
from __future__ import print_function import json import boto3 print('Loading function') #Updates an SSM parameter #Expects parameterName, parameterValue def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # get SSM client client = boto3.client('ssm') #confirm parameter exists before updating it response = client.describe_parameters( Filters=[ { 'Key': 'Name', 'Values': [ event['parameterName'] ] }, ] ) if not response['Parameters']: print('No such parameter') return 'SSM parameter not found.' #if parameter has a Description field, update it PLUS the Value if 'Description' in response['Parameters'][0]: description = response['Parameters'][0]['Description'] response = client.put_parameter( Name=event['parameterName'], Value=event['parameterValue'], Description=description, Type='String', Overwrite=True ) #otherwise just update Value else: response = client.put_parameter( Name=event['parameterName'], Value=event['parameterValue'], Type='String', Overwrite=True ) reponseString = 'Updated parameter %s with value %s.' % (event['parameterName'], event['parameterValue']) return reponseString
-
選擇 Save (儲存)。
-
若要測試 Lambda 函數,請從 Select a test event (選取測試事件) 選單,選擇 Configure test events (設定測試事件)。
-
針對 Event name (事件名稱),輸入測試事件的名稱,例如
MyTestEvent
。 -
用以下 JSON 取代現有文字,將
your-ami-id
取代為新 AMI 的 ID 以設定為latestAmi
參數值。{ "parameterName":"latestAmi", "parameterValue":"
your-ami-id
" } -
選擇 Create (建立 OpsItem)。
-
選擇 Test (測試) 以測試函數。輸出應該會顯示參數已成功更新,並包含更新的詳細資訊。例如:「Updated parameter latestAmi with value ami-123456」(以值 ami-123456 更新了參數 latestAmi)。
任務 4:建立 Runbook 並修補 AMI
使用以下程序建立和執行 Runbook,以修補您針對 latestAmi 參數指定的 AMI。自動化工作流程完成後,latestAmi 的值會以新修補的 AMI 之 ID 更新。後續的自動化會使用由先前執行建立的 AMI。
若要建立 Runbook 並修補 AMI
開啟位於 AWS Systems Managerhttps://console.aws.amazon.com/systems-manager/ 的 主控台。https://console.aws.amazon.com/systems-manager/
在導覽窗格中,選擇 Documents (文件)。
-或-
如果 AWS Systems Manager 首頁先開啟,選擇選單圖示 (
) 以開啟導覽窗格,然後在導覽窗格中,選擇 Documents (文件)。
-
選擇 Create automation (建立自動化)。
-
在 Name (名稱)欄位中,輸入
UpdateMyLatestWindowsAmi
。 -
選擇 Editor (編輯器) 標籤,然後選擇 Edit (編輯)。
-
用下面的 JSON 範例 Runbook 取代 Document editor (文件編輯器) 欄位中的預設內容。
注意 您必須將此範本中的
assumeRole
和IamInstanceProfileName
值變更為您在 設定自動化 時建立的服務角色 ARN 和執行個體設定檔角色。{ "description":"Systems Manager Automation Demo – Patch AMI and Update SSM Param", "schemaVersion":"0.3", "assumeRole":"
the role ARN you created
", "parameters":{ "sourceAMIid":{ "type":"String", "description":"AMI to patch", "default":"{{ssm:latestAmi}}" }, "targetAMIname":{ "type":"String", "description":"Name of new AMI", "default":"patchedAMI-{{global:DATE_TIME}}" } }, "mainSteps":[ { "name":"startInstances", "action":"aws:runInstances", "timeoutSeconds":1200, "maxAttempts":1, "onFailure":"Abort", "inputs":{ "ImageId":"{{ sourceAMIid }}", "InstanceType":"m3.large", "MinInstanceCount":1, "MaxInstanceCount":1, "IamInstanceProfileName":"the name of the IAM role you created
" } }, { "name":"installMissingWindowsUpdates", "action":"aws:runCommand", "maxAttempts":1, "onFailure":"Continue", "inputs":{ "DocumentName":"AWS-InstallWindowsUpdates", "InstanceIds":[ "{{ startInstances.InstanceIds }}" ], "Parameters":{ "SeverityLevels":"Important" } } }, { "name":"stopInstance", "action":"aws:changeInstanceState", "maxAttempts":1, "onFailure":"Continue", "inputs":{ "InstanceIds":[ "{{ startInstances.InstanceIds }}" ], "DesiredState":"stopped" } }, { "name":"createImage", "action":"aws:createImage", "maxAttempts":1, "onFailure":"Continue", "inputs":{ "InstanceId":"{{ startInstances.InstanceIds }}", "ImageName":"{{ targetAMIname }}", "NoReboot":true, "ImageDescription":"AMI created by EC2 Automation" } }, { "name":"terminateInstance", "action":"aws:changeInstanceState", "maxAttempts":1, "onFailure":"Continue", "inputs":{ "InstanceIds":[ "{{ startInstances.InstanceIds }}" ], "DesiredState":"terminated" } }, { "name":"updateSsmParam", "action":"aws:invokeLambdaFunction", "timeoutSeconds":1200, "maxAttempts":1, "onFailure":"Abort", "inputs":{ "FunctionName":"Automation-UpdateSsmParam", "Payload":"{\"parameterName\":\"latestAmi\", \"parameterValue\":\"{{createImage.ImageId}}\"}" } } ], "outputs":[ "createImage.ImageId" ] } -
選擇 Create automation (建立自動化) 以儲存 Runbook。
-
在導覽窗格中,選擇 Automation (自動化),接著選擇 Execute automation (執行自動化)。
-
在 Choose document (選擇文件) 頁面中,選擇 Owned by me (由我擁有) 索引標籤,然後選取 UpdateMyLatestWindowsAmi 卡片中的按鈕。
-
在 Document details (文件詳細資訊) 部分,確認 Document version (文件版本) 設為 1 (Default)。
-
選擇 Next (下一步)。
-
選擇 Simple execution (簡單執行)。
-
選擇 Execute (執行)。
-
自動化完成後,在導覽窗格中選擇 Parameter Store 並確認
latestAmi
的新值符合自動化傳回的值。您也可以在 Amazon EC2 主控台的 AMIs 部分確認新的 AMI ID 符合自動化輸出。