簡體   English   中英

AWS Boto3-等待直到將卷附加到EC2實例

[英]AWS boto3 - wait until volume is attached to EC2 instance

我需要實現的是具有Lambda函數來創建EBS卷,將其附加到EC2實例,對其進行格式化並將其安裝在/data目錄下。

我正在使用ssm:RunCommandclient.send_command )執行應該格式化和裝入卷的shell腳本,但是代碼失敗,因為在我調用RunCommand時卷尚未附加到實例。

我正在使用EC2.Waiter.VolumeInUse等待連接卷,但似乎無法正常工作。

這是我的代碼

import boto3

# HARDCODED VALUES FOR TESTING
AVAILABILITY_ZONE = 'us-east-1d'
INSTANCE_ID = 'i-0bd640b495fd7d77c'

ec2_client = boto3.client('ec2')
ssm_client = boto3.client('ssm')

volume_available_waiter = ec2_client.get_waiter('volume_available')
volume_attached_waiter = ec2_client.get_waiter('volume_in_use')


def lambda_handler(event, context):
    try:
        # create 8 GB general purpose volume in given AZ
        create_volume_response = ec2_client.create_volume(
            AvailabilityZone=AVAILABILITY_ZONE,
            Size=8,
            VolumeType='gp2'
        )

        # retrieve volume id and wait till it is available
        volume_id = create_volume_response['VolumeId']
        volume_available_waiter.wait(
            VolumeIds=[volume_id]
        )

        # attach newly created volume to a given instance
        ec2_client.attach_volume(
            Device='/dev/xvdh',
            InstanceId=INSTANCE_ID,
            VolumeId=volume_id
        )

        # wait till the volume is properly attached to EC2 instance
        volume_attached_waiter.wait(
            VolumeIds=[volume_id]
        )

        # use SSM RunCommand to format and mount volume
        ssm_client.send_command(
            InstanceIds=[INSTANCE_ID],
            DocumentName='AWS-RunShellScript',
            Parameters={
                'commands': [
                    'echo "STARTING MOUNT SEQUENCE"'
                    'echo $(lsblk)'
                    'mkfs -t xfs /dev/xvdh',
                    'mkdir /data',
                    'mount /dev/xvdh /data'
                ]
            }
        )

    except Exception as e:
        print(e)

    return 0

當檢查log cat /var/log/messages ,我可以清楚地看到echo $(lsblk)輸出尚未附加新卷。

等待將卷連接到EC2實例之前的正確方法是什么?

在這種情況下,正確的方法是等待直到在SSM中附加了卷,而不是讓lambda掛起並等待。
由於已經在使用SSM,因此您將需要制作一個SSM Automation文檔 ,該文檔將等待卷被附加,然后執行RunCommand來格式化和掛載該卷。
您的文檔將需要添加2個步驟:
1- aws:waitForAwsResourceProperty等待連接卷
2- aws:runCommand執行您的Shell腳本

首先,創建您的SSM自動化文檔:

---
description: "Automation Document Example YAML Template"
schemaVersion: "0.3"
assumeRole: "{{ AutomationAssumeRole }}"
parameters:
  InstanceId:
    type: "String"
    description: "(Required) The ID of the EC2 Instance."
  VolumeId:
    type: "String"
    description: "(Required) The ID of the volume."
  AutomationAssumeRole:
    type: "String"
    description: "(Optional) The ARN of the role that allows Automation to perform the actions on your behalf."
    default: ""

mainSteps:
- name: "VerifyVolumeAttached"
  action: "aws:waitForAwsResourceProperty"
  timeoutSeconds: 600
  inputs:
    Service: "ec2"
    Api: "DescribeVolumes"
    VolumeIds: ["{{ VolumeId }}"]
    PropertySelector: "$.Volumes[0].Attachments[0].State"
    DesiredValues:
    - "attached"

- name: "MountVolume"
  action: "aws:runCommand"
  inputs:
    DocumentName: "AWS-RunShellScript"
    InstanceIds:
    - "{{InstanceId}}"
    Parameters:
      commands: ['echo "STARTING MOUNT SEQUENCE"','echo $(lsblk)','mkfs -t xfs /dev/xvdh','mkdir /data','mount /dev/xvdh /data']

然后,您將需要為SSM創建IAM角色,並具有對Runcommand和DescribeVolumes的必需權限。
然后將lambda中的send命令塊替換為:

# Start SSM automation execution    
ssm_client.start_automation_execution(DocumentName=your_automation_document_name,Parameters={"InstanceId": [INSTANCE_ID],"VolumeId":[volume_id],"AutomationAssumeRole":[ssm_automation_role_arn]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM