0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS既存のリソースから情報を抽出し、テンプレート化する方法を考える

0
Last updated at Posted at 2025-08-21

1. はじめに

ハンズオンで構築した環境を自動化したい。現状、既存のリソース情報から CloudFormation テンプレートを自動生成する公式ツールは提供されていない。
そこで、CLI でリソース情報を JSON として抽出し、その結果を AI に渡してテンプレート化を依頼→検証する、というシンプルな手順を試す。

2. 代表的なリソースの情報抽出コマンド

以下は代表的な抽出コマンドの例。S3 はコマンドが多く冗長になりがちで、今回の目的(UI で作成した CodePipeline の自動化)には向かない。
この検証では aws codepipeline get-pipeline を中心に使う。
コマンド一つで情報が抽出できるものしかこの方法は使えないかもしれません。

# AWS リソース情報抽出コマンド集

## S3
aws s3api list-buckets
aws s3api get-bucket-location --bucket <BucketName>
aws s3api get-bucket-versioning --bucket <BucketName>
aws s3api get-bucket-encryption --bucket <BucketName>
aws s3api get-public-access-block --bucket <BucketName>
aws s3api get-bucket-policy --bucket <BucketName>
aws s3api get-bucket-tagging --bucket <BucketName> 2>/dev/null || echo "no-tags"

## IAM ロール
aws iam get-role --role-name <RoleName>
aws iam list-attached-role-policies --role-name <RoleName>
aws iam list-role-policies --role-name <RoleName>
aws iam get-role-policy --role-name <RoleName> --policy-name <PolicyName>

## CodePipeline
aws codepipeline get-pipeline --name <PipelineName> --query 'pipeline'
aws codepipeline get-pipeline-state --name <PipelineName>

## CodeBuild
aws codebuild batch-get-projects --names <ProjectName>

## CloudFormation
aws cloudformation get-template --stack-name <StackName> --query 'TemplateBody'
aws cloudformation describe-stacks --stack-name <StackName>

## CloudFront
aws cloudfront list-distributions
aws cloudfront get-distribution --id <DistributionId>
aws cloudfront get-distribution-config --id <DistributionId>

## EC2
aws ec2 describe-instances --instance-ids <InstanceId>
aws ec2 describe-security-groups --group-ids <SGId>
aws ec2 describe-subnets --subnet-ids <SubnetId>

## VPC
aws ec2 describe-vpcs --vpc-ids <VpcId>
aws ec2 describe-route-tables --filters "Name=vpc-id,Values=<VpcId>"
aws ec2 describe-internet-gateways --filters "Name=attachment.vpc-id,Values=<VpcId>"
aws ec2 describe-nat-gateways --filter Name=vpc-id,Values=<VpcId>

## RDS
aws rds describe-db-instances --db-instance-identifier <DBInstanceId>
aws rds describe-db-subnet-groups --db-subnet-group-name <DBSubnetGroupName>

## ALB (ELB v2)
aws elbv2 describe-load-balancers --names <LBName>
aws elbv2 describe-target-groups --names <TGName>
aws elbv2 describe-listeners --load-balancer-arn <LBArn>

## Lambda
aws lambda get-function --function-name <FunctionName>
aws lambda get-function-configuration --function-name <FunctionName>

## Secrets Manager / SSM
aws secretsmanager describe-secret --secret-id <SecretName>
aws ssm get-parameter --name <ParamName> --with-decryption

## API Gateway
たくさんあるので向いてない

検証

UI で作成した CodePipeline の設定を aws codepipeline get-pipeline で取得し、
得られた JSON をもとに CloudFormation テンプレートへ落とし込む流れで検証する。

パイプラインが存在することを確認

PS C:\Users\user> aws codepipeline list-pipelines
{
    "pipelines": [
        {
            "name": "aws-static-website-hosting",
            "version": 1,
            "pipelineType": "V2",
            "executionMode": "QUEUED",
            "created": "2025-08-19T20:36:10.807000+09:00",
            "updated": "2025-08-19T20:36:10.807000+09:00"
        }
    ]
}

パイプラインの情報抽出

