求可获取公网IP、VPC、实例状态及名称的AWS CLI审计命令
Got it, let's get this sorted for your audit work—here's exactly what you need, broken down step by step:
Final Working Command
aws ec2 describe-instances \ --filter "Name=instance-state-name,Values=running" \ --query "Reservations[*].Instances[*].[PublicIpAddress, VpcId, State.Name, Tags[?Key=='Name'].Value|[0]]" \ --output=text
Let's Break This Down:
Adding the
--filterfor Running Instances
The--filterflag uses the formatName=FIELD_NAME,Values=TARGET_VALUE. For instance state, the field isinstance-state-name, and we want the valuerunning. You can place this flag right afterdescribe-instances(the order of flags like--filterand--querydoesn't matter much, but this is the most intuitive placement).Expanding the
--queryto Include Your Required Fields
We updated the query to pull 4 key pieces of info for your audit:PublicIpAddress: Your original public IP fieldVpcId: The ID of the VPC the instance belongs toState.Name: The instance state (we already filtered for running, but including this makes the audit output explicit)Tags[?Key=='Name'].Value|[0]: Extracts the instance's "Name" tag. The|[0]ensures we get a single value instead of an array (even if the instance has no Name tag, it'll return an empty string instead of a blank array).
Output Format
Keeping--output=textensures the results are space-separated, which is easy to parse into spreadsheets or audit tools. If you prefer a more human-readable format for quick checks, swap it with--output=table.
Bonus Tip: Handling Instances Without Public IPs
If you want to exclude instances that don't have a public IP (common in private subnets), tweak the query to filter those out:
aws ec2 describe-instances \ --filter "Name=instance-state-name,Values=running" \ --query "Reservations[*].Instances[?PublicIpAddress != null].[PublicIpAddress, VpcId, State.Name, Tags[?Key=='Name'].Value|[0]]" \ --output=text
内容的提问来源于stack exchange,提问作者Craigus

