I have a lot of instances running an an AWS Account. Each is attached to a different IAM Role (1). I can review the Role via the Management Console (2) and see the attached Policies (3).
I want to obtain a list of these programmatically. I have written some powershell.
$region = 'eu-west-3'
Set-DefaultAWSRegion -Region $region
$ec2 = Get-EC2Instance
$ec2list = $ec2.Instances
$ec2listdetails = $ec2list | ForEach-Object {
$properties = [ordered]@{
Name = ($_ | Select-Object -ExpandProperty tags | Where-Object -Property Key -eq Name).value
InstanceState = $_.State.Name
InstanceID = $_.InstanceId
InstanceType = $_.InstanceType
Platform = $_.Platform
PlatformDetails = $_.PlatformDetails
LaunchTime = $_.launchtime
KeyName = $_.KeyName
AmiID = $_.ImageID
ImageName = (Get-EC2Image -ImageId $_.ImageID).Name
IamRoleID = $_.IamInstanceProfile.Id
IamRoleARN = $_.IamInstanceProfile.Arn
PrivateIP = $_.PrivateIpAddress
SubnetId = $_.SubnetId
SubnetName = (Get-EC2Subnet -subnetid ($_.SubnetId) | Select-Object -ExpandProperty tags | Where-Object -Property Key -eq Name).value
NetworkInterfaceId = $_.networkinterfaces.networkinterfaceid
MAC = $_.networkinterfaces.MacAddress
VPCId = $_.VpcId
VPCName = (Get-EC2VPC -vpcid ($_.vpcId) | Select-Object -ExpandProperty tags | Where-Object -Property Key -eq Name).value
AZ = $_.placement.AvailabilityZone
SG = $_.SecurityGroups.GroupName
BackupTag = ($_ | Select-Object -ExpandProperty tags | Where-Object -Property Key -eq BackupTag).value
ProductTag = ($_ | Select-Object -ExpandProperty tags | Where-Object -Property Key -eq Product).value
}
New-Object -TypeName PSObject -Property $properties
}
$ec2listdetails | Sort-Object -Property SubnetName | Export-Csv -Path "$($PWD.Path)\ec2-report-$region.csv"
Get-EC2Instance returns the following properties:
The returned property is the IamInstanceProfile, I can't seem to find the correct command to get all Policies attached to that Profile programmatically?
Any ideas?