1. 程式人生 > >Automatically Attach a Second ENI to an Instance Launched Through Auto Scaling

Automatically Attach a Second ENI to an Instance Launched Through Auto Scaling

import boto3
import botocore
from datetime import datetime

ec2_client = boto3.client('ec2')
asg_client = boto3.client('autoscaling')


def lambda_handler(event, context):
    if event["detail-type"] == "EC2 Instance-launch Lifecycle Action":
        instance_id = event['detail']['EC2InstanceId']
        LifecycleHookName=event['detail']['LifecycleHookName']
        AutoScalingGroupName=event['detail']['AutoScalingGroupName']
        subnet_id = get_subnet_id(instance_id)
        interface_id = create_interface(subnet_id)
        attachment = attach_interface(interface_id, instance_id)
        if not interface_id:
            complete_lifecycle_action_failure(LifecycleHookName,AutoScalingGroupName,instance_id)
        elif not attachment:
            complete_lifecycle_action_failure(LifecycleHookName,AutoScalingGroupName,instance_id)
            delete_interface(interface_id)
        else:
            complete_lifecycle_action_success(LifecycleHookName,AutoScalingGroupName,instance_id)
       
        
def get_subnet_id(instance_id):
    try:
        result = ec2_client.describe_instances(InstanceIds=[instance_id])
        vpc_subnet_id = result['Reservations'][0]['Instances'][0]['SubnetId']
        log("Subnet id: {}".format(vpc_subnet_id))

    except botocore.exceptions.ClientError as e:
        log("Error describing the instance {}: {}".format(instance_id, e.response['Error']))
        vpc_subnet_id = None

    return vpc_subnet_id


def create_interface(subnet_id):
    network_interface_id = None

    if subnet_id:
        try:
            network_interface = ec2_client.create_network_interface(SubnetId=subnet_id)
            network_interface_id = network_interface['NetworkInterface']['NetworkInterfaceId']
            log("Created network interface: {}".format(network_interface_id))
        except botocore.exceptions.ClientError as e:
            log("Error creating network interface: {}".format(e.response['Error']))

    return network_interface_id


def attach_interface(network_interface_id, instance_id):
    attachment = None

    if network_interface_id and instance_id:
        try:
            attach_interface = ec2_client.attach_network_interface(
                NetworkInterfaceId=network_interface_id,
                InstanceId=instance_id,
                DeviceIndex=1
            )
            attachment = attach_interface['AttachmentId']
            log("Created network attachment: {}".format(attachment))
        except botocore.exceptions.ClientError as e:
            log("Error attaching network interface: {}".format(e.response['Error']))

    return attachment


def delete_interface(network_interface_id):
    try:
        ec2_client.delete_network_interface(
            NetworkInterfaceId=network_interface_id
        )
        log("Deleted network interface: {}".format(network_interface_id))
        return True

    except botocore.exceptions.ClientError as e:
        log("Error deleting interface {}: {}".format(network_interface_id, e.response['Error']))
        
        
def complete_lifecycle_action_success(hookname,groupname,instance_id):
    try:
        asg_client.complete_lifecycle_action(
                LifecycleHookName=hookname,
                AutoScalingGroupName=groupname,
                InstanceId=instance_id,
                LifecycleActionResult='CONTINUE'
            )
        log("Lifecycle hook CONTINUEd for: {}".format(instance_id))
    except botocore.exceptions.ClientError as e:
            log("Error completing life cycle hook for instance {}: {}".format(instance_id, e.response['Error']))
            log('{"Error": "1"}')    
            
def complete_lifecycle_action_failure(hookname,groupname,instance_id):
    try:
        asg_client.complete_lifecycle_action(
                LifecycleHookName=hookname,
                AutoScalingGroupName=groupname,
                InstanceId=instance_id,
                LifecycleActionResult='ABANDON'
            )
        log("Lifecycle hook ABANDONed for: {}".format(instance_id))
    except botocore.exceptions.ClientError as e:
            log("Error completing life cycle hook for instance {}: {}".format(instance_id, e.response['Error']))
            log('{"Error": "1"}')    
    

def log(error):
    print('{}Z {}'.format(datetime.utcnow().isoformat(), error))

