客户发了一个需求如下:

用shell 或者python3 控制aws去获取新IP、绑定IP到实例

这个就非常简单了,因为本身aws就提供python的工具,一切都可以api化的

做法如下:

#安装aws的工具
cd /tmp 
curl -kL "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version
 
#配置aws key
aws configure
 
#查看配置
aws configure list

----------------------------

#申请一个新IP并且打tag
aws ec2 allocate-address --region $Region |tee /tmp/eip.log
eip_id=$(jq -r ".AllocationId" /tmp/eip.log)
aws ec2 create-tags --resources ${eip_id} --tags Key=Name,Value=eip-01

eip=$(jq -r ".PublicIp" /tmp/eip.log)

#给ec2赋ip,前提是知道ec2_id
aws ec2 associate-address --instance-id ${ec2_id} --allocation-id ${eip_id}


----------------------------

#启动新ec2的方法
#启动ec2
aws ec2 run-instances \
--region $Region --count 1 \
--instance-type t2.micro \
--subnet-id ${lan_a_public_id} \
--security-group-ids $gid \
--key-name MySshKey \
--image-id ami-04ff9e9b51c1f62ca  \
 |tee /tmp/ec2.log
 
ec2_id=$(jq -r ".Instances[0].InstanceId" /tmp/ec2.log)
参考:

https://www.cnblogs.com/elvi/p/16542406.html