我需要创建一个从Google Cloud Platform删除实例组的脚本。此组可以位于任何区域中。当我运行命令时:
gcloud compute instance-groups managed delete [instance-group-name](没有区域或区域)系统会提示我选择一个区域或区域。对这样的脚本有什么帮助吗?
发布于 2018-02-26 17:27:41
放置--zone标志并在命令中指定它显然会阻止提示输入区域。但是,如果每个实例组的区域不同,并且您希望自动执行此过程,则可以向脚本中添加一些命令来列出您的实例组(输出将包括区域),然后过滤输出以创建包含区域信息的变量。然后可以在gcloud compute instance-groups managed delete命令中使用此变量。
例如,要隔离要删除的实例组的区域,可以尝试执行以下操作。
gcloud compute instance-groups list | grep INSTANCE_GROUP_NAME | awk '{print $2;}'上面的命令首先使用grep过滤一行信息,其中包含您想要删除的实例组的详细信息,因此在应用awk之前,该信息如下所示:
test-instance-group us-west1-c zone default Yes 1awk '{print $2;}'筛选器打印出第二个非空格子字符串,它将是区域,因此将输出以下内容:
us-west1-c因此,就脚本而言,在执行删除实例组的命令之前,需要为该实例组区域设置一个变量。总而言之,下面是您的脚本可能的样子:
#!/bin/bash
### retrieve the zone information of the instance group and store it in a variable.
zonevar="$(gcloud compute instance-groups list | grep INSTANCE_GROUP_NAME | awk '{print $2;}')"
### use the variable in the gcloud command to delete the instance group.
gcloud compute instance-groups managed delete INSTANCE_GROUP_NAME --zone=$zonevar如果您想要应用区域信息而不是区域信息,则可以应用相同的逻辑。
发布于 2018-02-26 23:14:54
您可以利用--format来泛化脚本并避免切片和骰子管道。特定于命令行的格式还可在将来针对不属于CLI合同一部分的表格格式更改进行验证。此脚本还处理区域/区域位置。
#!/bin/bash
typeset -A locationsof
function getlocations {
set -- $(gcloud compute instance-groups list \
--format="value(name,location(),location_scope())")
while (( $# >= 3 ))
do
locationsof[$1]+=" --$3=$2"
shift 3
done
}
getlocations
for name
do
if [[ $name == -n || $name == --show ]]; then
show=echo
continue
fi
locations=${locationsof[$name]}
if [[ ! $locations ]]; then
echo "$name: unknown instance group" >&2
continue
fi
for location in $locations
do
$show gcloud compute instance-groups managed delete $name $location
done
done使用-n或测试脚本--在真正删除任何内容之前显示。使用--verbosity=info运行任意list命令以查看默认输出格式。这就是格式的咒语的由来。
https://stackoverflow.com/questions/48975408
复制相似问题