gpt4 book ai didi

python - 调用时出现 digitalocean 脚本错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:29:09 26 4
gpt4 key购买 nike

我在 centos 上使用 digitalocean 脚本,但它似乎不起作用。 https://www.digitalocean.com/community/tutorials/how-to-set-up-highly-available-haproxy-servers-with-keepalived-and-floating-ips-on-ubuntu-14-04

Traceback (most recent call last):
File "/usr/local/bin/assign-ip", line 33, in <module>
usage()
File "/usr/local/bin/assign-ip", line 12, in usage
print('{} [Floating IP] [Droplet ID]'.format(sys.argv[0]))
ValueError: zero length field name in format

这里是要调用的sh脚本

` export DO_TOKEN='xxxxxxxxxxx'
IP='xxx.xxx.xxx.xxx'
ID=$(curl -s 169.254.169.254/metadata/v1/id)
HAS_FLOATING_IP=$(curl -s http://169.254.169.254/metadata/v1/floating_ip/ipv4/active)

if [ $HAS_FLOATING_IP = "false" ]; then
n=0
while [ $n -lt 10 ]
do
python /usr/local/bin/assign-ip $IP $ID && break
n=$((n+1))
sleep 3
done
fi`

这是分配IP的脚本

`#!/usr/bin/python

import os
import sys
import requests
import json

api_base = 'https://api.digitalocean.com/v2'


def usage():
print('{} [Floating IP] [Droplet ID]'.format(sys.argv[0]))
print('\nYour DigitialOcean API token must be in the "DO_TOKEN"'
' environmental variable.')


def main(floating_ip, droplet_id):
payload = {'type': 'assign', 'droplet_id': droplet_id}
headers = {'Authorization': 'Bearer {}'.format(os.environ['DO_TOKEN']),
'Content-type': 'application/json'}
url = api_base + "/floating_ips/{}/actions".format(floating_ip)
r = requests.post(url, headers=headers, data=json.dumps(payload))

resp = r.json()
if 'message' in resp:
print('{0}: {1}'.format(resp['id'], resp['message']))
sys.exit(1)
else:
print('Moving IP address: {}'.format(resp['action']['status']))

if __name__ == "__main__":
if 'DO_TOKEN' not in os.environ or not len(sys.argv) > 2:
usage()
sys.exit()
main(sys.argv[1], sys.argv[2])
`

最佳答案

刚刚偶然发现了这个。我实际上写了the Python script多于。它所链接的教程针对的是 Ubuntu 14.04。您看到的错误是由于 CentOS 6 附带 Python 2.6 而脚本使用了仅适用于 Python 2.7 的功能。 gist containing it已更新为与 Python 2.6 和 CentOS 6 兼容。

具体来说,错误是由于在字符串格式中省略了位置参数。例如:

print('{} [Floating IP] [Droplet ID]'.format(sys.argv[0]))

在 Python < 2.6 中,这需要明确。例如:

print('{0} [Floating IP] [Droplet ID]'.format(sys.argv[0]))

From the docs :

Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.

关于python - 调用时出现 digitalocean 脚本错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33417462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com