首页 > 解决方案 > 用于分配弹性 IP 的 AWS EC2 用户数据脚本

问题描述

我正在尝试为 VPC 创建自己的堡垒主机,并创建了一个最小/最大实例为 1 的自动缩放组。在我的启动配置中,我为 ec2 用户数据指定以下内容:

#!

INSTANCE_ID=`/usr/bin/curl -s http://169.254.169.254/latest/meta-data/instance-id`

aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id eipalloc-my-eip-id --allow-reassociation

此用户数据的目标是立即将弹性 IP 地址与我新创建的 EC2 实例相关联 -我从其他 StackOverflow 帖子中读到,在使用 ASG 时必须明确完成此操作。

但是,在 ASG 实例启动并完成初始化后,我仍然没有在该实例的控制台输出中看到任何弹性 IP:

在此处输入图像描述

我已经确认实例确实正在使用用户数据: 在此处输入图像描述

我试图查看系统日志以查看初始化期间是否有任何错误消息,但起初我看不到任何表明associate-address命令失败的信息(内部/var/log/cloud-init-output)。

编辑:尝试调试:

但是,我随后手动将弹性 IP 与我的实例关联 SSH,并尝试运行上面的用户数据命令。有趣的是,当我到达该aws ec2 associate-address部分时,我遇到了

无法找到凭据。您可以通过运行“aws configure”来配置凭据。

这似乎是问题的根源 - 我的 AWS 配置文件未配置。但是,我一直认为会为您设置默认的 AWS 实例配置文件,以便在实例完成初始化时访问 AWS CLI。

谁能指出为什么我的用户数据关联弹性 IP 地址可能无法正常执行?

标签: amazon-web-servicesamazon-ec2

解决方案


看起来附加到此 EC2 实例的实例配置文件没有执行上述任务的权限。

参考https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-ec2-console.html#ex-eip

您能否确保您的实例配置文件允许以下操作?

ec2:AllocateAddress: To allocate an Elastic IP address.

ec2:ReleaseAddress: To release an Elastic IP address.

ec2:AssociateAddress: To associate an Elastic IP address with an instance or a network interface.

ec2:DescribeNetworkInterfaces and ec2:DescribeInstances: To work with the Associate address screen. The screen displays the available instances or network interfaces to which you can associate an Elastic IP address.

ec2:DisassociateAddress: To disassociate an Elastic IP address from an instance or a network interface.

示例策略如下所示:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "ec2:DescribeAddresses",
            "ec2:AllocateAddress",
            "ec2:DescribeInstances",
            "ec2:AssociateAddress"
        ],
        "Resource": "*"
    }
]

}

希望这可以帮助。


推荐阅读