如何将 NAT 实例置于自动缩放中?

How to put a NAT-Instance in auto scaling?

我想创建一个容错网站并尝试创建一个自动缩放 group.NAT- 使用了实例而不是 NAT 网关。我遇到了以下问题。

当 NAT 实例[由于某种原因]终止时。自动缩放组将启动相应的 NAT 映像,但它不会禁用 Source/destination 检查。这必须手动完成,因此,连接到 nat 实例的私有子网将具有状态消息 "Black-hole"。除非手动更改源目标检查,否则私有子网甚至不会显示新的 NAT 实例。

有人能解决这个问题吗?

一种选择是使用 Instance Recovery 而不是自动缩放。它替换实例而不更改 任何东西(甚至实例 ID 保持不变)。

当然,与 NAT 实例相比,NAT 网关本质上是容错的,因为它们不是像实例那样位于单个物理位置的单个物理事物。

您可以使用 AWS CLI 修改网络接口的 sourceDestCheck 属性。您可以从实例的用户数据启动它。其他方法是自定义 python 程序甚至 PowerShell(包括在下面)。

aws ec2 modify-instance-attribute --instance-id i-1234567890abcdef0 --source-dest-check "{\"Value\": true}"

或者通过更改网络接口。

aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --no-source-dest-check

这个 Stack Overflow 问题涵盖了在 Python 中做同样的事情。

禁用Source/Destination检查AWSPythonBoto

本文档介绍了如何在 PowerShell 中执行此操作。

Edit-EC2NetworkInterfaceAttribute Cmdlet

我的首选方法是 Python 或 PowerShell。这些方法是获取所需参数(instanceId 或 networkId)的最简单方法。

[编辑:示例程序]

下面的两个示例都需要在实例上安装凭据或 IAM 角色。这是修改 source/destination 标志所必需的。

这是一个示例 shell 脚本。

EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`"
EC2_AVAIL_ZONE="`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone`"
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*$:\1:'`"
echo "Region:" $EC2_REGION

aws ec2 modify-instance-attribute --instance-id $EC2_INSTANCE_ID --source-dest-check "{\"Value\": false}" --region $EC2_REGION

rc=$?; if [[ $rc != 0 ]]; then echo "Failure:" $rc; exit $rc; fi

echo "Success"

这是一个使用 boto3 的示例 Python 2 程序(将区域更改为您的区域):

#!/usr/bin/python
import boto3
import requests
import sys

# install boto3
# sudo pip install boto3

# Disable stack trace on failure
sys.tracebacklimit = 0

# Specify the URL for the instance metadata
url = 'http://169.254.169.254/latest/meta-data/instance-id'

# Specify the region where our instance is at
region = 'us-west-2'

# Make a request to get the contents of the URL
r = requests.get(url)

if r.ok != True:
    print "Error: Failed to get instance-id from metadata:", r.reason
    print "Status Code:", r.status_code
    sys.exit(1)

# Get the instance ID from the return response
instance_id = r.text

print "Instance ID:", instance_id

if instance_id[0] != 'i':
    print "Error: Does not look like a valid instance ID: ", instance_id
    sys.exit(1)

client = boto3.client('ec2', region_name=region)

r = client.modify_instance_attribute(InstanceId=instance_id, SourceDestCheck={'Value': False})

code = r['ResponseMetadata']['HTTPStatusCode']

if code != 200:
    print "Error: Cannot change SourceDestCheck: ", code
    sys.exit(1)

print "Success: SourceDestCheck disabled"