Install
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
$ brew install aws-nuke $ aws-nuke -h NAME: aws-nuke - remove everything from an aws account USAGE: aws-nuke [global options] [command [command options]] VERSION: 3.61.0 AUTHOR: Erik Kristensen <erik@erikkristensen.com> COMMANDS: completion generate shell completion script version displays the version resource-types, list-resources list available resources to nuke run, nuke run nuke against an aws account and remove everything from it explain-account explain the account and authentication method used to authenticate against AWS explain-config explain the configuration file and the resources that will be nuked for an account help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --help, -h show help --version, -v print the version |
Coding
- iam/alias.tf
|
1 2 3 |
resource "aws_iam_account_alias" "hoge_test" { account_alias = "hoge-test" } |
- aws-nuke/aws-nuke-config.yaml
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 |
regions: - "ap-northeast-1" - "us-east-1" blocklist: - "xxxxxxxxx" # hoge1-prod - "xxxxxxxxx" # hoge2--stg accounts: "xxxxxxxx": alias: "hoge-test" skip-alias-check: true filters: IAMRole: - property: RoleName type: regex value: "hogeAccountAccessRole|AWSServiceRole.*" EC2VPC: - property: tag:Name type: regex value: "default" EC2SecurityGroup: - property: GroupName type: exact value: "default" EC2InternetGateway: - property: DefaultVPC type: exact value: "true" EC2InternetGatewayAttachment: - property: DefaultVPC type: exact value: "true" EC2Subnet: - property: DefaultForAz type: exact value: "true" - property: SubnetId type: regex value: "subnet-(0e0.*|02d.*|034.*)" EC2DHCPOption: - property: DefaultVPC type: exact value: "true" - property: IsDefault type: exact value: "true" EC2DefaultSecurityGroupRule: - property: GroupId type: regex value: ".*" RDSDBSubnetGroup: - property: DBSubnetGroupName type: regex value: "default-vpc-.*" DocDBSubnetGroup: - property: DBSubnetGroupName type: regex value: "default-vpc-.*" global-filters: - property: Name type: regex value: "^(?!.*(?i)test).*$" targets: - "EC2Instance" - "EC2Volume" - "EC2SecurityGroup" - "EC2VPC" - "EC2Subnet" - "EC2InternetGateway" - "EC2NatGateway" - "EC2RouteTable" - "EC2EIP" - "EC2Route" - "EC2VPCSecurityGroupEgressRule" - "EC2VPCSecurityGroupIngressRule" - "RDSCluster" - "RDSInstance" - "RDSClusterInstance" - "RDSClusterParameterGroup" - "RDSParameterGroup" - "RDSSubnetGroup" - "DocDBSubnetGroup" - "ECSCluster" - "ECSService" - "ECSTaskDefinition" - "ECSCapacityProvider" - "ELBv2" - "ELBv2Listener" - "ELBv2ListenerRule" - "ELBv2TargetGroup" - "S3Bucket" - "S3BucketPolicy" - "S3BucketOwnershipControls" - "S3BucketPublicAccessBlock" - "S3BucketVersioning" - "S3BucketEncryption" - "S3BucketLogging" - "S3BucketACL" - "CloudFrontDistribution" - "CloudFrontCachePolicy" - "CloudFrontOriginAccessControl" - "CloudFrontResponseHeadersPolicy" - "ElastiCacheCluster" - "ElastiCacheReplicationGroup" - "ElastiCacheServerlessCache" - "ElastiCacheSubnetGroup" - "IAMRole" - "IAMRolePolicy" - "IAMInstanceProfile" - "KMSKey" - "KMSAlias" - "KMSKeyPolicy" - "ACMCertificate" - "ACMCertificateValidation" - "Route53Record" - "WAFv2WebACL" - "WAFv2WebACLAssociation" - "ECRRepository" - "ECRRepositoryPolicy" - "ECRLifecyclePolicy" - "SecretsManagerSecret" - "CloudWatchLogGroup" - "CloudWatchLogStream" - "CloudWatchEventRule" - "CloudWatchEventTarget" - "CloudWatchEventConnection" - "CloudWatchEventApiDestination" - "CloudWatchLogDelivery" - "CloudWatchLogDeliverySource" - "CloudWatchLogDeliveryDestination" - "ApplicationAutoScalingPolicy" - "ApplicationAutoScalingTarget" - "SSMDocument" resource-types: excludes: - "ElasticTranscoderPreset" - "ElasticTranscoderPipeline" - "QLDBLedger" - "RoboMakerSimulationApplication" - "RoboMakerSimulationJob" - "RoboMakerRobotApplication" - "Cloud9Environment" - "CloudSearchDomain" - "CodeStarProject" - "CodeStarConnection" - "CodeStarNotificationRule" - "OpsWorksCMBackup" - "OpsWorksCMServer" - "OpsWorksCMServerState" - "QuickSightUser" - "QuickSightSubscription" - "IoTTwinMakerWorkspace" - "IoTTwinMakerEntity" - "IoTTwinMakerScene" - "IoTTwinMakerSyncJob" - "IoTTwinMakerComponentType" - "MediaTailorConfiguration" - "NeptuneGraph" - "ShieldProtection" - "ShieldProtectionGroup" - "FMSPolicy" - "FMSNotificationChannel" - "OpsWorksLayer" - "OpsWorksApp" - "OpsWorksUserProfile" - "OpsWorksInstance" - "BedrockCustomModel" - "BedrockModelCustomizationJob" - "CloudTrailTrail" - "ConfigServiceConfigRule" - "ConfigServiceConfigurationRecorder" - "ConfigServiceDeliveryChannel" - "SecurityHub" - "SNSEndpoint" - "SNSPlatformApplication" - "SNSSubscription" - "SNSTopic" - "KMSAlias" - "KMSKey" - "S3Object" - "FSxBackup" - "DynamoDBTableItem" - "DynamoDBBackup" - "EC2NetworkAcl" - "EC2NetworkAclEntry" - "RDSDBSubnetGroup" - "DocDBSubnetGroup" - "ElastiCacheSubnetGroup" - "DAXSubnetGroup" - "RedshiftSubnetGroup" - "DatabaseMigrationServiceSubnetGroup" - "IAMOpenIDConnectProvider" - "IAMPolicy" - "IAMRole" - "IAMRolePolicy" - "IAMRolePolicyAttachment" - "IAMSAMLProvider" - "IAMAccountSettingPasswordPolicy" - "IAMGroup" - "IAMGroupPolicy" - "IAMGroupPolicyAttachment" - "IAMInstanceProfile" - "IAMInstanceProfileRole" - "IAMLoginProfile" - "IAMRolesAnywhereCRL" - "IAMRolesAnywhereProfile" - "IAMRolesAnywhereTrustAnchor" - "IAMServerCertificate" - "IAMServiceSpecificCredential" - "IAMSigningCertificate" - "IAMUser" - "IAMUserAccessKey" - "IAMUserGroupAttachment" - "IAMUserHTTPSGitCredential" - "IAMUserMFADevice" - "IAMUserPolicy" - "IAMUserPolicyAttachment" - "IAMUserSSHPublicKey" - "IAMVirtualMFADevice" - "BedrockKnowledgeBase" - "DynamoDBTable" - "AWS::AppFlow::ConnectorProfile" - "AWS::AppFlow::Flow" - "AWS::AppRunner::Service" - "AWS::ApplicationInsights::Application" - "AWS::Backup::Framework" - "AWS::MWAA::Environment" - "AWS::NetworkFirewall::Firewall" - "AWS::NetworkFirewall::FirewallPolicy" - "AWS::NetworkFirewall::RuleGroup" - "AWS::Synthetics::Canary" - "AWS::Transfer::Workflow" - "AWS::Timestream::Table" - "AWS::Timestream::Database" - "AWS::Timestream::ScheduledQuery" - "AWS::AccessAnalyzer::Analyzer" - "AccessAnalyzerArchiveRule" - "AMGWorkspace" - "AMPWorkspace" - "AmplifyApp" - "AppConfigApplication" - "AppConfigConfigurationProfile" - "AppConfigDeploymentStrategy" - "AppConfigEnvironment" - "AppConfigHostedConfigurationVersion" - "AppMeshGatewayRoute" - "AppMeshMesh" - "AppMeshRoute" - "AppMeshVirtualGateway" - "AppMeshVirtualNode" - "AppMeshVirtualRouter" - "AppMeshVirtualService" - "AppRegistryApplication" - "AppRunnerConnection" - "AppRunnerService" - "AppStreamDirectoryConfig" - "AppStreamFleet" - "AppStreamFleetState" - "AppStreamImage" - "AppStreamImageBuilder" - "AppStreamImageBuilderWaiter" - "AppStreamStack" - "AppStreamStackFleetAttachment" - "AppSyncGraphqlAPI" - "ApplicationAutoScalingScalableTarget" - "AWS::ApiGateway::ApiKey" - "AWS::ApiGateway::ClientCertificate" - "APIGatewayDomainName" - "APIGatewayRestAPI" - "AWS::ApiGateway::UsagePlan" - "APIGatewayV2API" - "APIGatewayV2VpcLink" - "APIGatewayVpcLink" - "AthenaDataCatalog" - "AthenaNamedQuery" - "AthenaPreparedStatement" - "AthenaWorkGroup" - "AWSBackupVaultAccessPolicy" - "BackupVault" - "BackupReportPlan" - "AWSBackupPlan" - "AWSBackupRecoveryPoint" - "AWSBackupSelection" - "BatchComputeEnvironment" - "BatchComputeEnvironmentState" - "BatchJobQueue" - "BatchJobQueueState" - "BillingCostandUsageReport" - "BudgetsBudget" - "CloudDirectoryDirectory" - "CloudDirectorySchema" - "CloudFormationStack" - "CloudFormationStackSet" - "CloudFormationType" - "CloudHSMV2Cluster" - "CloudHSMV2ClusterHSM" - "ComprehendDocumentClassifier" - "ComprehendDominantLanguageDetectionJob" - "ComprehendEndpoint" - "ComprehendEntitiesDetectionJob" - "ComprehendEntityRecognizer" - "ComprehendEventsDetectionJob" - "ComprehendKeyPhrasesDetectionJob" - "ComprehendPiiEntitiesDetectionJob" - "ComprehendSentimentDetectionJob" - "ComprehendTargetedSentimentDetectionJob" - "ConfigServiceConformancePack" - "DAXCluster" - "DAXParameterGroup" - "DAXSubnetGroup" - "DataPipelinePipeline" - "DeviceFarmProject" - "ESDomain" - "FirehoseDeliveryStream" - "GameLiftBuild" - "GameLiftFleet" - "GameLiftMatchmakingConfiguration" - "GameLiftMatchmakingRuleSet" - "GameLiftQueue" - "GlobalAccelerator" - "GlobalAcceleratorEndpointGroup" - "GlobalAcceleratorListener" - "GuardDutyDetector" - "ImageBuilderComponent" - "ImageBuilderDistributionConfiguration" - "ImageBuilderImage" - "ImageBuilderInfrastructureConfiguration" - "ImageBuilderPipeline" - "ImageBuilderRecipe" - "Inspector2" - "InspectorAssessmentRun" - "InspectorAssessmentTarget" - "InspectorAssessmentTemplate" - "IoTAuthorizer" - "IoTCACertificate" - "IoTCertificate" - "IoTJob" - "IoTOTAUpdate" - "IoTPolicy" - "IoTRoleAlias" - "IoTSiteWiseAccessPolicy" - "IoTSiteWiseAsset" - "IoTSiteWiseAssetModel" - "IoTSiteWiseDashboard" - "IoTSiteWiseGateway" - "IoTSiteWisePortal" - "IoTSiteWiseProject" - "IoTStream" - "IoTThing" - "IoTThingGroup" - "IoTThingType" - "IoTThingTypeState" - "IoTTopicRule" - "KendraIndex" - "KinesisAnalyticsApplication" - "KinesisStream" - "KinesisVideoProject" - "LexBot" - "LexIntent" - "LexModelBuildingServiceBotAlias" - "LexSlotType" - "MachineLearningBranchPrediction" - "MachineLearningDataSource" - "MachineLearningEvaluation" - "MachineLearningMLModel" - "Macie" - "ManagedBlockchainMember" - "MGNJob" - "MGNSourceServer" - "MQBroker" - "MSKCluster" - "MSKConfiguration" - "MediaConvertJobTemplate" - "MediaConvertPreset" - "MediaConvertQueue" - "MediaLiveChannel" - "MediaLiveInput" - "MediaLiveInputSecurityGroup" - "MediaPackageChannel" - "MediaPackageOriginEndpoint" - "MediaStoreContainer" - "MediaStoreDataItems" - "NeptuneCluster" - "NeptuneInstance" - "NeptuneSnapshot" - "NetworkManagerConnectPeer" - "NetworkManagerCoreNetwork" - "NetworkManagerGlobalNetwork" - "NetworkManagerNetworkAttachment" - "OSPackage" - "OSCollection" - "OSDomain" - "OSPipeline" - "OSVPCEndpoint" - "PinpointApp" - "PinpointPhoneNumber" - "PipesPipe" - "PollyLexicon" - "RedshiftCluster" - "RedshiftParameterGroup" - "RedshiftScheduledAction" - "RedshiftSnapshot" - "RedshiftSnapshotSchedule" - "RedshiftSubnetGroup" - "RedshiftServerlessNamespace" - "RedshiftServerlessSnapshot" - "RedshiftServerlessWorkgroup" - "RekognitionCollection" - "RekognitionDataset" - "RekognitionProject" - "ResourceExplorer2Index" - "ResourceExplorer2View" - "ResourceGroupGroup" - "SageMakerApp" - "SageMakerDomain" - "SageMakerEndpoint" - "SageMakerEndpointConfig" - "SageMakerModel" - "SageMakerNotebookInstance" - "SageMakerNotebookInstanceLifecycleConfig" - "SageMakerNotebookInstanceState" - "SageMakerSpace" - "SageMakerUserProfiles" - "SchedulerSchedule" - "SecretsManagerSecret" - "SESConfigurationSet" - "SESIdentity" - "SESReceiptFilter" - "SESReceiptRuleSet" - "SESTemplate" - "SFNStateMachine" - "ServiceCatalogConstraintPortfolioAttachment" - "ServiceCatalogPortfolio" - "ServiceCatalogPortfolioProductAttachment" - "ServiceCatalogPortfolioShareAttachment" - "ServiceCatalogPrincipalPortfolioAttachment" - "ServiceCatalogProduct" - "ServiceCatalogProvisionedProduct" - "ServiceCatalogTagOption" - "ServiceCatalogTagOptionPortfolioAttachment" - "ServiceDiscoveryInstance" - "ServiceDiscoveryNamespace" - "ServiceDiscoveryService" - "SignerSigningJob" - "SQSQueue" - "SSMActivation" - "SSMAssociation" - "SSMDocument" - "SSMMaintenanceWindow" - "SSMParameter" - "SSMPatchBaseline" - "SSMQuickSetupConfigurationManager" - "SSMResourceDataSync" - "StorageGatewayFileShare" - "StorageGatewayGateway" - "StorageGatewayTape" - "StorageGatewayVolume" - "TranscribeCallAnalyticsCategory" - "TranscribeCallAnalyticsJob" - "TranscribeLanguageModel" - "TranscribeMedicalTranscriptionJob" - "TranscribeMedicalVocabulary" - "TranscribeTranscriptionJob" - "TranscribeVocabulary" - "TranscribeVocabularyFilter" - "TransferServer" - "TransferServerUser" - "TransferWebApp" - "WAFRegionalByteMatchSet" - "WAFRegionalByteMatchSetIP" - "WAFRegionalIPSet" - "WAFRegionalIPSetIP" - "WAFRegionalRateBasedRule" - "WAFRegionalRateBasedRulePredicate" - "WAFRegionalRegexMatchSet" - "WAFRegionalRegexMatchTuple" - "WAFRegionalRegexPatternSet" - "WAFRegionalRegexPatternString" - "WAFRegionalRule" - "WAFRegionalRuleGroup" - "WAFRegionalRulePredicate" - "WAFRegionalWebACL" - "WAFRegionalWebACLRuleAttachment" - "WAFRule" - "WAFWebACL" - "WAFWebACLRuleAttachment" - "WAFv2APIKey" - "WAFv2IPSet" - "WAFv2RegexPatternSet" - "WAFv2RuleGroup" - "WAFv2WebACL" - "WorkSpacesWorkspace" - "XRayGroup" - "XRaySamplingRule" |
GitHub Actions
- .github/workflows/aws-nuke.yml
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
name: Cleanup AWS Resources on: workflow_dispatch: permissions: id-token: write contents: read env: AWS_REGION: ap-northeast-1 jobs: cleanup: runs-on: ubuntu-latest environment: hoge steps: - name: Checkout uses: actions/checkout@v4 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} aws-region: ${{ env.AWS_REGION }} role-duration-seconds: 3600 - name: Install aws-nuke run: | cd /tmp wget https://github.com/ekristen/aws-nuke/releases/download/v3.60.1/aws-nuke-v3.60.1-linux-amd64.tar.gz tar -xzf aws-nuke-v3.60.1-linux-amd64.tar.gz sudo mv aws-nuke /usr/local/bin/aws-nuke sudo chmod +x /usr/local/bin/aws-nuke echo "aws-nuke installed" - name: aws-nuke Dry Run run: | AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) echo "Running aws-nuke dry-run to preview deletion targets..." echo "Account: $AWS_ACCOUNT_ID" aws-nuke run --config aws-nuke/aws-nuke-config.yaml <<< "hoge-test" |grep "would remove" - name: Run aws-nuke cleanup run: | AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) echo "Running aws-nuke cleanup on account: $AWS_ACCOUNT_ID" aws-nuke run --config aws-nuke/aws-nuke-config.yaml <<< "hoge-test" --no-dry-run --forceと |
AWS環境で、sandboxやtest環境での検証後にリソースを削除するのを忘れてしまいがちで、意図しないコストが発生するケースがよくある。aws-cli などを用いてリソース削除を自動化することも可能だが、タグによる条件分岐や対象サービスの管理が複雑化し、メンテナンス性に課題がある。
aws-nukeを活用することで、不要なリソースを一括で管理・削除でき、運用の効率化が可能。デメリットとしては環境ごとに除外するリソース名を設定する必要があるところだが、一度フィルタを整備してしまえば、他のアカウントや環境にも横展開できるというメリットがある。さらに、CI/CDパイプラインに組み込むことで、毎週定期的に不要なリソースを削除するバッチ処理を実行でき、継続的なコスト削減にも期待できる。個人的にDry Runと実行するパイプラインは分割したほうが良さげで、依存関係は削除できるかは検証中。
Was this helpful?
0 / 0
1989年生まれのFindy/SRE サブマネージャー。ホスティングから大規模なアドテクなどのインフラエンジニアとして携わる。現在はサービスの信頼性向上、DevOps、可用性、レイテンシ、パフォーマンス、モニタリング、オブザーバビリティ、緊急対応、AWSでのインフラ構築、Docker開発環境の提供、IaC、新技術の検証、リファクタリング、セキュリティ強化、分析基盤の運用、チームマネジメントを担当している。
個人事業主では数社サーバー保守とベンチャー企業のインフラコンサルティングを行うほか、TechBullを創業し、未経験者向けにSREのコーチングやコミュニティ運営、LT大会の開催、 会員管理システム「Members」の開発をリードしている。さらに、エンジニア向けYouTubeメディア「TECH WORLD」ではSRE関連の動画に出演し、過去には脆弱性スキャナ「Vuls」のOSS活動にも貢献。