我在制作带附加磁盘的vm图像时遇到问题。我使用此处描述的捕获方法https://softlayer-python.readthedocs.io/en/v3.3.0/api/managers/cci.html。虽然我将additional_disks设置为False,但我的图像也包含可附加设备。它会影响所有设备。有谁知道什么是错的?提前谢谢。
我的脚本如下所示:
import SoftLayer
import argparse
import sys
import datetime
def initialize_sl_connection():
with open('/etc/default/sl_snapshots', 'r') as f:
for line in f:
if 'SL_USERNAME' in line:
SL_USERNAME = line.rstrip().split('=')[1]
if 'SL_API_KEY' in line:
SL_API_KEY = line.rstrip().split('=')[1]
client = SoftLayer.Client(username = SL_USERNAME, api_key = SL_API_KEY)
mgr_vs = SoftLayer.VSManager(client)
mgr_image = SoftLayer.ImageManager(client)
return (mgr_vs, mgr_image)
def get_instance_id_by_hostname_and_datacenter(mgr_vs, hostname, datacenter):
instance = (mgr_vs.list_instances(hostname = hostname, datacenter = datacenter)[0:]+[{}])[0]
return instance['id'] if instance.has_key('id') else None
def capture_sl_snapshot(mgr_vs, hostname, additionaldisks, instance_id):
name = hostname + '_' + str(datetime.date.today()).replace('-','_')
mgr_vs.capture(instance_id = instance_id, name = name, additional_disks = additionaldisks, notes = None)
def clean_old_sl_snapshots(mgr_image, hostname):
image_list = mgr_image.list_private_images(name = hostname+'*')
number_of_snapshots = len(image_list)
if number_of_snapshots > 4:
for i in range(0, number_of_snapshots-4):
mgr_image.delete_image(image_list[i]['id'])
def main():
parser = argparse.ArgumentParser(
description='Automate creating SL snapshots with Ansible.')
parser.add_argument(
'--hostname',
dest='hostname',
help='Servers hostname.',
required=True)
parser.add_argument(
'--datacenter',
dest='datacenter',
help='Datacenters name.',
required=True)
parser.add_argument(
'--additionaldisks',
dest='additionaldisks',
help='Create snapshot for any additional disk attached to the machine.',
required=True)
args = parser.parse_args()
mgr_vs = initialize_sl_connection()[0]
mgr_image = initialize_sl_connection()[1]
instance_id = get_instance_id_by_hostname_and_datacenter(mgr_vs, args.hostname, args.datacenter)
if instance_id:
capture_sl_snapshot(mgr_vs, args.hostname, args.additionaldisks, instance_id)
clean_old_sl_snapshots(mgr_image, args.hostname)
if __name__ == "__main__":
main()
我的电话如下:
/usr/bin/python /opt/scripts/sl_take_snapshot.py --hostname my_servers_hostname --datacenter lon02 --additionaldisks False
/ etc / defaults / sl_snapshots文件具有以下结构:
root@ip-10-0-3-84:~# cat /etc/default/sl_snapshots
SL_USERNAME=my_username
SL_API_KEY=my_key
提前感谢您提供的任何帮助。
答案 0 :(得分:1)
问题似乎是你如何解析你的价值观:
parser.add_argument(
'--additionaldisks',
dest='additionaldisks',
help='Create snapshot for any additional disk attached to the machine.',
required=True)
目前您正在解析的值是一个字符串而不是booelan,所以你得到的是这样的:
additionaldisks ='False'
对于python,空字符串的计算结果为False,但其他所有字符串的计算结果为True。这就是你编码的原因是捕获所有磁盘。
如果您不想捕获所有需要从呼叫中删除“--additionaldisks False”的磁盘。如果您想将其保留在通话中,则需要更改解析代码,请参阅此处以获取更多信息Parsing boolean values with argparse
此致