Last active
March 7, 2022 20:34
-
-
Save pcgeek86/42764099021c0b1baa7f32d48afef4c2 to your computer and use it in GitHub Desktop.
AWS Cleanup script using PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
Call this script: | |
foreach ($Region in (Get-AWSRegion).Region) { | |
Set-DefaultAWSRegion -Region $Region | |
iex (iwr https://gist.githubusercontent.com/pcgeek86/42764099021c0b1baa7f32d48afef4c2/raw).Content | |
} | |
#> | |
Get-LMFunctionList | Remove-LMFunction -Force | |
foreach ($LambdaLayer in (Get-LMLayerList)) { | |
foreach ($LayerVersion in (Get-LMLayerVersionList -LayerName $LambdaLayer.LayerName)) { | |
Remove-LMLayerVersion -LayerName $LambdaLayer.LayerName -VersionNumber $LayerVersion.Version -Force | |
} | |
} | |
Get-ECSTaskDefinitionList | % { Unregister-ECSTaskDefinition -TaskDefinition $_ } | |
Get-CWLLogGroups | % { Remove-CWLLogGroup -LogGroupName $_.LogGroupName -Force } | |
$InstanceProfileList = Get-IAMInstanceProfileList | |
foreach ($IAMRole in (Get-IAMRoleList)) { | |
if ($IAMRole.RoleName -match '^cbt$') { Write-Host -ForegroundColor Blue -Object 'Skipping admin role'; continue } | |
if ($IAMRole.Path -match '/aws\-service') { | |
Remove-IAMServiceLinkedRole -RoleName $IAMRole.RoleName -Force | |
continue | |
} | |
foreach ($RolePolicy in (Get-IAMRolePolicies -RoleName $IAMRole.RoleName)) { | |
if ($RolePolicy -notmatch ':') { | |
Remove-IAMRolePolicy -RoleName $IAMRole.RoleName -PolicyName $RolePolicy -Force | |
} | |
#Unregister-IAMRolePolicy -RoleName $IAMRole.RoleName -PolicyArn $RolePolicy -Force | |
Write-Host -Object $RolePolicy | |
} | |
foreach ($AttachedPolicy in (Get-IAMAttachedRolePolicyList -RoleName $IAMRole.RoleName)) { | |
Unregister-IAMRolePolicy -PolicyArn $AttachedPolicy.PolicyArn -RoleName $IAMRole.RoleName -Force | |
} | |
# Remove the IAM role from any EC2 instance profiles | |
foreach ($InstanceProfile in ($InstanceProfileList).Where({ $PSItem.Roles.RoleName -contains $IAMRole.RoleName })) { | |
Remove-IAMRoleFromInstanceProfile -InstanceProfileName $InstanceProfile.InstanceProfileName -RoleName $IAMRole.RoleName -Force | |
} | |
Remove-IAMRole -RoleName $IAMRole.RoleName -Force | |
Write-Host -Object $IAMRole.RoleName | |
} | |
function AWS-IAM-Policy-Cleanup { | |
$IAMPolicyList = Get-IAMPolicyList -Scope local | |
foreach ($IAMPolicy in $IAMPolicyList) { | |
$IAMPolicy.Arn | |
$VersionList = Get-IAMPolicyVersionList -PolicyArn $IAMPolicy.Arn | |
foreach ($PolicyVersion in $VersionList) { | |
Remove-IAMPolicyVersion -PolicyArn $IAMPolicy.Arn -VersionId $PolicyVersion.VersionId -Force | |
} | |
Remove-IAMPolicy -PolicyArn $IAMPolicy.Arn -Force | |
Remove-Variable -Name VersionList | |
} | |
Remove-Variable -Name IAMPolicy, IAMPolicyList | |
} | |
AWS-IAM-Policy-Cleanup | |
# Clean up Elastic Container Registry (ECR) | |
foreach ($Repository in (Get-ECRRepository)) { | |
foreach ($ECRImage in (Get-ECRImage -RepositoryName $Repository.RepositoryName)) { | |
$ImageId = [Amazon.ECR.Model.ImageIdentifier]::new() | |
$ImageId.ImageDigest = $ECRImage.ImageDigest | |
Remove-ECRImageBatch -ImageId $ImageId -RepositoryName $Repository.RepositoryName -Force | |
} | |
Remove-ECRRepository -RepositoryName $Repository.RepositoryName -Force | |
} | |
foreach ($StateMachine in (Get-SFNStateMachineList)) { | |
Remove-SFNStateMachine -StateMachineArn $StateMachine.StateMachineArn -Force | |
} | |
foreach ($Activity in (Get-SFNActivityList)) { | |
Remove-SFNActivity -ActivityArn $Activity.ActivityArn -Force | |
} | |
$ClusterList = Get-ECSClusterList | |
foreach ($ECSCluster in $ClusterList) { | |
$ClusterDetail = Get-ECSClusterDetail -Cluster $ECSCluster | |
$ClusterName = $ClusterDetail.Clusters[0].ClusterName | |
# Stop all ECS Tasks on the cluster | |
Get-ECSTaskList -Cluster $ECSCluster | % { Stop-ECSTask -Cluster $ECSCluster -Task $PSItem } | |
$ServiceList = Get-ECSClusterService -Cluster $ClusterName | |
foreach ($ECSService in $ServiceList) { | |
Update-ECSService -Cluster $ClusterName -Service $ECSService -DesiredCount 0 | |
Remove-ECSService -Cluster $ClusterName -Service $ECSService -Force | |
} | |
} | |
Remove-Variable -Name ClusterList | |
foreach ($ECSCluster in (Get-ECSClusterList)) { | |
Remove-ECSCluster -Cluster $ECSCluster -Force | |
} | |
foreach ($Stack in (Get-CFNStack)) { | |
Remove-CFNStack -StackName $Stack.StackName -Force | |
} | |
$PolicyList = (Get-IAMPolicyList).Where({ $PSItem.Arn -match 'arn:aws:iam::\d{12}'}) | |
foreach ($Policy in $PolicyList) { | |
Remove-IAMPolicy -PolicyArn $Policy.Arn -Force | |
} | |
Get-EC2SpotFleetRequest | Stop-EC2SpotFleetRequest -TerminateInstance $true | |
# Clean up all stand-alone EC2 instances (not deployed by EC2 Spot, Auto Scaling, or other services) | |
Get-EC2Instance | Remove-EC2Instance -Force | |
# Clean up AWS Directory Service | |
Get-DSDirectory | Unregister-WKSWorkspaceDirectory | |
Get-DSDirectory | Remove-DSDirectory -Force | |
# Clean up all Amazon Machine Images | |
Get-EC2Image -Owner self | Unregister-EC2Image | |
# Clean up AWS CodeCommit repositories | |
Get-CCRepositoryList | Remove-CCRepository -Force | |
# Clean up AWS CodeBuild projects | |
Get-CBProjectList | Remove-CBProject -Force | |
# Delete all Amazon EC2 EBS snapshots | |
Get-EC2Snapshot -Owner self | Remove-EC2Snapshot -Force | |
# Clean up all DocumentDB clusters | |
Get-DOCDBCluster | Edit-DOCDBCluster -DeletionProtection $false -SkipFinalSnapshot $true | |
# You might get this error message: Remove-DOCDBCluster: Cluster cannot be deleted, it still contains DB instances in non-deleting state. | |
# ... which means you need to delete the individual instances first | |
# Delete all instances | |
Get-DOCDBInstance | Remove-DOCDBInstance -Force | |
# If you don't skip final snapshot, you get this error: Remove-DOCDBCluster: Please specify FinalDBSnapshotIdentifier or SkipFinalSnapshot | |
Get-DOCDBCluster | Remove-DOCDBCluster -Force -SkipFinalSnapshot $true | |
# Destroy all DynamoDB tables | |
Get-DDBTableList | Remove-DDBTable -Force | |
# Stop any running Automation Executions in the AWS Systems Manager Automation service | |
Get-SSMAutomationExecutionList | Stop-SSMAutomationExecution | |
# AWS Service Catalog | |
## Unregister all products from portfolios | |
Find-SCProductsAsAdmin | % { Get-SCProductPortfolioList -ProductId $_.ProductARN.Split('/')[-1] | Add-Member -Name ProductId -MemberType NoteProperty -Value $_.ProductARN.Split('/')[-1] -PassThru } | % { Unregister-SCProductFromPortfolio -PortfolioId $_.Id -ProductId $_.ProductId } | |
# Unregister all AWS Service Catalog principals from portfolios | |
Get-SCPortfolioList | % { Get-SCPrincipalsForPortfolio -PortfolioId $_.Id | Add-Member -MemberType NoteProperty -Name PortfolioId -Value $_.Id -PassThru } | % { Unregister-SCPrincipalFromPortfolio -PortfolioId $_.PortfolioId -PrincipalARN $_.PrincipalARN -Force } | |
## Delete all AWS Service Catalog portfolios | |
Get-SCPortfolioList | Remove-SCPortfolio -Force | |
## Get all AWS Service Catalog provisioned products for the account (by region) | |
Get-SCProvisionedProduct -AccessLevelFilter_Key Account -AccessLevelFilter_Value self | %{ Remove-SCProvisionedProduct -ProvisionedProductId $_.Id -Force } | |
# Delete all Amazon SQS queues | |
Get-SQSQueue | Remove-SQSQueue -Force | |
# Clean up Amazon S3 Buckets | |
Get-S3Bucket | Remove-S3Bucket -DeleteBucketContent -Force | |
# Clean up all EC2 instance profiles | |
Get-IAMInstanceProfileList | Remove-IAMInstanceProfile -Force | |
# Delete all Elastic Load Balancer (ELB) Load Balancers | |
Get-ELB2LoadBalancer | Remove-ELB2LoadBalancer -Force | |
# Delete all ELB Target Groups | |
Get-ELB2TargetGroup | Remove-ELB2TargetGroup -Force | |
# Amazon VPC Cleanup | |
# Delete all Amazon VPC NAT Gateways | |
Get-EC2NatGateway | ? State -ne deleted | Remove-EC2NatGateway -Force | |
# Release all Amazon EC2 / VPC Elastic IP Addresses | |
Get-EC2Address | % { Remove-EC2Address -Force -AllocationId $_.AllocationId } | |
# Detach and remove all VPC / EC2 Internet Gateways | |
Get-EC2InternetGateway | % { Dismount-EC2InternetGateway -Force -InternetGatewayId $_.InternetGatewayId -VpcId $_.Attachments[0].VpcId } | |
Get-EC2InternetGateway | Remove-EC2InternetGateway -Force | |
$EC2NetworkInterfaceList = Get-EC2NetworkInterface | |
foreach ($EC2NetworkInterface in $EC2NetworkInterfaceList) { | |
Remove-EC2NetworkInterface -NetworkInterfaceId $EC2NetworkInterface.NetworkInterfaceId -Force | |
} | |
$RouteTableList = Get-EC2RouteTable | |
foreach ($RouteTable in $RouteTableList) { | |
foreach ($RouteTableAssociation in $RouteTable.Associations) { | |
Unregister-EC2RouteTable -AssociationId $RouteTableAssociation.RouteTableAssociationId | |
} | |
foreach ($Route in $RouteTable.Routes) { | |
Remove-EC2Route -DestinationCidrBlock $Route.DestinationCidrBlock -RouteTableId $RouteTable.RouteTableId -Force | |
} | |
Remove-EC2RouteTable -RouteTableId $RouteTable.RouteTableId -Force | |
} | |
$SubnetList = Get-EC2Subnet | |
foreach ($Subnet in $SubnetList) { | |
Remove-EC2Subnet -SubnetId $Subnet.SubnetId -Force | |
} | |
# Delete all Amazon VPC DHCP Option Sets | |
$DHCPOptionList = Get-EC2DhcpOption | |
foreach ($DHCPOption in $DHCPOptionList) { | |
Remove-EC2DhcpOption -DhcpOptionsId $DHCPOption.DhcpOptionsId -Force | |
} | |
$NetworkACLList = Get-EC2NetworkAcl | |
foreach ($NetworkACL in $NetworkACLList) { | |
Remove-EC2NetworkAcl -NetworkAclId $NetworkACL.NetworkAclId -Force | |
} | |
$EC2SecurityGroupList = Get-EC2SecurityGroup | |
foreach ($EC2SecurityGroup in $EC2SecurityGroupList) { | |
Remove-EC2SecurityGroup -Force -GroupId $EC2SecurityGroup.GroupId | |
} | |
# Delete all Amazon VPCs | |
$VPCList = Get-EC2Vpc | |
foreach ($VPC in $VPCList) { | |
# Disassociate DHCP options with Amazon VPCs | |
Register-EC2DhcpOption -DhcpOptionsId 'default' -VpcId $VPC.VpcId | |
Remove-EC2Vpc -VpcId $VPC.VpcId -Force | |
} | |
# Clean up any lexicons that were imported into Amazon Polly | |
Get-POLLexiconList | Remove-POLLexicon -Force | |
# Delete all EC2 Elastic Block Store (EBS) volumes | |
Get-EC2Volume | Remove-EC2Volume -Force | |
# Delete all Amazon CloudWatch Alarms | |
Get-CWAlarm | Remove-CWAlarm -Force | |
# Delete all Amazon CloudWatch Dashboards | |
Get-CWDashboardList | Remove-CWDashboard -Force | |
# Delete all Amazon CloudWatch Events (Event Bridge) rules | |
$RuleList = Get-EVBRule | |
foreach ($EVBRule in $RuleList) { | |
$EVBTargetList = Get-EVBTargetsByRule -Rule $EVBRule.Name | |
foreach ($EVBTarget in $EVBTargetList) { | |
Remove-EVBTarget -Rule $EVBRule.Name -Id $EVBTarget.Id -Force -Enforce $true | |
} | |
Remove-EVBRule -Force -Enforce $true -Name $EVBRule.Name -EventBusName $EVBRule.EventBusName | |
} | |
# Clean up Amazon RDS database clusters | |
Get-RDSDBCluster | Remove-RDSDBCluster -Force -SkipFinalSnapshot $true | |
Get-RDSDBInstance | Remove-RDSDBInstance -Force -SkipFinalSnapshot $true | |
# Clean up all AWS Datapipelines | |
Get-DPPipeline | % { Remove-DPPipeline -PipelineId $_.Id -Force } | |
# Clean up all Amazon Elastic FileSystem (EFS) resources | |
$EFSList = Get-EFSFileSystem | |
foreach ($FileSystem in $EFSList) { | |
$MountTargetList = Get-EFSMountTarget -FileSystemId $FileSystem.FileSystemId | |
foreach ($MountTarget in $MountTargetList) { | |
Remove-EFSMountTarget -MountTargetId $MountTarget.MountTargetId -Force | |
} | |
Remove-EFSFileSystem -FileSystemId $FileSystem.FileSystemId -Force | |
$MountTargetList = $null | |
} | |
# Clean up all Amazon Timestream databases | |
$DBList = Get-TSWDatabaseList | |
foreach ($TSDB in $DBList) { | |
$TableList = Get-TSWTableList -DatabaseName $TSDB.DatabaseName | |
foreach ($Table in $TableList) { | |
Remove-TSWTable -DatabaseName $TSDB.DatabaseName -TableName $Table.TableName -Force | |
} | |
Remove-TSWDatabase -DatabaseName $TSDB.DatabaseName -Force | |
} | |
Remove-Variable -Name Table, TableList, DBList, TSDB -ErrorAction Ignore | |
# Remove all Amazon Managed Prometheus workspaces | |
Get-PROMWorkspaceList | Remove-PROMWorkspace -Force | |
# Clean up all AWS Transcribe Transcription Jobs | |
Get-TRSTranscriptionJobList | Remove-TRSTranscriptionJob -Force | |
# Delete all EC2 Spot Instance requests | |
Get-EC2SpotInstanceRequest | Stop-EC2SpotInstanceRequest | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment