如何在ec2中更改弹性IP

时间:2016-12-26 19:53:26

标签: amazon-web-services amazon-ec2 boto boto3 elastic-ip

是否可以使用您所在的服务器更改ec2中的IP?

我目前在控制台中所做的是:

  1. 关闭ec2
  2. 取消关联弹性IP地址
  3. 释放弹性IP地址(因此我可以创建一个新的IP地址,否则,它表示最大IP)
  4. 分配新的弹性IP地址
  5. 启动ec2
  6. 将新的弹性IP地址与ec2
  7. 相关联

    但是,我在控制台中执行此操作,因为ec2服务器正在关闭。有没有办法在我使用的当前服务器上执行此操作。例如,在伪代码中:

    import ec2, boto
    ec2.disappociate_current_ip()
    ec2.release_ip()
    ec2.allocate_new_ip()
    ec2.associate_new_ip()
    

1 个答案:

答案 0 :(得分:3)

有可能。 当您取消关联弹性IP地址时,您可能会失去互联网连接,具体取决于您的子网设置。如果您的子网配置为自动分配公共IP,您将在解除关联和关联之间获得公共IP(非弹性IP)。但是,如果您的公有子网未配置为自动获取公共IP,则您的实例将失去Internet连接(除非有到达Internet的路由),并且您的其余脚本将不会执行。以下是一个Boto3脚本,为您提供但未经测试的想法。调整它以满足您的需求。

import boto3
import requests

client = boto3.client('ec2')
inst_id = requests.get('http://169.254.169.254/latest/meta-data/instance-id').text
print inst_id

public_ip = requests.get('http://169.254.169.254/latest/meta-data/public-ipv4').text
print 'Current IP:', public_ip
print 'Disassociating:', public_ip
client.disassociate_address(PublicIp=public_ip)

public_ip = client.allocate_address( Domain='vpc')['PublicIp']
print 'New IP:', public_ip
print 'Associating:', public_ip
client.associate_address(InstanceId=inst_id, PublicIp=public_ip)