【问题标题】:How can I get the the ID of an AWS security group if I know the name?如果我知道名称,如何获取 AWS 安全组的 ID?
【发布时间】:2019-01-19 16:19:17
【问题描述】:

我正在使用 AWS CLI,我想获取我知道其名称的安全组的 ID (kingkajou_sg)。我该怎么做?

当我要求它列出所有安全组时,它很高兴:

$ aws ec2 describe-security-groups | wc -l
     430

当我 grep 浏览此信息时,我看到有问题的 SG 已列出:

$ aws ec2 describe-security-groups | grep -i kingkajou_sg
            "GroupName": "kingkajou_sg",

但是,当我尝试仅获取有关该安全组的信息时,它不会让我这样做。为什么?

$ aws ec2 describe-security-groups --group-names kingkajou_sg

An error occurred (InvalidGroup.NotFound) when calling the 
DescribeSecurityGroups operation: The security group 'kingkajou_sg' does not exist in default VPC 'vpc-XXXXXXXX'

有人可以提供我可以用来提取安全组 ID 的单行命令吗?您可以假设该命令将从与安全组位于同一 VPC 的 EC2 中运行。

【问题讨论】:

    标签: amazon-ec2 aws-cli aws-security-group


    【解决方案1】:

    来自 API 文档:

    --组名(列表)

    [仅限 EC2-Classic 和默认 VPC] 一个或多个安全组名称。您可以指定安全组名称或安全组 ID。对于非默认 VPC 中的安全组,请使用 group-name 过滤器按名称描述安全组。

    如果您使用的是非默认 VPC,请使用过滤器

    aws ec2 describe-security-groups --filter Name=vpc-id,Values=<my-vpc-id> Name=group-name,Values=kingkajou_sg --query 'SecurityGroups[*].[GroupId]' --output text
    

    【讨论】:

      【解决方案2】:

      如果它在 VPC 中并且您知道名称和区域以及 vpc id,您可以尝试如下:

      aws ec2 describe-security-groups --region eu-west-1 --filter Name=vpc-id,Values=vpc-xxxxx Name=group-name,Values=<your sg name> --query 'SecurityGroups[*].[GroupId]' --output text
      

      【讨论】:

        【解决方案3】:

        您只需要使用 aws cli 命令添加 --query 'SecurityGroups[*].[GroupId]' 选项。

        aws ec2 describe-security-groups --group-names kingkajou_sg --query 'SecurityGroups[*].[GroupId]' --output text
        

        【讨论】:

        • 这仅在默认 VPC 中创建安全组时有效。
        猜你喜欢
        • 2022-01-17
        • 2011-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-22
        • 1970-01-01
        • 2023-03-29
        相关资源
        最近更新 更多