客户发了一个需求如下:
1用shell 或者python3 控制aws去获取新IP、绑定IP到实例
这个就非常简单了,因为本身aws就提供python的工具,一切都可以api化的
做法如下:
1#安装aws的工具
2cd /tmp
3curl -kL "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
4unzip awscliv2.zip
5sudo ./aws/install
6aws --version
7
8#配置aws key
9aws configure
10
11#查看配置
12aws configure list
13
14----------------------------
15
16#申请一个新IP并且打tag
17aws ec2 allocate-address --region $Region |tee /tmp/eip.log
18eip_id=$(jq -r ".AllocationId" /tmp/eip.log)
19aws ec2 create-tags --resources ${eip_id} --tags Key=Name,Value=eip-01
20
21eip=$(jq -r ".PublicIp" /tmp/eip.log)
22
23#给ec2赋ip,前提是知道ec2_id
24aws ec2 associate-address --instance-id ${ec2_id} --allocation-id ${eip_id}
25
26
27----------------------------
28
29#启动新ec2的方法:
30#启动ec2
31aws ec2 run-instances \
32--region $Region --count 1 \
33--instance-type t2.micro \
34--subnet-id ${lan_a_public_id} \
35--security-group-ids $gid \
36--key-name MySshKey \
37--image-id ami-04ff9e9b51c1f62ca \
38 |tee /tmp/ec2.log
39
40ec2_id=$(jq -r ".Instances[0].InstanceId" /tmp/ec2.log)