PS C:\Users\user> aws codepipeline get-pipeline --name aws-static-website-hosting
{
    "pipeline": {
        "name": "aws-static-website-hosting",
        "roleArn": "arn:aws:iam::414328432170:role/service-role/handson-pipeline-service-role",
        "artifactStore": {
            "type": "S3",
            "location": "codepipeline-ap-northeast-1-49bc9c9efc28-43de-9322-923c265b4546"
        },
        "stages": [
            {
                "name": "Source",
                "actions": [
                    {
                        "name": "Source",
                        "actionTypeId": {
                            "category": "Source",
                            "owner": "AWS",
                            "provider": "CodeStarSourceConnection",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "BranchName": "main",
                            "ConnectionArn": "arn:aws:codeconnections:ap-northeast-1:414328432170:connection/a8f8fc76-d904-4e45-8f82-c0979b312825",
                            "DetectChanges": "true",
                            "FullRepositoryId": "aws-hands-on-training/aws-static-website-hosting",
                            "OutputArtifactFormat": "CODE_ZIP"
                        },
                        "outputArtifacts": [
                            {
                                "name": "SourceArtifact"
                            }
                        ],
                        "inputArtifacts": [],
                        "region": "ap-northeast-1",
                        "namespace": "SourceVariables"
                    }
                ],
                "onFailure": {
                    "result": "RETRY",
                    "retryConfiguration": {
                        "retryMode": "ALL_ACTIONS"
                    }
                }
            },
            {
                "name": "Deploy",
                "actions": [
                    {
                        "name": "Deploy",
                        "actionTypeId": {
                            "category": "Deploy",
                            "owner": "AWS",
                            "provider": "CloudFormation",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "ActionMode": "CREATE_UPDATE",
                            "RoleArn": "arn:aws:iam::414328432170:role/handson-cfn-service-role",
                            "StackName": "handson-lab-click-S3bucket",
                            "TemplatePath": "SourceArtifact::cfn/ap-northeast-1/s3/01form-handson-bucket.yaml"
                        },
                        "outputArtifacts": [],
                        "inputArtifacts": [
                            {
                                "name": "SourceArtifact"
                            }
                        ],
                        "region": "ap-northeast-1",
                        "namespace": "DeployVariables"
                    }
                ],
                "onFailure": {
                    "result": "ROLLBACK"
                }
            }
        ],
        "version": 1,
        "executionMode": "QUEUED",
        "pipelineType": "V2",
        "triggers": [
            {
                "providerType": "CodeStarSourceConnection",
                "gitConfiguration": {
                    "sourceActionName": "Source",
                    "push": [
                        {
                            "branches": {
                                "includes": [
                                    "main"
                                ]
                            }
                        }
                    ]
                }
            }
        ]
    },
    "metadata": {
        "pipelineArn": "arn:aws:codepipeline:ap-northeast-1:414328432170:aws-static-website-hosting",
        "created": "2025-08-19T20:36:10.807000+09:00",
        "updated": "2025-08-19T20:36:10.807000+09:00"
    }
}

# このコマンドの出力結果は使わなくてもよさそうだったので省略
# aws codepipeline get-pipeline-state --name aws-static-website-hosting

AI入力文

AWS CodePipelineを構成するテンプレートを作成してほしい。
CodePipelineはすでにUI上で構築しており、その情報をもとに作成してほしい。
情報は以下の通り
(ここに前述の出力結果を貼る)

追加の要件
パイプライン名はhandson-pipeline-aws-static-website-hosting-s3bucket
スタック名はhandson-pipeline-aws-static-website-hosting-s3bucket
AWSアカウントは自動取得できる変数を使う
アーティファクトバケットはcodepipeline-ap-northeast-artifacts-moritokey
このテンプレートを用いて複数のテンプレートを生成しないので、パラメタ化は不要。

AI出力結果

AWSTemplateFormatVersion: '2010-09-09'
Description: >
  Create CodePipeline (handson-pipeline-aws-static-website-hosting-s3bucket) based on existing UI configuration.
  Uses existing IAM roles, CodeStar Connection, and artifact S3 bucket. No parameters (except pseudo-params) by design.

Resources:
  HandsonStaticWebsiteHostingPipeline:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      Name: handson-pipeline-aws-static-website-hosting-s3bucket
      RoleArn: !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/service-role/handson-pipeline-service-role"
      PipelineType: V2
      ExecutionMode: QUEUED
      ArtifactStore:
        Type: S3
        Location: codepipeline-ap-northeast-artifacts-moritokey
      Triggers:
        - ProviderType: CodeStarSourceConnection
          GitConfiguration:
            SourceActionName: Source
            Push:
              - Branches:
                  Includes:
                    - main
      Stages:
        - Name: Source
          Actions:
            - Name: Source
              Namespace: SourceVariables
              ActionTypeId:
                Category: Source
                Owner: AWS
                Provider: CodeStarSourceConnection
                Version: '1'
              RunOrder: 1
              Configuration:
                BranchName: main
                ConnectionArn: !Sub "arn:${AWS::Partition}:codeconnections:${AWS::Region}:${AWS::AccountId}:connection/a8f8fc76-d904-4e45-8f82-c0979b312825"
                DetectChanges: 'true'
                FullRepositoryId: aws-hands-on-training/aws-static-website-hosting
                OutputArtifactFormat: CODE_ZIP
              OutputArtifacts:
                - Name: SourceArtifact
              Region: ap-northeast-1

        - Name: Deploy
          Actions:
            - Name: Deploy
              Namespace: DeployVariables
              ActionTypeId:
                Category: Deploy
                Owner: AWS
                Provider: CloudFormation
                Version: '1'
              RunOrder: 1
              Configuration:
                ActionMode: CREATE_UPDATE
                RoleArn: !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/handson-cfn-service-role"
                StackName: handson-pipeline-aws-static-website-hosting-s3bucket
                # ここにリソースを作成するテンプレートを指定する
                TemplatePath: SourceArtifact::cfn/ap-northeast-1/s3/01form-handson-bucket.yaml
              InputArtifacts:
                - Name: SourceArtifact
              Region: ap-northeast-1



感想

一発で動作するテンプレートができました。
AIはすごいですね。今まで苦労はなんだったのか。

今後この方法を活用して生産性を上げようと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?