gpt4 book ai didi

c# - 使用 C# 获取 ec2-instance 标签

转载 作者:行者123 更新时间:2023-11-30 16:58:51 26 4
gpt4 key购买 nike

我不是开发人员,所以也许有不同解决方案的答案,但我无法真正从 python 或其他语言中翻译它。

我正在尝试使用 AWS .NET SDK 查找实例,然后获取实例的标签。我已经能够确定实例是否已启动并正在运行。我还看到了如何创建和删除标签(不在下面的代码示例中)。但我没有看到一种简单的方法来实际检查标签是否存在并获取标签的值(如果存在)。

抱歉,如果我遗漏了显而易见的内容,但这对我来说是全新的。这是我用来检查实例是否正在运行的代码示例。

            instanceID = "i-myInstanceID";
do {
var myrequest = new DescribeInstanceStatusRequest();
DescribeInstanceStatusResponse myresponse = ec2.DescribeInstanceStatus(myrequest);
int isCount = myresponse.DescribeInstanceStatusResult.InstanceStatuses.Count;
for (int isc=0; isc < isCount; isc++) {
InstanceStatus instanceStatus = myresponse.DescribeInstanceStatusResult.InstanceStatuses[isc];
if (instanceStatus.InstanceId.Contains(instanceID)) {
Console.WriteLine("It looks like instance "+instanceID+" is running.");
idIdx = isc;
foundID = true;
break;
}
}
if ((foundID==false) && (secondCounter==1)) {
Console.Write("Looking for instance "+instanceID);
} else {
Console.Write(".");
}
Thread.Sleep(1000);
secondCounter++;
if (secondCounter > 5) {
break;
}
} while (foundID == false) ;

最佳答案

首先发送DescribeInstancesRequest获取实例列表:

    public DescribeInstancesResult GetInstances(Ec2Key ec2Key)
{
_logger.Debug("GetInstances Start.");

AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);

var ec2Request = new DescribeInstancesRequest();

DescribeInstancesResponse describeInstancesResponse = ec2.DescribeInstances(ec2Request);

DescribeInstancesResult result = describeInstancesResponse.DescribeInstancesResult;

_logger.Debug("GetInstances End.");

return result;
}

然后循环遍历实例,直到找到你想要的那个,然后使用 Tag.GetTagValueByKey 方法:

        // This just calls the above code
DescribeInstancesResult ec2Instances = _ec2ResourceAccess.GetInstances(ec2Key);

var returnInstances = new List<Ec2UtilityInstance>();
foreach (var reservation in ec2Instances.Reservation)
{
foreach (var runningInstance in reservation.RunningInstance)
{
var returnInstance = new Ec2UtilityInstance();

returnInstance.InstanceId = runningInstance.InstanceId;
returnInstance.InstanceName = runningInstance.Tag.GetTagValueByKey("Name");
returnInstance.Status = (Ec2UtilityInstanceStatus)Enum.Parse(typeof(Ec2UtilityInstanceStatus), runningInstance.InstanceState.Name, true);
returnInstance.DefaultIp = runningInstance.Tag.GetTagValueByKey("DefaultIp");
returnInstance.InstanceType = runningInstance.InstanceType;
returnInstance.ImageId = runningInstance.ImageId;

returnInstances.Add(returnInstance);
}
}

这是从以下位置获取的完整源代码的链接:

https://github.com/escherrer/EC2Utilities

通用\管理器

公共(public)\资源访问

关于c# - 使用 C# 获取 ec2-instance 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24663104/

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