# Terraformの導入 --- ## 目的 - terraformの基本的な使い方を知る --- ## IAMユーザーの作成、認証情報の生成 - IAMユーザーの作成 - https://qiita.com/kzykmyzw/items/ca0c3276dfebb401f7d8 --- # 全体像  --- # 完成図 - Index.htmlを表示するだけの単純なWebサーバーをデプロイします  --- # 開発環境  --- # Cloud9の作成 - Create Environment  - 適当な名前を入力  --- - t3.smallを選択し、後はデフォルトで次へ   --- - 「Create environment」し、「Open IDE」  --- - `which terraform` - `terraform -v` - バージョンが1.0以下ならばLinux版terraformをダウンロードする - https://www.terraform.io/downloads.html - 解凍し、/usr/binに格納 --- # Cloud9の設定 - Preferenceから「AWS Managed Temporary Credeintials」を無効化  --- ## IAMユーザーから認証情報を生成  --- ## アクセスキーの作成  --- ## CodeCommit認証情報の作成  --- - `aws configure`でCloud9のローカルにシークレットIDとシークレットキーを保存 - `/home/ec2-user/.aws/credentials`を編集して以下を追記 ``` [default] aws_access_key_id = ****** aws_secret_access_key = ******** ``` --- `vi ~/.aws/config` 以下を入力 ``` [default] output = json region = ap-northeast-1 ``` --- - 確認 - `aws s3 ls`で`aws-training-tfstate-84`バケットが見えればOK --- # リポジトリのクローン - `codecommit::ap-northeast-1://terraform-training` - `git switch -c 名前`で自分用のブランチを切る --- - 名前は`名前-苗字`のローマ字 --- # Terraformの構成を理解する - terraformは初期化した際に配下のtfファイルをすべて読み込む - tfvarsファイルは、同じディレクトリの変数の値として読み込まれる - terraform.tfvarsファイルは、ルートディレクトリにある場合自動的に変数の値として読み込まれる  --- # Terraformを使用してみる - backend.tfで状態ファイルをS3にアップロードする ```backend.tf terraform { backend "s3" { bucket = "aws-training-tfstate-74" key = "takaba/terraform.tfstate" profile = "default" region = "ap-northeast-1" } } ``` ※あらかじめS3バケットを作成しておく --- - `backend.tf`を変更する - key = "××/terraform.tfstate"の部分を自分の名前に変更 - bucket = "aws-training-tfstate-**(アカウントIDの先頭2文字)" --- terraform.tfvars ``` key_name = "terraform-training" public_key_path = "/home/ec2-user/.ssh/authorized_keys" my_localhost = ["IP/32"] aws_profile = "devops_stg" my_name = "ryo-takaba" ``` - 自分のIP - [確認くん](https://www.ugtop.com/spill.shtml) --- - `terraform init`でS3のバケット内の自分のキー名のプレフィクスのtfstateファイルができていることを確認  ---  --- ## ①VPCの作成 main.tfの一番下に以下を追記してください ``` # VPC resource "aws_vpc" "training" { cidr_block = "10.0.0.0/16" enable_dns_support = true enable_dns_hostnames = true tags = { Name = "training-vpc" } } ``` ---  --- #### terraformで作成するリソースを確認する - `terraform plan` - 事前に作成するリソースを確認する。 #### 実際に作成する - `terraform apply` - 作成を実行する - 上記で問題なければ実行して実際に作成 --- ## Terraformで変数を使う main.tfの5行目に以下を追記してください ``` variable "my_name" { default = "自分の名前" } ``` --- ## Terraformで変数を使う - VPCの記述を以下のように変更してください ``` # VPC resource "aws_vpc" "training" { cidr_block = "10.0.0.0/16" enable_dns_support = true enable_dns_hostnames = true tags = { Name = "training-vpc-${var.my_name}" } } ``` #### 変更箇所 <div class="flexbox"> <div>変更前:Name = "training-vpc"</div> <div>変更前:Name = <span class="text-color">"training-vpc-${var.my_name}"</span></div> </div> --- ## ②サブネットの作成 ``` # サブネット resource "aws_subnet" "public-1a" { vpc_id = aws_vpc.training.id cidr_block = "10.0.1.0/24" availability_zone = "ap-northeast-1a" map_public_ip_on_launch = true tags = { Name = "public-1a" } } ``` ---  --- ### 残りのサブネットを追加 ``` # サブネット resource "aws_subnet" "public-1c" { vpc_id = aws_vpc.training.id cidr_block = "10.0.2.0/24" availability_zone = "ap-northeast-1c" map_public_ip_on_launch = true tags = { Name = "public-1c" } } resource "aws_subnet" "private-1a" { vpc_id = aws_vpc.training.id cidr_block = "10.0.3.0/24" availability_zone = "ap-northeast-1a" map_public_ip_on_launch = true tags = { Name = "private-1a" } } # サブネット resource "aws_subnet" "private-1c" { vpc_id = aws_vpc.training.id cidr_block = "10.0.4.0/24" availability_zone = "ap-northeast-1c" map_public_ip_on_launch = true tags = { Name = "private-1c" } } ``` ---  --- ## ③インターネットゲートウェイを作る ``` # インターネットゲートウェイ resource "aws_internet_gateway" "training" { vpc_id = aws_vpc.training.id tags = { Name = "training-igw" } } ``` ---  --- ## ④ルートテーブルを作る ``` # ルートテーブル resource "aws_route_table" "training" { vpc_id = aws_vpc.training.id route { cidr_block = "0.0.0.0/0" gateway_id = aws_internet_gateway.training.id } tags = { Name = "training-route-table" } } resource "aws_route_table_association" "training" { subnet_id = aws_subnet.public-1a.id route_table_id = aws_route_table.training.id } ``` ---  --- ## ⑤セキュリティグループを作る ``` # セキュリティグループ resource "aws_security_group" "web" { name = "web" vpc_id = aws_vpc.training.id ingress { description = "allow http" from_port = "80" to_port = "80" protocol = "tcp" cidr_blocks = var.my_localhost } ingress { description = "allow ssh" from_port = "22" to_port = "22" protocol = "tcp" cidr_blocks = var.my_localhost } egress { description = "allow https" from_port = "443" to_port = "443" protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { description = "allow http" from_port = "80" to_port = "80" protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } tags = { Name = "training-server-${var.my_name}" } } ``` ---  --- ## 変数を追加する main.tfの8行目に以下を追記してください ``` variable "my_localhost" { default = "自分のIP/32" } ``` ### 自分のIP 確認くん(https://www.ugtop.com/spill.shtml) --- ## 変数を整理する 1. main.tfと同じフォルダにvariables.tfを作成してください 2. 以下の内容を張り付けてください 3. main.tfの同じ内容は削除してください ``` variable "my_name" { default = "自分の名前" } variable "my_localhost" { default = "自分のIP/32" } ``` --- ## ⑥EC2インスタンスを作成する ``` # EC2インスタンス resource "aws_instance" "terraform-server" { ami = data.aws_ami.amazon_linux.id instance_type = "t3.micro" subnet_id = aws_subnet.public-1a.id user_data = file("./files/user_data.sh") key_name = var.key_name vpc_security_group_ids = [ aws_security_group.web.id ] tags = { Name = "training-server-${var.my_name}" } } ``` ---  --- ## 他の場所から情報を取得する - main.tfと同じフォルダにdata.tfを作成し以下の内容を張り付けてください ``` data "aws_ami" "amazon_linux" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-gp2"] } } ``` --- ## ⑦EC2インスタンスにApahceをインストールする 1. main.tfと同じフォルダにfilesディレクトリを作成 2. user_data.shとしてfilesフォルダに以下を保存 ``` #!/bin/bash echo "installing apache" sudo yum update -y sudo yum install -y httpd sudo systemctl start httpd sudo systemctl enable httpd ``` ---  --- 2. main.tfのEC2に以下を追記 `subnet_id = aws_subnet.public-1a.id`の1行下に追記 ``` user_data = file("./files/user_data.sh") ``` --- ## ⑧index.htmlをデプロイする - user_data.shの末尾に以下の1行を追加 ``` echo "hello terraform" > /var/www/html/index.html ``` ---  --- ## 確認 - http://パブリックIPv4アドレス/index.htmlにアクセス  - 成功すれば下のように表示される  --- ### user_dataが動かない場合 - https://qiita.com/polarbear08/items/4031e5f8e494e8cf3fee --- # 完了です ## お疲れ様でした --- ## appendix1 ### セッションマネージャーでアクセスできるEC2を作成する。 ### 事前準備 - `https://s3.amazonaws.com/session-manager-downloads/plugin/latest/windows/SessionManagerPluginSetup.exe`をインストールしてシェルを再起動する --- ### ポイントは以下 - https://dev.classmethod.jp/articles/troubleshooting-ssm-session-manager-configuration/#toc-7 #### パブリック側に建てる場合 - VPCエンドポイントを作成する - インスタンスからのアウトバウンドを0.0.0.0/0に設定する - ルートテーブルのターゲットにS3エンドポイントを設定する #### プライベート側に建てる場合 - NATゲートウェイを作成する - NATがなくてもパブリックIPアドレスを割り当てれば疎通可能?要検証 - VPCエンドポイントを作成する - 4つすべて立てないと疎通しないので注意 - インスタンスからのアウトバウンドを0.0.0.0/0に設定する - ルートテーブルのターゲットにS3エンドポイントを設定する - NATゲートウェイはSSMでの接続には不要 --- - IAMのポリシーのjsonの書き方はいくつかあるが、ファイルで外だしして`iam_policy_document`で読み込む - https://dev.classmethod.jp/articles/writing-iam-policy-with-terraform/ --- - 起動シェルをbashにしたい場合は、ブラウザコンソールで`/bin/bash`を設定する - `sudo su - ec2-user`でもよい <style> .text-color { color: #0044ff; } .flexbox { display: flex; flex-direction: column; align-items: flex-start; } code { background-color: gray; color: #333333; font-family: consolas; } li { line-height: 2; } .hljs { margin-top: 20px; } </style> ### 参考 https://qiita.com/charon/items/58c3ad20232c74a6dc01 ## appendix2 ### GRCでcodecommitにアクセス - git-remote-codecommitが入っているか確認 - `which git-remote-codecommit` - なかったらインストール - `pip3 install git-remote-codecommit` - 現在のoriginをGRC用のURLに変更 - `git remote set-url origin codecommit::ap-northeast-1://terraform-training`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up