【问题标题】:Copy AMI to another region using boto3使用 boto3 将 AMI 复制到另一个区域
【发布时间】:2019-01-15 03:43:42
【问题描述】:

我正在尝试自动化我的 AWS EC2 控制台上的“复制 AMI”功能,谁能指出一些通过 boto3 执行此操作的 Python 代码?

【问题讨论】:

    标签: amazon-web-services amazon-ec2 boto3 amazon-ami


    【解决方案1】:

    我大部分时间都使用 EC2.ServiceResource 之类的高级资源,所以下面是我用来同时使用 EC2 资源和低级客户端的代码,

    source_image_id = '....'
    profile = '...'
    source_region = 'us-west-1'
    source_session = boto3.Session(profile_name=profile, region_name=source_region)
    ec2 = source_session.resource('ec2')
    ami = ec2.Image(source_image_id)
    target_region = 'us-east-1'
    target_session = boto3.Session(profile_name=profile, region_name=target_region)
    target_ec2 = target_session.resource('ec2')
    target_client = target_session.client('ec2')
    response = target_client.copy_image(
      Name=ami.name,
      Description = ami.description,
      SourceImageId = ami.id,
      SorceRegion = source_region
    )
    target_ami = target_ec2.Image(response['ImageId'])
    

    【讨论】:

      【解决方案2】:

      更准确地说。

      假设您要复制的 AMI 位于 us-east-1(源区域)。 您的要求是将其复制到 us-west-2(目标区域)

      获取 boto3 EC2 客户端会话到 us-west-2 区域,然后在 SourceRegion 中传递 us-east-1。

      import boto3
      session1 = boto3.client('ec2',region_name='us-west-2')
      
      response = session1.copy_image(
         Name='DevEnv_Linux',
         Description='Copied this AMI from region us-east-1',
         SourceImageId='ami-02a6ufwod1f27e11',
         SourceRegion='us-east-1'
      )
      

      【讨论】:

        【解决方案3】:

        来自EC2 — Boto 3 documentation

        response = client.copy_image(
            ClientToken='string',
            Description='string',
            Encrypted=True|False,
            KmsKeyId='string',
            Name='string',
            SourceImageId='string',
            SourceRegion='string',
            DryRun=True|False
        )
        

        确保将请求发送到目标区域,并传递对SourceRegion 的引用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多