相關推薦

Automatically Attach a Second ENI to an Instance Launched Through Auto Scaling

import boto3 import botocore from datetime import datetime ec2_client = boto3.client('ec2') asg_client = boto3.client('autoscaling') def lamb

Troubleshoot Connecting to an Instance in a VPC

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

開啟頁面出現Object reference not set to an instance of an object錯誤

開啟網頁出現 查看出錯的位置,如圖中紅色部分所標,因為系統之前執行正常,所以這部分程式碼是沒有問題的,出問題的函式是get name函式,開啟相應的網頁程式碼,發現 其功能是根據專業程式碼讀取專業名稱,應該就最近增加的相應資料量出現了問題,從資料庫中把相關的表格開啟檢查,果然發現,有的

Deploy Code From a CodeCommit Repository to an Elastic Beanstalk Environment

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

Attach a Security Group to a Load Balancer

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

Add a Second Elastic IP Address with a Single Elastic Network Interface to an EC2 Instance

When you add a second Elastic IP address to an elastic network interface, that Elastic IP address is lost when the interface is rebooted. To ma

Assign a Custom Primary Private Address to an Amazon EC2 Instance

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

Attach an RDS DB Instance to an OpsWorks Stack

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

asmcmd:Connected to an idle instance.

asmcmd原因:環境變量設置錯誤 asmcmd:Connected to an idle instance.

NetScaler SNIPs Bound To An Interface Without A VLAN

nic objective summary uptime env imp oci map you NetScaler SNIPs Bound To An Interface Without A VLAN https://www.citrix.com/blogs/2014/0

解決 Unable to create an instance of type [com.sun.faces.config.ConfigureListener]

宣告:每個人的的電腦都會因為電腦環境,版本等因素不同,可能解決方法不通用,請大家多點耐心吧,畢竟是幹這行的,開始學習的時候,我搭建SSM框架很多次,有問題無法解決就重頭搭建,bug是有的,但總有一天能克服。   我遇到的問題 Caused by: org.apache.cata

問題解決:Pytorch :Trying to backward through the graph a second time, but the buffers。。

最近在學習Pytorch,剛用Pytorch重寫了之前用Tensorlfow寫的論文程式碼。 首次執行就碰到了一個bug: Pytorch - RuntimeError: Trying to backward through the graph a second time, but the

PBRT_V2 總結記錄 <5> A good way to gain an understanding of pbrt

A good way to gain an understanding of pbrt is to follow the process of computing the radiance value for a single ray in a debugger. Build

Each record in table should have a unique `key` prop,or set `rowKey` to an unique primary key.

鍵值對 clas ima 處理 unique uniq http ould rowkey 1.react 報錯 Each record in table should have a unique `key` prop,or set `rowKey` to an uniq

How to attach multiple files to an email using JavaMail?

在 java 的世界裡要寄Email+附件還滿簡單的,sample code 如下: import java.util.Properties; import javax.activation.*; import javax.mail.*; public class MailProjectClass

identifier of an instance of .. altered to null ---- hibernate exception

identifier of an instance of .. altered to null 是做Hibernate,對一條資料進行復制(新增資料)時遇到的問題 原因: 在SSH框架中,我們常常把事務放在業務邏輯層(Manager),所有業務邏輯完成後才能commit事務

Reality Design: A 60 second ‘How To Guide’

Reality Design: A 60 second ‘How To Guide’Wanna design for AR, MR, VR or all the RRRs? What are you- some sorta pirate???? Let’s do this!Am I recommending

How to Integrate a C Library into an iOS App Written in Swift

Nowadays, everyone values privacy and security. That’s why it wasn’t surprising when, recently, we needed to use an encryption library on one of our Distil

Ask HN: Is it a good idea to do an internship after a year working full time?

I am finding it extremely hard to land a job abroad (read US/Canada) with my current experience. I think I may have a better chance trying for an internshi

identifier of an instance of bean was altered from 1 to 2(持久化物件ID變更)

今天遇到個怪問題,hibernate修改外來鍵id時出現: org.springframework.orm.hibernate3.HibernateSystemException: identifier of an instance of xx altered from 2