与 AWS SDK或DescribeVpcs一起使用 CLI - Amazon Elastic Compute Cloud

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或DescribeVpcs一起使用 CLI

以下代码示例演示如何使用 DescribeVpcs

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/// <summary> /// Get the default VPC for the account. /// </summary> /// <returns>The default VPC object.</returns> public async Task<Vpc> GetDefaultVpc() { try { var vpcResponse = await _amazonEc2.DescribeVpcsAsync( new DescribeVpcsRequest() { Filters = new List<Amazon.EC2.Model.Filter>() { new("is-default", new List<string>() { "true" }) } }); return vpcResponse.Vpcs[0]; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "UnauthorizedOperation") { _logger.LogError(ec2Exception, $"You do not have the necessary permissions to describe VPCs."); } throw; } catch (Exception ex) { _logger.LogError(ex, $"An error occurred while describing the vpcs.: {ex.Message}"); throw; } }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 DescribeVpcs” 中的。

CLI
AWS CLI

示例 1:描述您的所有内容 VPCs

以下describe-vpcs示例检索有关您的VPCs详细信息。

aws ec2 describe-vpcs

输出:

{ "Vpcs": [ { "CidrBlock": "30.1.0.0/16", "DhcpOptionsId": "dopt-19edf471", "State": "available", "VpcId": "vpc-0e9801d129EXAMPLE", "OwnerId": "111122223333", "InstanceTenancy": "default", "CidrBlockAssociationSet": [ { "AssociationId": "vpc-cidr-assoc-062c64cfafEXAMPLE", "CidrBlock": "30.1.0.0/16", "CidrBlockState": { "State": "associated" } } ], "IsDefault": false, "Tags": [ { "Key": "Name", "Value": "Not Shared" } ] }, { "CidrBlock": "10.0.0.0/16", "DhcpOptionsId": "dopt-19edf471", "State": "available", "VpcId": "vpc-06e4ab6c6cEXAMPLE", "OwnerId": "222222222222", "InstanceTenancy": "default", "CidrBlockAssociationSet": [ { "AssociationId": "vpc-cidr-assoc-00b17b4eddEXAMPLE", "CidrBlock": "10.0.0.0/16", "CidrBlockState": { "State": "associated" } } ], "IsDefault": false, "Tags": [ { "Key": "Name", "Value": "Shared VPC" } ] } ] }

示例 2:描述指定的 VPC

以下describe-vpcs示例检索指定VPC项的详细信息。

aws ec2 describe-vpcs \ --vpc-ids vpc-06e4ab6c6cEXAMPLE

输出:

{ "Vpcs": [ { "CidrBlock": "10.0.0.0/16", "DhcpOptionsId": "dopt-19edf471", "State": "available", "VpcId": "vpc-06e4ab6c6cEXAMPLE", "OwnerId": "111122223333", "InstanceTenancy": "default", "CidrBlockAssociationSet": [ { "AssociationId": "vpc-cidr-assoc-00b17b4eddEXAMPLE", "CidrBlock": "10.0.0.0/16", "CidrBlockState": { "State": "associated" } } ], "IsDefault": false, "Tags": [ { "Key": "Name", "Value": "Shared VPC" } ] } ] }
JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

const client = new EC2Client({}); const { Vpcs } = await client.send( new DescribeVpcsCommand({ Filters: [{ Name: "is-default", Values: ["true"] }], }), );
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 DescribeVpcs” 中的。

PowerShell
用于 PowerShell

示例 1:此示例描述了指定的VPC。

Get-EC2Vpc -VpcId vpc-12345678

输出:

CidrBlock : 10.0.0.0/16 DhcpOptionsId : dopt-1a2b3c4d InstanceTenancy : default IsDefault : False State : available Tags : {Name} VpcId : vpc-12345678

示例 2:此示例描述了默认值VPC(每个区域只能有一个)。如果您的账户在此区域支持 EC2-Classic,则没有默认设置VPC。

Get-EC2Vpc -Filter @{Name="isDefault"; Values="true"}

输出:

CidrBlock : 172.31.0.0/16 DhcpOptionsId : dopt-12345678 InstanceTenancy : default IsDefault : True State : available Tags : {} VpcId : vpc-45678901

示例 3:此示例描述了VPCs与指定筛选器匹配的(即,具有CIDR与值 “10.0.0.0/16” 匹配且处于 “可用” 状态的)。

Get-EC2Vpc -Filter @{Name="cidr"; Values="10.0.0.0/16"},@{Name="state";Values="available"}

示例 4: 此示例描述了您的所有内容VPCs.

Get-EC2Vpc
  • 有关API详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考DescribeVpcs中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

class AutoScalingWrapper: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix: str, inst_type: str, ami_param: str, autoscaling_client: boto3.client, ec2_client: boto3.client, ssm_client: boto3.client, iam_client: boto3.client, ): """ Initializes the AutoScaler class with the necessary parameters. :param resource_prefix: The prefix for naming AWS resources that are created by this class. :param inst_type: The type of EC2 instance to create, such as t3.micro. :param ami_param: The Systems Manager parameter used to look up the AMI that is created. :param autoscaling_client: A Boto3 EC2 Auto Scaling client. :param ec2_client: A Boto3 EC2 client. :param ssm_client: A Boto3 Systems Manager client. :param iam_client: A Boto3 IAM client. """ self.inst_type = inst_type self.ami_param = ami_param self.autoscaling_client = autoscaling_client self.ec2_client = ec2_client self.ssm_client = ssm_client self.iam_client = iam_client sts_client = boto3.client("sts") self.account_id = sts_client.get_caller_identity()["Account"] self.key_pair_name = f"{resource_prefix}-key-pair" self.launch_template_name = f"{resource_prefix}-template-" self.group_name = f"{resource_prefix}-group" # Happy path self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" # Failure mode self.bad_creds_policy_name = f"{resource_prefix}-bc-pol" self.bad_creds_role_name = f"{resource_prefix}-bc-role" self.bad_creds_profile_name = f"{resource_prefix}-bc-prof" def get_default_vpc(self) -> Dict[str, Any]: """ Gets the default VPC for the account. :return: Data about the default VPC. """ try: response = self.ec2_client.describe_vpcs( Filters=[{"Name": "is-default", "Values": ["true"]}] ) except ClientError as err: error_code = err.response["Error"]["Code"] log.error("Failed to retrieve the default VPC.") if error_code == "UnauthorizedOperation": log.error( "You do not have the necessary permissions to describe VPCs. " "Ensure that your AWS IAM user or role has the correct permissions." ) elif error_code == "InvalidParameterValue": log.error( "One or more parameters are invalid. Check the request parameters." ) log.error(f"Full error:\n\t{err}") else: if "Vpcs" in response and response["Vpcs"]: log.info(f"Retrieved default VPC: {response['Vpcs'][0]['VpcId']}") return response["Vpcs"][0] else: pass
  • 有关API详细信息,请参阅DescribeVpcs中的 AWS SDKPython (Boto3) API 参考。

有关 AWS SDK开发者指南和代码示例的完整列表,请参阅使用创建 Amazon EC2 资源 AWS SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。