如何通过PowerShell获取CloudFormation栈EC2实例IP?已试命令未返回
Got it, let's break down why your current command isn't returning the IP address and how to fix it quickly.
Why Get-CFNStackResourceList doesn't show IPs
The Get-CFNStackResourceList cmdlet only returns basic metadata about CloudFormation resources—like logical ID, physical ID, and resource type. It doesn't fetch detailed properties from the underlying service (in this case, EC2), which is why you're missing the IP addresses.
Step-by-Step Solution
You'll need to first grab the EC2 instance's physical ID (aka Instance ID) from CloudFormation, then use EC2-specific cmdlets to pull the IPs.
1. Get the EC2 Instance ID from your CloudFormation stack
Run this to retrieve the physical resource ID of your EC2 instance:
$ec2Resource = Get-CFNStackResourceList -StackName 'teststack' -LogicalResourceId 'EC2Instance' -Region 'eu-west-1' $instanceId = $ec2Resource.PhysicalResourceId
2. Fetch the IP addresses using the Instance ID
Now use Get-EC2Instance to get the instance's details, including private and public IPs:
$instance = Get-EC2Instance -InstanceId $instanceId -Region 'eu-west-1' | Select-Object -ExpandProperty Instances # Access the IPs Write-Host "Private IP: $($instance.PrivateIpAddress)" Write-Host "Public IP: $($instance.PublicIpAddress)"
3. One-Liner for Efficiency
If you want to combine both steps into a single command (great for quick checks):
Get-CFNStackResourceList -StackName 'teststack' -LogicalResourceId 'EC2Instance' -Region 'eu-west-1' | ForEach-Object { Get-EC2Instance -InstanceId $_.PhysicalResourceId -Region 'eu-west-1' | Select-Object -ExpandProperty Instances | Select-Object InstanceId, PrivateIpAddress, PublicIpAddress }
Important Notes
- If your EC2 instance is in a private subnet without an Elastic IP, the
PublicIpAddressfield will be empty—this is expected. - Make sure your IAM permissions include both
cloudformation:DescribeStackResources(for the CloudFormation cmdlet) andec2:DescribeInstances(for the EC2 cmdlet).
内容的提问来源于stack exchange,提问作者srinivasb

