【问题标题】:AWS boto3 - wait until volume is attached to EC2 instanceAWS boto3 - 等到卷附加到 EC2 实例
【发布时间】:2019-07-26 17:25:46
【问题描述】:

我需要实现的是拥有创建 EBS 卷、将其附加到 EC2 实例、对其进行格式化并将其挂载到 /data 目录下的 Lambda 函数。

我正在使用ssm:RunCommand (client.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

在查看日志cat /var/log/messages 时,我可以清楚地看到echo $(lsblk) 的输出尚未附加新卷。

等待卷附加到 EC2 实例的正确方法是什么?

【问题讨论】:

    标签: python amazon-web-services aws-lambda boto3


    【解决方案1】:

    在这种情况下,正确的方法是等到卷附加到 SSM 中,而不是让您的 lambda 挂起等待。
    由于您已经在使用 SSM,因此您需要创建一个 SSM Automation document 来等待卷被附加,然后执行 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']
    

    然后,您需要创建一个IAM Role for SSM,并拥有 Runcommand 和 DescribeVolumes 所需的权限。
    然后将 lambda 中的发送命令块替换为:

    # 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]}
    

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 2015-04-10
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多