如何利用DigitalOcean的API自动切换Floating IP并更新CloudFlare记录
环境
- PHP7
- Debian
- DigitalOcean
- CloudFlare
流程
- Test TCP Status(TCP Status is FALSE)
- Unassign old Floating IP from Droplet
- Assign new Floating IP to Droplet
- Update new Floating IP to Cloudflare
- Delete old Unassigned Floating IP
- Test TCP Status Again(TCP Status is TRUE)
初始化
替换代码高亮行的DigitalOcean_API_KEY以及CloudFlare_API_KEY
替换内容参见官方文档:
- DigitalOcean:https://docs.digitalocean.com/reference/api/api-reference/#section/Authentication
- CloudFlare:https://api.cloudflare.com/#getting-started-requests
DigitalOcean中Droplets的Name要和绑定的域名一致,示例中Droplets的Name为nyc.minirplus.com,Droplets绑定的域名也是nyc.minirplus.com。
使用方法
将代码保存为php文件 auto_swap_ip_digitalocean.php ,放入 /usr/local/sbin ,然后先在shell中进行手动测试
1 |
php /usr/local/sbin/auto_swap_ip_digitalocean.php nyc.minirplus.com |
测试完毕后通过crontab进行定时调用
1 2 |
# Auto Swap IP For DigitalOcean * * * * * sudo -u root php /usr/local/sbin/auto_swap_ip_digitalocean.php nyc.minirplus.com >> /var/log/auto_swap_ip_digitalocean_nyc.minirplus.com.log |
执行缓存文件保存在当前用户的根目录下的 data_auto_swap_ip_digitalocean_'.$server_name.'.json
Test TCP Status的错误次数在 $max_tcp_test_time 设置,默认为15次错误,如果定时任务设置为每分钟的话,15次检测错误会开始激活Swap IP操作。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
<?php echo "====================Auto Swap IP For DigitalOcean===================="; echo "\n"; echo 'Time: '.date("Y-m-d H:i:s"); echo "\n"; function callAPI($method, $url, $data, $auth){ $curl = curl_init(); switch ($method){ case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "DELETE": curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); } // OPTIONS: curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, $auth); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // EXECUTE: $result = curl_exec($curl); if(!$result){ $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); return $httpcode; } curl_close($curl); return $result; } // load process step function output_json($name, $value, $server_name){ $load_json = load_json($server_name); $load_json["$name"] = $value; $outputJSON = json_encode($load_json); $fp = fopen('data_auto_swap_ip_digitalocean_'.$server_name.'.json', 'w') or die("Unable to open file!"); fwrite($fp, $outputJSON); fclose($fp); } function load_json($server_name){ if(file_exists('data_auto_swap_ip_digitalocean_'.$server_name.'.json')){ $load_json = file_get_contents('data_auto_swap_ip_digitalocean_'.$server_name.'.json'); }else{ $load_json = '{"step":10}'; echo 'Json file not exists, will reset to default: '.$load_json; echo "\n"; } return json_decode($load_json, true); } // set input value if( isset($argv[1])) { $server_name = $argv[1]; echo "server_name: ".$set_domain; echo "\n"; }else{ $server_name = null; echo "server_name Not Set!"."\n"; echo "\n"; die(); } echo 'Get Last Process Status...'; echo "\n"; $last_status = load_json($server_name); echo 'Last process status: '.$last_status['step']; echo "\n"; $digitalocean_api_auth = array( 'Content-Type: application/json', 'Authorization: Bearer $api_key', ); $cloudflare_api_auth = array( 'X-Auth-Email: $account_email', 'X-Auth-Key: $api_key', 'Content-Type: application/json', ); switch ($last_status['step']) { case 0: echo 'Unassign Floating IP...'; echo "\n"; $get_data = callAPI('GET', 'https://api.digitalocean.com/v2/floating_ips', false, $digitalocean_api_auth); $response = json_decode($get_data, true); foreach ($response['floating_ips'] as $value) { if($value['droplet']['name'] == $server_name){ $floating_ip = $value['ip']; $droplet_id = $value['droplet']['id']; } } if(!isset($floating_ip)){ echo 'server has no defined floating ips, will assign a new floating ip'; echo "\n"; output_json('step', 1, $server_name); die(); } echo 'floating_ip is: '.$floating_ip; echo "\n"; echo 'droplet_id is: '.$droplet_id; echo "\n"; echo 'folating ip exists, will Unassign Floating IP...'; echo "\n"; $data_json = json_encode(array( "type" => "unassign" )); $get_data = callAPI('POST', 'https://api.digitalocean.com/v2/floating_ips/'.$floating_ip.'/actions', $data_json, $digitalocean_api_auth); echo 'unassign floating ip success, will assign a new floating ip'; echo "\n"; output_json('step', 1, $server_name); break; case 1: echo 'Assign Floating IP to Droplet...'; echo "\n"; echo 'Get Server ID...'; echo "\n"; $get_data = callAPI('GET', 'https://api.digitalocean.com/v2/droplets', false, $digitalocean_api_auth); $response = json_decode($get_data, true); foreach ($response['droplets'] as $value) { if($value['name'] == $server_name){ $droplet_id = $value['id']; } } if(!isset($droplet_id)){ echo 'use name '.$server_name.' get nothing'; echo "\n"; die(); } echo 'droplet_id is: '.$droplet_id; echo "\n"; echo 'Assign a Floating IP to '.$droplet_id; echo "\n"; $data_json = json_encode(array( "droplet_id" => $droplet_id, )); $get_data = callAPI('POST', 'https://api.digitalocean.com/v2/floating_ips', $data_json, $digitalocean_api_auth); echo 'Next Step --> Update Floating IP to Cloudflare'; echo "\n"; output_json('step', 2, $server_name); break; case 2: echo 'Update Floating IP to Cloudflare...'; echo "\n"; echo 'Get Floating IP...'; echo "\n"; $get_data = callAPI('GET', 'https://api.digitalocean.com/v2/floating_ips', false, $digitalocean_api_auth); $response = json_decode($get_data, true); foreach ($response['floating_ips'] as $value) { if($value['droplet']['name'] == $server_name){ $floating_ip = $value['ip']; $droplet_id = $value['droplet']['id']; } } if(!isset($floating_ip)){ echo 'server has no defined floating ips, need assign a new floating ip'; echo "\n"; die(); } echo 'floating_ip is: '.$floating_ip; echo "\n"; echo 'droplet_id is: '.$droplet_id; echo "\n"; $get_data = callAPI('GET', 'https://api.cloudflare.com/client/v4/zones?name=minirplus.com', false, $cloudflare_api_auth); $response = json_decode($get_data, true); $zone_id = $response['result'][0]['id']; echo 'zone_id is: '.$zone_id; echo "\n"; $target_domain = $server_name; $get_data = callAPI('GET', 'https://api.cloudflare.com/client/v4/zones/'.$zone_id.'/dns_records?type=A&name='.$target_domain, false, $cloudflare_api_auth); $response = json_decode($get_data, true); $dns_records_id = $response['result'][0]['id']; $old_ip = $response['result'][0]['content']; echo 'DNS Record on cloudflare is: '.$old_ip; echo "\n"; $local_ip = $floating_ip; if($local_ip == $old_ip){ $new_ip = $old_ip; echo "the newest ip address $local_ip is same as the cloudflare record $old_ip, will do nothing"; echo "\n"; } else{ $new_ip = $local_ip; echo "the newest ip address $local_ip is different as the cloudflare record $old_ip, will update the record to newest"; echo "\n"; // update ip address $data_array = array( "type" => "A", "name" => $target_domain, "content" => $new_ip, "ttl" => 120, "proxied" => false ); $put_data = callAPI('PUT', 'https://api.cloudflare.com/client/v4/zones/'.$zone_id.'/dns_records/'.$dns_records_id, json_encode($data_array), $cloudflare_api_auth); $response = json_decode($put_data, true); } break; case 3: echo 'Delete Unassigned Floating IPs...'; echo "\n"; echo 'Get Unassigned Floating IPs...'; echo "\n"; $get_data = callAPI('GET', 'https://api.digitalocean.com/v2/floating_ips', false, $digitalocean_api_auth); $response = json_decode($get_data, true); foreach ($response['floating_ips'] as $value) { if($value['droplet'] == NULL){ $floating_ip = $value['ip']; } } if(!isset($floating_ip)){ echo 'no unassigned floating ips'; echo "\n"; output_json('step',4, $server_name); die(); } echo 'unassigned floating_ip is: '.$floating_ip; echo "\n"; echo 'Delete '.$floating_ip.'...'; echo "\n"; $get_data = callAPI('DELETE', 'https://api.digitalocean.com/v2/floating_ips/'.$floating_ip, false, $digitalocean_api_auth); output_json('step',4, $server_name); break; default: echo 'Testing server tcp status...'; echo "\n"; $max_tcp_test_time = 15; $cmd_wget = "wget -q -O - https://ziyuan.baidu.com/robots/doanalysis?site=sjo.minirplus.com"; exec($cmd_wget,$array); $wget_result = json_decode($array[0],true); $tcp_test = $wget_result['status']; if($tcp_test == 9){ echo "tcp test result is $tcp_test, block by chinafirewall, will test again"; echo "\n"; echo "current test time is ".(0-$last_status['step']).", max test time is $max_tcp_test_time"; echo "\n"; if($last_status['step'] > 0){ output_json('step', -1, $server_name); }else{ output_json('step', $last_status['step']-1, $server_name); } if($last_status['step'] <= -($max_tcp_test_time)){ echo "tcp test Reached the max test time: $max_tcp_test_time, will start swap ip process..."; echo "\n"; output_json('step', 0, $server_name); } }else{ echo "tcp test result is $tcp_test, server is running fine"; echo "\n"; output_json('step', 200, $server_name); } } die(); |
2 comments