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

时间:2018-08-12 23:59:08

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

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

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

$ 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的单行命令吗?您可以假定该命令将从与Security组位于同一VPC的EC2中运行。

3 个答案:

答案 0 :(得分:1)

来自API文档:

-组名(列表)

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

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

aws ec2 describe-security-groups --filter Name=vpc-id,Values=<my-vpc-id> Name=group-name,Values=<group-name>

答案 1 :(得分:0)

您只需要在aws cli命令中添加--query 'SecurityGroups[*].[GroupName]'选项。

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

答案 2 :(得分:0)

如果它在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