<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Amazon Linux - CayTech Lab</title>
	<atom:link href="https://caymezon.com/tag/amazon-linux/feed/" rel="self" type="application/rss+xml" />
	<link>https://caymezon.com</link>
	<description></description>
	<lastBuildDate>Sat, 07 Feb 2026 09:55:59 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.1</generator>

<image>
	<url>https://caymezon.com/wp-content/uploads/2026/01/cropped-CayTechLab-32x32.jpg</url>
	<title>Amazon Linux - CayTech Lab</title>
	<link>https://caymezon.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<atom:link rel='hub' href='https://caymezon.com/?pushpress=hub'/>
	<item>
		<title>【実践】VSCodeとCloudFormationで学ぶAWS EC2構築｜コードでインフラ管理</title>
		<link>https://caymezon.com/aws-ec2-cloudformation-vscode-guide/</link>
					<comments>https://caymezon.com/aws-ec2-cloudformation-vscode-guide/#respond</comments>
		
		<dc:creator><![CDATA[caymezon]]></dc:creator>
		<pubDate>Sat, 10 Jan 2026 11:21:55 +0000</pubDate>
				<category><![CDATA[AWS Basic]]></category>
		<category><![CDATA[Cloud & Infra]]></category>
		<category><![CDATA[Amazon Linux]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[CloudFormation]]></category>
		<category><![CDATA[EC2]]></category>
		<category><![CDATA[IaC]]></category>
		<category><![CDATA[VSCode]]></category>
		<guid isPermaLink="false">https://caymezon.com/?p=19912</guid>

					<description><![CDATA[<p>目次 1️⃣ はじめに：なぜCloudFormationを使うのか？手動構築の課題CloudFormationのメリットこの記事で学べること対象読者前提条件2️⃣ 構築する環境の全体像アーキテクチャ図構築されるリソース実 [&#8230;]</p>
<p>The post <a href="https://caymezon.com/aws-ec2-cloudformation-vscode-guide/">【実践】VSCodeとCloudFormationで学ぶAWS EC2構築｜コードでインフラ管理</a> first appeared on <a href="https://caymezon.com">CayTech Lab</a>.</p>]]></description>
										<content:encoded><![CDATA[<div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-2" checked><label class="toc-title" for="toc-checkbox-2">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">1️⃣  はじめに：なぜCloudFormationを使うのか？</a><ol><li><a href="#toc2" tabindex="0">手動構築の課題</a></li><li><a href="#toc3" tabindex="0">CloudFormationのメリット</a></li><li><a href="#toc4" tabindex="0">この記事で学べること</a></li><li><a href="#toc5" tabindex="0">対象読者</a></li><li><a href="#toc6" tabindex="0">前提条件</a></li></ol></li><li><a href="#toc7" tabindex="0">2️⃣  構築する環境の全体像</a><ol><li><a href="#toc8" tabindex="0">アーキテクチャ図</a></li><li><a href="#toc9" tabindex="0">構築されるリソース</a></li><li><a href="#toc10" tabindex="0">実現する機能</a></li></ol></li><li><a href="#toc11" tabindex="0">3️⃣  ローカル環境の準備</a><ol><li><a href="#toc12" tabindex="0">作業フォルダの作成</a></li><li><a href="#toc13" tabindex="0">キーペアファイルの配置</a></li></ol></li><li><a href="#toc14" tabindex="0">4️⃣  CloudFormationテンプレートの作成</a><ol><li><a href="#toc15" tabindex="0">テンプレートファイルを作成</a></li><li><a href="#toc16" tabindex="0">完全なテンプレートコード</a></li><li><a href="#toc17" tabindex="0">テンプレートの構造解説</a></li></ol></li><li><a href="#toc18" tabindex="0">5️⃣  CloudFormationスタックの作成</a><ol><li><a href="#toc19" tabindex="0">スタック作成コマンド</a></li><li><a href="#toc20" tabindex="0">スタック作成の進行状況を確認</a></li><li><a href="#toc21" tabindex="0">スタック作成完了の確認</a></li></ol></li><li><a href="#toc22" tabindex="0">6️⃣  EC2インスタンスの動作確認</a><ol><li><a href="#toc23" tabindex="0">Webサーバーへのアクセス</a></li><li><a href="#toc24" tabindex="0">SSH接続の確認</a></li></ol></li><li><a href="#toc25" tabindex="0">7️⃣  セキュリティグループの設定変更</a><ol><li><a href="#toc26" tabindex="0">自分のIPアドレスを確認</a></li><li><a href="#toc27" tabindex="0">セキュリティグループIDを取得</a></li><li><a href="#toc28" tabindex="0">インバウンドルールを更新</a></li></ol></li><li><a href="#toc29" tabindex="0">8️⃣  スタックの削除（リソースのクリーンアップ）</a><ol><li><a href="#toc30" tabindex="0">インスタンスを停止</a></li><li><a href="#toc31" tabindex="0">スタックを削除</a></li></ol></li><li><a href="#toc32" tabindex="0">9️⃣  トラブルシューティング</a><ol><li><a href="#toc33" tabindex="0">スタック作成が失敗する</a></li><li><a href="#toc34" tabindex="0">SSH接続ができない</a></li><li><a href="#toc35" tabindex="0">Webページが表示されない</a></li></ol></li><li><a href="#toc36" tabindex="0">🔟 まとめ</a><ol><li><a href="#toc37" tabindex="0">学んだこと</a></li><li><a href="#toc38" tabindex="0">CloudFormationのメリット再確認</a></li><li><a href="#toc39" tabindex="0">次のステップ</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">1️⃣  はじめに：なぜCloudFormationを使うのか？</span></h2>
<p>AWSマネジメントコンソールでのEC2構築は直感的ですが、<strong>再現性</strong>と<strong>管理性</strong>に課題があります。</p>
<h3><span id="toc2">手動構築の課題</span></h3>
<ul>
<li>❌ 同じ構成を再現するのが難しい</li>
<li>❌ 設定ミスが発生しやすい</li>
<li>❌ 変更履歴が残らない</li>
<li>❌ チーム共有が困難</li>
</ul>
<h3><span id="toc3">CloudFormationのメリット</span></h3>
<ul>
<li>✅ <strong>インフラをコード化</strong>（IaC: Infrastructure as Code）</li>
<li>✅ <strong>バージョン管理</strong>が可能（Gitで管理）</li>
<li>✅ <strong>再現性が高い</strong>（同じ環境を何度でも作成可能）</li>
<li>✅ <strong>自動化</strong>しやすい</li>
</ul>
<h3><span id="toc4">この記事で学べること</span></h3>
<ul>
<li>VSCodeとAWS CLIを使ったローカル開発環境での構築</li>
<li>CloudFormationテンプレートの作成と理解</li>
<li>スタックの作成・更新・削除の実践手順</li>
<li>セキュリティグループの適切な設定</li>
</ul>
<h3><span id="toc5">対象読者</span></h3>
<ul>
<li>AWS初心者でIaCに興味がある方</li>
<li>EC2をコードで管理したい方</li>
<li>VSCodeを使った開発に慣れている方</li>
</ul>
<h3><span id="toc6">前提条件</span></h3>
<ul>
<li>✅ AWS CLIがインストール済み</li>
<li>✅ AWS CLIの初期設定完了（<code>aws configure</code>）</li>
<li>✅ VSCodeがインストール済み</li>
<li>✅ EC2キーペアを作成済み</li>
</ul>
<p>キーペアの作成方法は<a href="https://caymezon.com/aws-ec2-keypair-creation-guide/">こちらの記事</a>を参照してください。</p>
<p><!-- START MoshimoAffiliateEasyLink --><script type="text/javascript">(function(b,c,f,g,a,d,e){b.MoshimoAffiliateObject=a;b[a]=b[a]||function(){arguments.currentScript=c.currentScript||c.scripts[c.scripts.length-2];(b[a].q=b[a].q||[]).push(arguments)};c.getElementById(a)||(d=c.createElement(f),d.src=g,d.id=a,e=c.getElementsByTagName("body")[0],e.appendChild(d))})(window,document,"script","//dn.msmstatic.com/site/cardlink/bundle.js?20220329","msmaflink");msmaflink({"n":"AWSの基本・仕組み・重要用語が全部わかる教科書 (見るだけ図解)","b":"SBクリエイティブ","t":"","d":"https:\/\/m.media-amazon.com","c_p":"\/images\/I","p":["\/51DEDQXj6oL._SL500_.jpg","\/41F589smNwL._SL500_.jpg","\/41R6f9yyCWL._SL500_.jpg","\/41HqWQ9BvmL._SL500_.jpg","\/41p8p0ZU79L._SL500_.jpg","\/41qLC-fndBL._SL500_.jpg","\/41fcLv9VT5L._SL500_.jpg","\/51lRvCsvHqL._SL500_.jpg"],"u":{"u":"https:\/\/www.amazon.co.jp\/dp\/4815607850","t":"amazon","r_v":""},"v":"2.1","b_l":[{"id":1,"u_tx":"Amazonで見る","u_bc":"#f79256","u_url":"https:\/\/www.amazon.co.jp\/dp\/4815607850","a_id":1384942,"p_id":170,"pl_id":27060,"pc_id":185,"s_n":"amazon","u_so":1},{"id":2,"u_tx":"楽天市場で見る","u_bc":"#f76956","u_url":"https:\/\/search.rakuten.co.jp\/search\/mall\/AWS%E3%81%AE%E5%9F%BA%E6%9C%AC%E3%83%BB%E4%BB%95%E7%B5%84%E3%81%BF%E3%83%BB%E9%87%8D%E8%A6%81%E7%94%A8%E8%AA%9E%E3%81%8C%E5%85%A8%E9%83%A8%E3%82%8F%E3%81%8B%E3%82%8B%E6%95%99%E7%A7%91%E6%9B%B8%20(%E8%A6%8B%E3%82%8B%E3%81%A0%E3%81%91%E5%9B%B3%E8%A7%A3)\/","a_id":1384917,"p_id":54,"pl_id":27059,"pc_id":54,"s_n":"rakuten","u_so":2},{"id":3,"u_tx":"Yahoo!ショッピングで見る","u_bc":"#66a7ff","u_url":"https:\/\/shopping.yahoo.co.jp\/search?first=1\u0026p=AWS%E3%81%AE%E5%9F%BA%E6%9C%AC%E3%83%BB%E4%BB%95%E7%B5%84%E3%81%BF%E3%83%BB%E9%87%8D%E8%A6%81%E7%94%A8%E8%AA%9E%E3%81%8C%E5%85%A8%E9%83%A8%E3%82%8F%E3%81%8B%E3%82%8B%E6%95%99%E7%A7%91%E6%9B%B8%20(%E8%A6%8B%E3%82%8B%E3%81%A0%E3%81%91%E5%9B%B3%E8%A7%A3)","a_id":1466950,"p_id":1225,"pl_id":27061,"pc_id":1925,"s_n":"yahoo","u_so":3}],"eid":"eaCUB","s":"s"});</script></p>
<div id="msmaflink-eaCUB">リンク</div>
<p><!-- MoshimoAffiliateEasyLink END --></p>
<h2><span id="toc7">2️⃣  構築する環境の全体像</span></h2>
<h3><span id="toc8">アーキテクチャ図</span></h3>
<pre><code class="language-plaintext">+------------------------------+
| ローカル環境 (VSCode)         |
| +--------------------------+ |
| | template.yaml            | |
| | (CloudFormation)         | |
| +--------------------------+ |
|              |               |
|              | AWS CLI       |
|              v               |
+--------------+---------------+
               |
               | スタック作成
               v
+--------------+---------------+
| AWS環境                      |
| +--------------------------+ |
| | IAM Role                 | |
| | EC2 Instance Profile     | |
| | Security Group           | |
| | EC2 Instance             | |
| | (Amazon Linux 2023)      | |
| | + Apache httpd           | |
| +--------------------------+ |
+------------------------------+
</code></pre>
<h3><span id="toc9">構築されるリソース</span></h3>
<table>
<thead>
<tr>
<th>リソース</th>
<th>用途</th>
<th>詳細</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>IAM Role</strong></td>
<td>EC2の権限管理</td>
<td>SSM接続用の権限を付与</td>
</tr>
<tr>
<td><strong>Instance Profile</strong></td>
<td>ロールのアタッチ</td>
<td>IAMロールとEC2の橋渡し</td>
</tr>
<tr>
<td><strong>Security Group</strong></td>
<td>ファイアウォール</td>
<td>SSH(22)とHTTP(80)を許可</td>
</tr>
<tr>
<td><strong>EC2 Instance</strong></td>
<td>仮想サーバー</td>
<td>t2.micro（無料枠対象）</td>
</tr>
<tr>
<td><strong>User Data</strong></td>
<td>初期設定</td>
<td>Apache自動インストール</td>
</tr>
</tbody>
</table>
<h3><span id="toc10">実現する機能</span></h3>
<ul>
<li><strong>Webサーバー</strong>：Apache httpdが自動起動</li>
<li><strong>サンプルページ</strong>：「Hello from Amazon Linux 2023!」を表示</li>
<li><strong>SSH接続</strong>：キーペアを使った安全な接続</li>
<li><strong>SSM接続</strong>：Session Managerでブラウザから接続可能</li>
</ul>
<p> </p>
<h2><span id="toc11">3️⃣  ローカル環境の準備</span></h2>
<h3><span id="toc12">作業フォルダの作成</span></h3>
<p><strong>VSCodeのターミナルを開く：</strong></p>
<pre><code class="language-bash">mkdir C:\my-aws\aws-learning-projects\ec2-cloudformation
cd C:\my-aws\aws-learning-projects\ec2-cloudformation

# Mac/Linuxの場合
mkdir -p ~/my-aws/aws-learning-projects/ec2-cloudformation
cd ~/my-aws/aws-learning-projects/ec2-cloudformation</code></pre>
<h3><span id="toc13">キーペアファイルの配置</span></h3>
<p>作成済みのキーペアファイル（<code>.pem</code>）を作業フォルダにコピー：</p>
<pre><code class="language-bash"># Windowsの場合（例）
copy %USERPROFILE%\.ssh\my-ec2-test-key.pem .

# Mac/Linuxの場合（例）
cp ~/.ssh/my-ec2-test-key.pem .
chmod 400 my-ec2-test-key.pem</code></pre>
<p><strong>フォルダ構成：</strong></p>
<pre><code class="language-plaintext">ec2-cloudformation/
├── my-ec2-test-key.pem  # キーペアファイル
└── template.yaml        # これから作成</code></pre>
<p> </p>
<h2><span id="toc14">4️⃣  CloudFormationテンプレートの作成</span></h2>
<h3><span id="toc15">テンプレートファイルを作成</span></h3>
<p><strong>VSCodeでファイルを開く：</strong></p>
<pre><code class="language-bash">code ./template.yaml</code></pre>
<h3><span id="toc16">完全なテンプレートコード</span></h3>
<p>以下のYAMLコードをコピーして <code>template.yaml</code> に貼り付けてください：</p>
<pre><code class="language-yaml">AWSTemplateFormatVersion: '2010-09-09'
Description: 'EC2 Instance with Amazon Linux 2023'

Parameters:
  KeyName:
    Type: String
    Default: my-ec2-test-key
    Description: Name of an existing EC2 KeyPair
  
  LatestAmiId:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
    Description: Latest Amazon Linux 2023 AMI ID from SSM Parameter Store

Resources:
  EC2Role:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
            Action: 'sts:AssumeRole'
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
      Tags:
        - Key: Name
          Value: ec2-test-01-role
        - Key: CmBillingGroup
          Value: test

  EC2InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - !Ref EC2Role

  EC2SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: ec2-test-01-sg
      GroupDescription: Security group for EC2 test instance
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
          Description: Allow SSH from anywhere (Change to your IP later)
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
          Description: Allow HTTP from anywhere (Change to your IP later)
      Tags:
        - Key: Name
          Value: ec2-test-01-sg
        - Key: CmBillingGroup
          Value: test

  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !Ref LatestAmiId
      InstanceType: t2.micro
      KeyName: !Ref KeyName
      SecurityGroupIds:
        - !Ref EC2SecurityGroup
      IamInstanceProfile: !Ref EC2InstanceProfile
      UserData:
        Fn::Base64: |
          #!/bin/bash
          yum update -y
          yum install -y httpd
          systemctl start httpd
          systemctl enable httpd
          echo "<h1>Hello from Amazon Linux 2023!</h1>" > /var/www/html/index.html
          echo "<p>Instance ID: $(ec2-metadata --instance-id | cut -d ' ' -f 2)</p>" >> /var/www/html/index.html
          echo "<p>Availability Zone: $(ec2-metadata --availability-zone | cut -d ' ' -f 2)</p>" >> /var/www/html/index.html
      Tags:
        - Key: Name
          Value: ec2-test-01-instance-al2023
        - Key: CmBillingGroup
          Value: test

Outputs:
  InstanceId:
    Description: EC2 Instance ID
    Value: !Ref EC2Instance
  
  PublicIP:
    Description: Public IP Address
    Value: !GetAtt EC2Instance.PublicIp
  
  PublicDNS:
    Description: Public DNS Name
    Value: !GetAtt EC2Instance.PublicDnsName
  
  WebsiteURL:
    Description: Website URL
    Value: !Sub 'http://${EC2Instance.PublicDnsName}'
  
  SSHCommand:
    Description: SSH Connection Command
    Value: !Sub 'ssh -i my-ec2-test-key.pem ec2-user@${EC2Instance.PublicIp}'
  
  AmiId:
    Description: AMI ID used for this instance
    Value: !Ref LatestAmiId</code></pre>
<p><strong>保存：</strong> <code>Ctrl + S</code></p>
<h3><span id="toc17">テンプレートの構造解説</span></h3>
<h4>Parameters（パラメータ）</h4>
<p><strong>KeyName：</strong></p>
<pre><code class="language-yaml">KeyName:
  Type: String
  Default: my-ec2-test-key</code></pre>
<ul>
<li>SSH接続用のキーペア名</li>
<li>既存のキーペアを指定</li>
</ul>
<p><strong>LatestAmiId：</strong></p>
<pre><code class="language-yaml">LatestAmiId:
  Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
  Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64</code></pre>
<ul>
<li><strong>自動取得</strong>：SSM Parameter Storeから最新のAmazon Linux 2023 AMI IDを取得</li>
<li><strong>メリット</strong>：AMI IDを手動で調べる必要がない</li>
</ul>
<h4>Resources（リソース）</h4>
<p><strong>1. EC2Role（IAMロール）</strong></p>
<pre><code class="language-yaml">EC2Role:
  Type: AWS::IAM::Role
  ManagedPolicyArns:
    - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore</code></pre>
<ul>
<li><strong>役割</strong>：EC2インスタンスに権限を付与</li>
<li><strong>権限</strong>：Session Manager接続を可能にする</li>
</ul>
<p><strong>2. EC2SecurityGroup（セキュリティグループ）</strong></p>
<pre><code class="language-yaml">SecurityGroupIngress:
  - IpProtocol: tcp
    FromPort: 22
    CidrIp: 0.0.0.0/0  # 初期設定：全公開</code></pre>
<ul>
<li><strong>SSH（ポート22）</strong>：SSH接続を許可</li>
<li><strong>HTTP（ポート80）</strong>：Webアクセスを許可</li>
<li><strong>注意</strong>：<code>0.0.0.0/0</code> は全公開設定。構築後に自分のIPに制限することを強く推奨</li>
</ul>
<p><strong>3. EC2Instance（メインのインスタンス）</strong></p>
<pre><code class="language-yaml">EC2Instance:
  Type: AWS::EC2::Instance
  Properties:
    ImageId: !Ref LatestAmiId
    InstanceType: t2.micro
    UserData:
      Fn::Base64: |
        #!/bin/bash
        yum update -y
        yum install -y httpd
        systemctl start httpd</code></pre>
<ul>
<li><strong>AMI</strong>：Amazon Linux 2023（最新版を自動取得）</li>
<li><strong>インスタンスタイプ</strong>：t2.micro（無料枠対象）</li>
<li><strong>UserData</strong>：Apache httpdを自動インストール・起動</li>
</ul>
<h4>Outputs（出力）</h4>
<pre><code class="language-yaml">Outputs:
  PublicIP:
    Value: !GetAtt EC2Instance.PublicIp
  WebsiteURL:
    Value: !Sub 'http://${EC2Instance.PublicDnsName}'</code></pre>
<ul>
<li>スタック作成後に表示される情報</li>
<li>SSH接続コマンドやWebサイトURLなど</li>
</ul>
<p> </p>
<h2><span id="toc18">5️⃣  CloudFormationスタックの作成</span></h2>
<h3><span id="toc19">スタック作成コマンド</span></h3>
<p><strong>VSCodeのターミナルで実行：</strong></p>
<pre><code class="language-bash">aws cloudformation create-stack \
  --stack-name ec2-test-stack \
  --template-body file://template.yaml \
  --region ap-northeast-1 \
  --capabilities CAPABILITY_IAM</code></pre>
<p><strong>Windowsの場合：</strong></p>
<pre><code class="language-bash">aws cloudformation create-stack ^
  --stack-name ec2-test-stack ^
  --template-body file://template.yaml ^
  --region ap-northeast-1 ^
  --capabilities CAPABILITY_IAM</code></pre>
<p><strong>コマンドの説明：</strong></p>
<ul>
<li><code>--stack-name ec2-test-stack</code>：スタック名（任意の名前）</li>
<li><code>--template-body file://template.yaml</code>：テンプレートファイルを指定</li>
<li><code>--region ap-northeast-1</code>：東京リージョン</li>
<li><code>--capabilities CAPABILITY_IAM</code>：IAMリソース作成の明示的な許可</li>
</ul>
<p><strong>出力例：</strong></p>
<pre><code class="language-json">{
    "StackId": "arn:aws:cloudformation:ap-northeast-1:123456789012:stack/ec2-test-stack/xxxxx"
}</code></pre>
<h3><span id="toc20">スタック作成の進行状況を確認</span></h3>
<p><strong>進行状況をリアルタイムで確認：</strong></p>
<pre><code class="language-bash">aws cloudformation describe-stacks \
  --stack-name ec2-test-stack \
  --query "Stacks[0].StackStatus" \
  --output text</code></pre>
<p><strong>ステータスの種類：</strong></p>
<ul>
<li><code>CREATE_IN_PROGRESS</code>：作成中</li>
<li><code>CREATE_COMPLETE</code>：作成完了</li>
<li><code>CREATE_FAILED</code>：作成失敗</li>
</ul>
<p><strong>完了まで約3〜5分かかります。</strong></p>
<h3><span id="toc21">スタック作成完了の確認</span></h3>
<p><strong>Outputs（出力情報）を取得：</strong></p>
<pre><code class="language-bash">aws cloudformation describe-stacks \
  --stack-name ec2-test-stack \
  --query "Stacks[0].Outputs" \
  --output table</code></pre>
<p><strong>出力例：</strong></p>
<pre><code class="language-plaintext">---------------------------------------------------------------------------------------
|                               DescribeStacks                                         |
+----------------------+---------------------------------------------------------------+
|     Description      |                      OutputValue                              |
+----------------------+---------------------------------------------------------------+
|  EC2 Instance ID     |  i-0123456789abcdef0                                          |
|  Public IP Address   |  x.x.x.x                                                      |
|  Public DNS Name     |  ec2-x-x-x-x.ap-northeast-1.compute.amazonaws.com             |
|  Website URL         |  http://ec2-x-x-x-x.ap-northeast-1.compute.amazonaws.com      |
|  SSH Connection      |  ssh -i my-ec2-test-key.pem ec2-user@x.x.x.x                  |
|  AMI ID              |  ami-0abcdef1234567890                                        |
+----------------------+---------------------------------------------------------------+</code></pre>
<p> </p>
<h2><span id="toc22">6️⃣  EC2インスタンスの動作確認</span></h2>
<h3><span id="toc23">Webサーバーへのアクセス</span></h3>
<p><strong>ブラウザでアクセス：</strong></p>
<pre><code class="language-plaintext">http://x.x.x.x</code></pre>
<p>（出力された PublicIP または WebsiteURL を使用）</p>
<p><strong>表示される内容：</strong></p>
<pre><code class="language-plaintext">Hello from Amazon Linux 2023!

Instance ID: i-0123456789abcdef0
Availability Zone: ap-northeast-1a</code></pre>
<h3><span id="toc24">SSH接続の確認</span></h3>
<p><strong>出力されたSSHコマンドを実行：</strong></p>
<pre><code class="language-bash">ssh -i my-ec2-test-key.pem ec2-user@x.x.x.x</code></pre>
<p><strong>初回接続時の確認：</strong></p>
<pre><code class="language-plaintext">The authenticity of host 'x.x.x.x' can't be established.
Are you sure you want to continue connecting (yes/no)?</code></pre>
<p>→ <code>yes</code> を入力</p>
<p><strong>接続成功：</strong></p>
<pre><code class="language-plaintext">   ,     #_
   ~\_  ####_        Amazon Linux 2023
  ~~  \_#####\
  ~~     \###|
  ~~       \#/ ___   https://aws.amazon.com/linux/amazon-linux-2023
   ~~       V~' '->
    ~~~         /
      ~~._.   _/
         _/ _/
       _/m/'

[ec2-user@ip-172-31-xx-xx ~]$</code></pre>
<p><strong>Apache確認：</strong></p>
<pre><code class="language-bash">sudo systemctl status httpd</code></pre>
<p><strong>切断：</strong></p>
<pre><code class="language-bash">exit</code></pre>
<p> </p>
<h2><span id="toc25">7️⃣  セキュリティグループの設定変更</span></h2>
<p>初期設定では <code>0.0.0.0/0</code>（全公開）になっているため、<strong>自分のIPアドレスのみに制限</strong>します。</p>
<h3><span id="toc26">自分のIPアドレスを確認</span></h3>
<p><strong>方法1：ブラウザで確認</strong></p>
<ul>
<li><a href="https://checkip.amazonaws.com/">https://checkip.amazonaws.com/</a> にアクセス</li>
</ul>
<p><strong>方法2：コマンドで確認</strong></p>
<pre><code class="language-bash">curl https://checkip.amazonaws.com/</code></pre>
<p><strong>出力例：</strong></p>
<pre><code class="language-plaintext">y.y.y.y</code></pre>
<h3><span id="toc27">セキュリティグループIDを取得</span></h3>
<pre><code class="language-bash">aws cloudformation describe-stacks \
  --stack-name ec2-test-stack \
  --query "Stacks[0].Resources[?ResourceType=='AWS::EC2::SecurityGroup'].PhysicalResourceId" \
  --output text</code></pre>
<p><strong>出力例：</strong></p>
<pre><code class="language-plaintext">sg-0123456789abcdef0</code></pre>
<h3><span id="toc28">インバウンドルールを更新</span></h3>
<p><strong>既存のルールを削除：</strong></p>
<pre><code class="language-bash"># セキュリティグループIDを変数に設定
SG_ID=sg-0123456789abcdef0

# SSH（ポート22）の既存ルールを削除
aws ec2 revoke-security-group-ingress \
  --group-id $SG_ID \
  --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges='[{CidrIp=0.0.0.0/0}]'

# HTTP（ポート80）の既存ルールを削除
aws ec2 revoke-security-group-ingress \
  --group-id $SG_ID \
  --ip-permissions IpProtocol=tcp,FromPort=80,ToPort=80,IpRanges='[{CidrIp=0.0.0.0/0}]'</code></pre>
<p><strong>自分のIPで新しいルールを追加：</strong></p>
<pre><code class="language-bash"># 自分のIPアドレス（例）
MY_IP=y.y.y.y/32

# SSH（ポート22）を自分のIPのみ許可
aws ec2 authorize-security-group-ingress \
  --group-id $SG_ID \
  --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges="[{CidrIp=$MY_IP,Description='My IP only'}]"

# HTTP（ポート80）を自分のIPのみ許可
aws ec2 authorize-security-group-ingress \
  --group-id $SG_ID \
  --ip-permissions IpProtocol=tcp,FromPort=80,ToPort=80,IpRanges="[{CidrIp=$MY_IP,Description='My IP only'}]"</code></pre>
<p><strong>確認：</strong></p>
<pre><code class="language-bash">aws ec2 describe-security-groups --group-ids $SG_ID</code></pre>
<p> </p>
<h2><span id="toc29">8️⃣  スタックの削除（リソースのクリーンアップ）</span></h2>
<h3><span id="toc30">インスタンスを停止</span></h3>
<p><strong>停止コマンド：</strong></p>
<pre><code class="language-bash"># インスタンスIDを取得
INSTANCE_ID=$(aws cloudformation describe-stacks \
  --stack-name ec2-test-stack \
  --query "Stacks[0].Outputs[?OutputKey=='InstanceId'].OutputValue" \
  --output text)

# インスタンスを停止
aws ec2 stop-instances --instance-ids $INSTANCE_ID</code></pre>
<p><strong>確認：</strong></p>
<pre><code class="language-bash">aws ec2 describe-instances \
  --instance-ids $INSTANCE_ID \
  --query "Reservations[0].Instances[0].State.Name" \
  --output text</code></pre>
<h3><span id="toc31">スタックを削除</span></h3>
<p><strong>削除コマンド：</strong></p>
<pre><code class="language-bash">aws cloudformation delete-stack --stack-name ec2-test-stack</code></pre>
<p><strong>削除の進行状況を確認：</strong></p>
<pre><code class="language-bash">aws cloudformation describe-stacks \
  --stack-name ec2-test-stack \
  --query "Stacks[0].StackStatus" \
  --output text</code></pre>
<p><strong>完全に削除されるまで約5分かかります。</strong></p>
<p><strong>削除完了の確認（エラーが表示されればOK）：</strong></p>
<pre><code class="language-bash">aws cloudformation describe-stacks --stack-name ec2-test-stack</code></pre>
<p><strong>エラー例：</strong></p>
<pre><code class="language-plaintext">An error occurred (ValidationError) when calling the DescribeStacks operation: 
Stack with id ec2-test-stack does not exist</code></pre>
<p> </p>
<h2><span id="toc32">9️⃣  トラブルシューティング</span></h2>
<h3><span id="toc33">スタック作成が失敗する</span></h3>
<p><strong>原因1：キーペアが存在しない</strong></p>
<p><strong>確認：</strong></p>
<pre><code class="language-bash">aws ec2 describe-key-pairs --key-names my-ec2-test-key</code></pre>
<p><strong>解決：</strong><br />キーペアを作成するか、テンプレートの <code>KeyName</code> を修正</p>
<p><strong>原因2：IAM権限不足</strong></p>
<p><strong>エラー例：</strong></p>
<pre><code class="language-plaintext">User is not authorized to perform: iam:CreateRole</code></pre>
<p><strong>解決：</strong><br />IAM権限を持つユーザーで実行するか、管理者に依頼</p>
<h3><span id="toc34">SSH接続ができない</span></h3>
<p><strong>原因1：セキュリティグループの設定</strong></p>
<p><strong>確認：</strong></p>
<pre><code class="language-bash">aws ec2 describe-security-groups --group-ids $SG_ID</code></pre>
<p>自分のIPアドレスが許可されているか確認</p>
<p><strong>原因2：キーペアファイルの権限</strong></p>
<p><strong>エラー例：</strong></p>
<pre><code class="language-plaintext">WARNING: UNPROTECTED PRIVATE KEY FILE!</code></pre>
<p><strong>解決：</strong></p>
<pre><code class="language-bash">chmod 400 my-ec2-test-key.pem</code></pre>
<h3><span id="toc35">Webページが表示されない</span></h3>
<p><strong>原因：User Dataの実行に時間がかかる</strong></p>
<p><strong>確認（SSH接続して）：</strong></p>
<pre><code class="language-bash">sudo tail -f /var/log/cloud-init-output.log</code></pre>
<p>Apache のインストールが完了するまで待つ（通常2〜3分）</p>
<p> </p>
<h2><span id="toc36">🔟 まとめ</span></h2>
<p>この記事では、VSCodeとCloudFormationを使ったEC2構築の実践的な手順を解説しました。</p>
<h3><span id="toc37">学んだこと</span></h3>
<ul>
<li>✅ <strong>CloudFormationテンプレートの構造</strong>：YAML形式でインフラを定義</li>
<li>✅ <strong>AWS CLIでのスタック管理</strong>：作成・更新・削除の一連の流れ</li>
<li>✅ <strong>セキュリティグループの適切な設定</strong>：全公開から自分のIPに制限</li>
<li>✅ <strong>User Dataでの自動化</strong>：Apache httpdの自動インストール</li>
</ul>
<h3><span id="toc38">CloudFormationのメリット再確認</span></h3>
<ol>
<li><strong>再現性</strong>：何度でも同じ環境を作成可能</li>
<li><strong>バージョン管理</strong>：Gitで履歴管理</li>
<li><strong>自動化</strong>：CI/CDパイプラインに組み込める</li>
<li><strong>ドキュメント化</strong>：コードがそのままドキュメント</li>
</ol>
<h3><span id="toc39">次のステップ</span></h3>
<ul>
<li><strong>テンプレートのカスタマイズ</strong>：EBSボリューム追加、RDS連携など</li>
<li><strong>GitHub管理</strong>：テンプレートをGitHubでバージョン管理</li>
<li><strong>CI/CD構築</strong>：GitHub Actionsで自動デプロイ</li>
<li><strong>複数環境管理</strong>：開発・ステージング・本番環境の切り分け</li>
</ul>
<hr>
<p><!-- START MoshimoAffiliateEasyLink --><script type="text/javascript">(function(b,c,f,g,a,d,e){b.MoshimoAffiliateObject=a;b[a]=b[a]||function(){arguments.currentScript=c.currentScript||c.scripts[c.scripts.length-2];(b[a].q=b[a].q||[]).push(arguments)};c.getElementById(a)||(d=c.createElement(f),d.src=g,d.id=a,e=c.getElementsByTagName("body")[0],e.appendChild(d))})(window,document,"script","//dn.msmstatic.com/site/cardlink/bundle.js?20220329","msmaflink");msmaflink({"n":"AWS運用入門 改訂第2版 押さえておきたいAWSの基本と運用ノウハウ [AWS深掘りガイド]","b":"SBクリエイティブ","t":"","d":"https:\/\/m.media-amazon.com","c_p":"\/images\/I","p":["\/51AAOubymTL._SL500_.jpg","\/51VMG6YKHdL._SL500_.jpg","\/41EdPB8azAL._SL500_.jpg","\/41v2JFE-9jL._SL500_.jpg","\/41FEEqR-yDL._SL500_.jpg","\/41JfZAdnTPL._SL500_.jpg","\/41vGK0czQrL._SL500_.jpg","\/41-SnYtz2aL._SL500_.jpg","\/41sPrV5fi3L._SL500_.jpg","\/41p7JtvYJ1L._SL500_.jpg","\/4169GVNTs8L._SL500_.jpg","\/41BPI5HP3zL._SL500_.jpg","\/41QOyk60CYL._SL500_.jpg","\/41APjk6FphL._SL500_.jpg","\/41ezKUu7VRL._SL500_.jpg","\/41A1n3K+r5L._SL500_.jpg","\/41aY2T8lEOL._SL500_.jpg","\/419Ca1V6HZL._SL500_.jpg","\/41zQkYyLPzL._SL500_.jpg","\/41YpHcyxiTL._SL500_.jpg","\/41-tKN5mt6L._SL500_.jpg","\/419Mv6m55IL._SL500_.jpg"],"u":{"u":"https:\/\/www.amazon.co.jp\/dp\/4815631085","t":"amazon","r_v":""},"v":"2.1","b_l":[{"id":1,"u_tx":"Amazonで見る","u_bc":"#f79256","u_url":"https:\/\/www.amazon.co.jp\/dp\/4815631085","a_id":1384942,"p_id":170,"pl_id":27060,"pc_id":185,"s_n":"amazon","u_so":1},{"id":2,"u_tx":"楽天市場で見る","u_bc":"#f76956","u_url":"https:\/\/search.rakuten.co.jp\/search\/mall\/AWS%E9%81%8B%E7%94%A8%E5%85%A5%E9%96%80%20%E6%94%B9%E8%A8%82%E7%AC%AC2%E7%89%88%20%E6%8A%BC%E3%81%95%E3%81%88%E3%81%A6%E3%81%8A%E3%81%8D%E3%81%9F%E3%81%84AWS%E3%81%AE%E5%9F%BA%E6%9C%AC%E3%81%A8%E9%81%8B%E7%94%A8%E3%83%8E%E3%82%A6%E3%83%8F%E3%82%A6%20%5BAWS%E6%B7%B1%E6%8E%98%E3%82%8A%E3%82%AC%E3%82%A4%E3%83%89%5D\/","a_id":1384917,"p_id":54,"pl_id":27059,"pc_id":54,"s_n":"rakuten","u_so":2},{"id":3,"u_tx":"Yahoo!ショッピングで見る","u_bc":"#66a7ff","u_url":"https:\/\/shopping.yahoo.co.jp\/search?first=1\u0026p=AWS%E9%81%8B%E7%94%A8%E5%85%A5%E9%96%80%20%E6%94%B9%E8%A8%82%E7%AC%AC2%E7%89%88%20%E6%8A%BC%E3%81%95%E3%81%88%E3%81%A6%E3%81%8A%E3%81%8D%E3%81%9F%E3%81%84AWS%E3%81%AE%E5%9F%BA%E6%9C%AC%E3%81%A8%E9%81%8B%E7%94%A8%E3%83%8E%E3%82%A6%E3%83%8F%E3%82%A6%20%5BAWS%E6%B7%B1%E6%8E%98%E3%82%8A%E3%82%AC%E3%82%A4%E3%83%89%5D","a_id":1466950,"p_id":1225,"pl_id":27061,"pc_id":1925,"s_n":"yahoo","u_so":3}],"eid":"E8MM1","s":"s"});</script></p>
<div id="msmaflink-E8MM1">リンク</div>
<p><!-- MoshimoAffiliateEasyLink END --></p>
<p><strong>参考リンク：</strong></p>
<ul>
<li><a href="https://docs.aws.amazon.com/ja_jp/cloudformation/">AWS CloudFormation 公式ドキュメント</a></li>
<li><a href="https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/template-reference.html">CloudFormation テンプレートリファレンス</a></li>
<li><a href="https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/UserGuide/user-data.html">EC2 User Data スクリプト</a></li>
</ul>
<p><strong>関連記事：</strong></p>
<ul>
<li><a href="https://caymezon.com/vscode-aws-ec2-guide/">【初心者向け】VSCodeとAWS CLIで始める！AWS EC2環境構築とGit連携の完全ガイド</a></li>
<li><a href="https://caymezon.com/aws-ec2-keypair-creation-guide/">【AWS初心者向け】EC2キーペア作成の完全ガイド</a></li>
</ul>
<p><strong>最終更新：</strong> 2026年1月11日</p><p>The post <a href="https://caymezon.com/aws-ec2-cloudformation-vscode-guide/">【実践】VSCodeとCloudFormationで学ぶAWS EC2構築｜コードでインフラ管理</a> first appeared on <a href="https://caymezon.com">CayTech Lab</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://caymezon.com/aws-ec2-cloudformation-vscode-guide/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
