代码之家  ›  专栏  ›  技术社区  ›  Saqib Ali

如果我知道AWS安全组的名称,如何获取其ID?

  •  0
  • Saqib Ali  · 技术社区  · 7 年前

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

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

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

    当我浏览这些信息时,我看到相关的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中运行。

    2 回复  |  直到 7 年前
        1
  •  8
  •   victor m    5 年前

    从API文档中:

    --组名(列表)

    [EC2 Classic and default VPC only]一个或多个安全组名称。您可以指定安全组名称或安全组ID。对于非默认VPC中的安全组,请使用组名称筛选器按名称描述安全组。

    如果您使用的是非默认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
  •  2
  •   Vishnu Nair    6 年前

    如果它位于专有网络中,并且您知道它的名称&地区和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
  •  1
  •   GroovyDotCom Deepak Reddy    6 年前

    你只需要添加 --query 'SecurityGroups[*].[GroupId]' 带有aws cli命令的选项。

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