EC2のセキュリティグループの詳細を取得したいときはaws ec2 describe-security-groupsコマンドを利用します。
--group-namesでセキュリティグループ名を指定して取得できると思いきや、名前では参照できないとエラーが出てしまいます。
$ aws ec2 describe-security-groups --group-names {sg-name} --region ap-northeast-1
An error occurred (InvalidParameterValue) when calling the DescribeSecurityGroups operation: Invalid value '{sg-name}' for groupName. You may not reference Amazon VPC security groups by name. Please use the corresponding id for this operation.
https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html
そこで、EC2にSSHしてから、セキュリティグループの詳細を取得したいときは、以下の工程を踏む必要があります。(もっといい方法もあるかもしれません)
インスタンスIDを取得
↓
そのインスタンスに紐付いているセキュリティグループIDを取得する
↓
セキュリティグループIDで詳細を取得する
上記の言葉をcliでワンライナーにすると下記になります。 注意点としては、EC2ReadOnlyの権限が必要なので、インスタンスのIAMロールとかに入れておきましょう
$ instanceId=$(curl -s http://169.254.169.254/latest/meta-data/instance-id);SecurityGroupId=$(aws ec2 describe-instances --instance-ids ${instanceId} --query Reservations[].Instances[].SecurityGroups[].GroupId --output text --region ap-northeast-1);aws ec2 describe-security-groups --group-ids ${SecurityGroupId} --region ap-northeast-1
{
"SecurityGroups": [
{
"IpPermissionsEgress": [
{
"IpProtocol": "-1",
"PrefixListIds": [],
"IpRanges": [
{
"CidrIp": "0.0.0.0/0"
}
],
"UserIdGroupPairs": [],
"Ipv6Ranges": []
}
],
"Description": "allow-town",
"IpPermissions": [
{
"PrefixListIds": [],
"FromPort": 80,
"IpRanges": [],
"ToPort": 80,
"IpProtocol": "tcp",
"UserIdGroupPairs": [
{
"UserId": "xxxx",
"GroupId": "sg-xxxxxx"
}
],
"Ipv6Ranges": []
},
{
"IpProtocol": "-1",
"PrefixListIds": [],
"IpRanges": [
{
"Description": "xxx",
"CidrIp": "xxx.xxx.xxx.xxx/32"
},
{
"Description": "xxx",
"CidrIp": "xxx.xxx.xxx.xxx/32"
},
{
"Description": "xxxx",
"CidrIp": "xxx.xxx.xxx.xxx/32"
}
],
"UserIdGroupPairs": [],
"Ipv6Ranges": []
}
],
"GroupName": "xxxxx",
"VpcId": "vpc-xxxx",
"OwnerId": "xxxx",
"GroupId": "sg-xxxxx"
}
]
}


