DescribeVpcs 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

DescribeVpcs 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 DescribeVpcs

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on 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 詳細資訊,請參閱 DescribeVpcs AWS SDK for .NET 參考中的 API

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" } ] } ] }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 DescribeVpcs

JavaScript
SDK for JavaScript (v3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

const client = new EC2Client({}); const { Vpcs } = await client.send( new DescribeVpcsCommand({ Filters: [{ Name: "is-default", Values: ["true"] }], }), );
  • 如需 API 詳細資訊,請參閱 DescribeVpcs AWS SDK for JavaScript 參考中的 API

PowerShell
for 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 (即具有符合值 '10.0.0.0/16' 且處於 'available' 狀態的 CIDR)。

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
Python 的 SDK (Boto3)
注意

還有更多 on 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 SDK for Python (Boto3) Word 參考中的 API