是否可以使用您所在的服务器更改ec2中的IP?
我目前在控制台中所做的是:
但是,我在控制台中执行此操作,因为ec2服务器正在关闭。有没有办法在我使用的当前服务器上执行此操作。例如,在伪代码中:
import ec2, boto
ec2.disappociate_current_ip()
ec2.release_ip()
ec2.allocate_new_ip()
ec2.associate_new_ip()
答案 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)