0
2

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 3 years have passed since last update.

CloudformationでEC2を作成してnginxをインストールするメモ

Last updated at Posted at 2020-11-29

はじめに

自分用のメモです
設定ファイルをどうしようか悩みました
最終的にS3に置いてコピーすることにしました

前提

  • VPCは既存であるものをつかいます(qiitaで検索すればcloudformationでVPCとサブネットの作成する例はいろいろでてきます)
  • 使うイメージはamazon linux
  • nginx のインストールをします
  • nginx の root を変更して、index.html を S3 コピーします
  • SSLの設定はしません

手順概略

  1. 手動で s3のバケット を作成
  2. nginxの設定ファイルを作成して作ったバケットにアップロード
  3. キーペアを作成(EC2にログインする用)
  4. cloudformationのスタックを作成
  5. 確認する

手順詳細

1. 手動で s3のバケット を作成

EC2を作成するリージョンと同じところに作ります

2. nginxの設定ファイルを作成して作ったバケットにアップロード

ここらへんから自分の目的にあったものを探して設定ファイルを作成してアップロードします

nginx.conf の例
nginx.conf

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        # root         /usr/share/nginx/html;
        root         /usr/share/nginx/html2;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

}

index.html

lnsw test

3. キーペアを作成(EC2にログインする用)

ここで作成します
image.png

4. cloudformationのスタックを作成

入力するパラメータは、VPC、S3バケット、キーペアの3つです

テンプレートは以下になります

ソース
ec2-template.yml
AWSTemplateFormatVersion: "2010-09-09"

# 変数
Parameters:
  # VPCは既存を使う
  EC2VpcId:
    Type: String
    Default: "vpc-999999"

  EC2Keypair:
    Type: String
    Default: "your-key-pair"

  S3ContainingNgnxConf:
    Type: String
    Default: "your-nginx-setting"

Resources:
  # EC2の実行ロール
  EC2IAMRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Service:
                - "ec2.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      Path: "/"

  S3AccessPolicies:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: s3access
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Action:
              - "s3:ListAllMyBuckets"
              - "s3:GetBucketLocation"
            Resource: "arn:aws:s3:::*"
          - Effect: Allow
            Action: "*"
            Resource:
              - !Sub "arn:aws:s3:::${S3ContainingNgnxConf}"
              - !Sub "arn:aws:s3:::${S3ContainingNgnxConf}/*"
      Roles:
        - !Ref EC2IAMRole

  S3AccessInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: "/"
      Roles:
        - !Ref EC2IAMRole

  # EC2
  EC2Instance:
    Type: "AWS::EC2::Instance"
    Properties:
      ImageId: "ami-000279759c4819ddf"
      InstanceType: "t2.nano"
      KeyName: !Ref EC2Keypair
      IamInstanceProfile: !Ref S3AccessInstanceProfile
      SecurityGroupIds:
        - !Ref EC2SecurityGroup
      Tags:
        - Key: "Name"
          Value: "LnswEC2"
          ## nginx インストール
      UserData: !Base64
        Fn::Sub: |
          #!/bin/bash
          sudo amazon-linux-extras install nginx1
          sudo systemctl enable nginx
          sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.org
          # 下記でS3にあるnginxの設定ファイルで上書きします
          sudo aws s3 cp s3://${S3ContainingNgnxConf}/nginx.conf /etc/nginx/nginx.conf > /home/ec2-user/log.txt
          # 公開するディレクトリの作成と公開ファイルのコピー
          sudo mkdir -p /usr/share/nginx/html2
          sudo aws s3 cp s3://${S3ContainingNgnxConf}/index.html /usr/share/nginx/html2/index.html >> /home/ec2-user/log.txt
          sudo systemctl start nginx

  # Elastic IP
  ElasticIp:
    Type: AWS::EC2::EIP
    Properties:
      InstanceId: !Ref EC2Instance
      Domain: vpc

  # セキュリティグループ
  EC2SecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "LnswEC2"
      VpcId: !Ref EC2VpcId
      GroupName: "LnswEC2"
      SecurityGroupIngress:
        - CidrIp: "0.0.0.0/0"
          FromPort: 22
          IpProtocol: "tcp"
          ToPort: 22
        - CidrIp: "0.0.0.0/0"
          FromPort: 80
          IpProtocol: "tcp"
          ToPort: 80
        - CidrIpv6: "::/0"
          FromPort: 80
          IpProtocol: "tcp"
          ToPort: 80
        # SSLを利用するときはnginxの設定をした後に下記を有効にする
        # - CidrIp: "0.0.0.0/0"
        #   FromPort: 443
        #   IpProtocol: "tcp"
        #   ToPort: 443
        # - CidrIpv6: "::/0"
        #   FromPort: 443
        #   IpProtocol: "tcp"
        #   ToPort: 443
      Tags:
        - Key: "Name"
          Value: "LnswEC2"

5. 確認する

作成したスタックのEC2のIPをブラウザで開くと確認できます
image.png

参考

CloudFormationでEC2にIAMロールを付与する
https://qiita.com/predora005/items/480dc3db258e84fcee81

S3からファイルがコピーできなくて困っていたので、とても参考になりました

AWS CloudFormationでEC2にミドルまでセットアップする
https://qiita.com/algi_nao/items/8898afed7ce723ea7fbb

おわりに

もっと複雑な設定をするにはAnsibleを利用したほうがいいのでしょうか?

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?