###### tags: `AWS` `Terraform`
# Terraformことはじめ
環境: CentOS7
Terraform: v0.12.24
**Terraform0.12では言語使用が拡張されたため、0.11以前のバージョンと互換性がない**
## Setup
1. terraform用IAM作成
| 項目 | 設定値 |
| -------- | -------- |
| ユーザー名 | terraform |
| AWS アクセスの種類 | プログラムによるアクセス - アクセスキーを使用 |
| アクセス権限の境界 | アクセス権限の境界が設定されていません |
| 管理ポリシー | AdministratorAccess |
2. AWS CLI
**install**
```shell-session
# pip3 install awscli --upgrade
# aws --version
aws-cli/1.18.26 Python/3.6.8 Linux/3.10.0-1062.12.1.el7.x86_64 botocore/1.15.26
```
**クレデンシャル**
```shell-session
# export AWS_ACCESS_KEY_ID=<アクセスキー>
# export AWS_SECRET_ACCESS_KEY=<シークレットキー>
# export AWS_DEFAULT_REGION=ap-northeast-1 // アジアパシフィック (東京)
// 設定確認
# aws sts get-caller-identity --query Account --output text
<AWSアカウントID>
```
3. Terraformのインストール
https://www.terraform.io/downloads.html
```shell-session
// 最新版のインストール
# wget https://releases.hashicorp.com/terraform/0.12.24/terraform_0.12.24_linux_amd64.zip
// コマンドとして配置
# unzip terraform_0.12.24_linux_amd64.zip -d /usr/local/bin/
Archive: terraform_0.12.24_linux_amd64.zip
inflating: /usr/local/bin/terraform
// version確認
# terraform -v
Terraform v0.12.24
```
4. git-secrets
クレデンシャル流出防止
```shell-session
# git clone https://github.com/awslabs/git-secrets.git
# cd git-secrets/
# make install
# cd
# git secrets --register-aws --global
# git secrets --install ~/.git-templates/git-secrets
? Installed commit-msg hook to /root/.git-templates/git-secrets/hooks/commit-msg
? Installed pre-commit hook to /root/.git-templates/git-secrets/hooks/pre-commit
? Installed prepare-commit-msg hook to /root/.git-templates/git-secrets/hooks/prepare-commit-msg
# git config --global init.templatedir '~/.git-templates/git-secrets'
```
(おまけ: 秘匿情報をCommitしようとすると...)
```shell-session
# touch secret.txt
# echo "aws_secret_access_key = ABcDe1F2hIjkl3nop45sTUv6XYz7aBcDEFghIJKL" > secret.txt
# git add .
# git commit -m "secret-key"
secret.txt:1:aws_secret_access_key = ABcDe1F2hIjkl3nop45sTUv6XYz7aBcDEFghIJKL
[ERROR] Matched one or more prohibited patterns
Possible mitigations:
- Mark false positives as allowed using: git config --add secrets.allowed ...
- Mark false positives as allowed by adding regular expressions to .gitallowed at repository's root directory
- List your configured patterns: git config --get-all secrets.patterns
- List your configured allowed patterns: git config --get-all secrets.allowed
- List your configured allowed patterns in .gitallowed at repository's root directory
- Use --no-verify if this is a one-time false positive
```
## EC2インスタンス(作成 - 設定変更・再作成 - 削除)
### 作成
1. リソース作成
```bash
# vim main.tf
resource "aws_instance" "example" {
ami = "ami-02ddf94e5edc8e904" # Amazon Linux AMI 2018.03.0 (HVM), SSD Volume Type
instance_type = "t2.micro"
}
```
2. リソースに必要なバイナリファイルのダウンロード
`Terraform has been successfully initialized!`が出力されることを確認
```bash
# terraform init
Initializing the backend...
Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.54.0...
The following providers do not have any version constraints in configuration,
so the latest version was installed.
To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.
* provider.aws: version = "~> 2.54"
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
```
3. terraform plan
実行時の挙動確認
```bash
# terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.example will be created
+ resource "aws_instance" "example" {
+ ami = "ami-02ddf94e5edc8e904"
+ arn = (known after apply)
+ associate_public_ip_address = (known after apply)
+ availability_zone = (known after apply)
+ cpu_core_count = (known after apply)
+ cpu_threads_per_core = (known after apply)
+ get_password_data = false
+ host_id = (known after apply)
+ id = (known after apply)
+ instance_state = (known after apply)
+ instance_type = "t2.macro"
+ ipv6_address_count = (known after apply)
+ ipv6_addresses = (known after apply)
+ key_name = (known after apply)
+ network_interface_id = (known after apply)
+ password_data = (known after apply)
+ placement_group = (known after apply)
+ primary_network_interface_id = (known after apply)
+ private_dns = (known after apply)
+ private_ip = (known after apply)
+ public_dns = (known after apply)
+ public_ip = (known after apply)
+ security_groups = (known after apply)
+ source_dest_check = true
+ subnet_id = (known after apply)
+ tenancy = (known after apply)
+ volume_tags = (known after apply)
+ vpc_security_group_ids = (known after apply)
+ ebs_block_device {
+ delete_on_termination = (known after apply)
+ device_name = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ snapshot_id = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (known after apply)
}
+ ephemeral_block_device {
+ device_name = (known after apply)
+ no_device = (known after apply)
+ virtual_name = (known after apply)
}
+ network_interface {
+ delete_on_termination = (known after apply)
+ device_index = (known after apply)
+ network_interface_id = (known after apply)
}
+ root_block_device {
+ delete_on_termination = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (known after apply)
}
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
```
4. リソース作成
```bash
# terraform apply
......
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: # yesと入力するとリソースが作成される
aws_instance.example: Creating...
aws_instance.example: Still creating... [10s elapsed]
aws_instance.example: Still creating... [20s elapsed]
aws_instance.example: Creation complete after 27s [id=i-06dc4289454480971]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
```
AWSマネジメントコンソール上でも確認できる

### 設定変更・再作成
#### リソース設定変更
```bash
# vim main.tf
resource "aws_instance" "example" {
ami = "ami-02ddf94e5edc8e904" # Amazon Linux AMI 2018.03.0 (HVM), SSD Volume Type
instance_type = "t2.micro"
tags = {
Name = "example"
}
}
# terraform apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
~ update in-place
Terraform will perform the following actions:
# aws_instance.example will be updated in-place
~ resource "aws_instance" "example" {
ami = "ami-02ddf94e5edc8e904"
arn = "arn:aws:ec2:ap-northeast-1:488656661057:instance/i-0fe53d6817ed0dff9"
associate_public_ip_address = true
availability_zone = "ap-northeast-1a"
cpu_core_count = 1
cpu_threads_per_core = 1
disable_api_termination = false
ebs_optimized = false
get_password_data = false
hibernation = false
id = "i-0fe53d6817ed0dff9"
instance_state = "running"
instance_type = "t2.micro"
ipv6_address_count = 0
ipv6_addresses = []
monitoring = false
primary_network_interface_id = "eni-0e25fc185305b62f5"
private_dns = "ip-172-31-38-133.ap-northeast-1.compute.internal"
private_ip = "172.31.38.133"
public_dns = "ec2-54-238-133-242.ap-northeast-1.compute.amazonaws.com"
public_ip = "54.238.133.242"
security_groups = [
"default",
]
source_dest_check = true
subnet_id = "subnet-e623ecae"
~ tags = {
+ "Name" = "example"
}
tenancy = "default"
volume_tags = {}
vpc_security_group_ids = [
"sg-774fa903",
]
credit_specification {
cpu_credits = "standard"
}
root_block_device {
delete_on_termination = true
encrypted = false
iops = 100
volume_id = "vol-0c18661555b5f2b20"
volume_size = 8
volume_type = "gp2"
}
}
Plan: 0 to add, 1 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: # yes
aws_instance.example: Modifying... [id=i-0fe53d6817ed0dff9]
aws_instance.example: Modifications complete after 4s [id=i-0fe53d6817ed0dff9]
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
```
**aws_instance.example will be updated in-place**
AWSマネジメントコンソールにも反映されている。

### リソースの再作成
```bash
# vim main.tf
resource "aws_instance" "example" {
ami = "ami-02ddf94e5edc8e904" # Amazon Linux AMI 2018.03.0 (HVM), SSD Volume Type
instance_type = "t2.micro"
user_data = <<EOF
#!/bin/bash
yum install -y httpd
systemctl start httpd.service
EOF
}
```
`user_data`でリソース作成時に実行したい内容を読み込み?
ファイルの指定も可(`main.tf`と同一ディレクトリにスクリプトを配置)
**疑問:権限は何で実行されるのか。。(root?)**
```bash
# terraform apply
aws_instance.example: Refreshing state... [id=i-0fe53d6817ed0dff9]
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement
Terraform will perform the following actions:
# aws_instance.example must be replaced
-/+ resource "aws_instance" "example" {
ami = "ami-02ddf94e5edc8e904"
~ arn = "arn:aws:ec2:ap-northeast-1:488656661057:instance/i-0fe53d6817ed0dff9" -> (known after apply)
~ associate_public_ip_address = true -> (known after apply)
~ availability_zone = "ap-northeast-1a" -> (known after apply)
~ cpu_core_count = 1 -> (known after apply)
~ cpu_threads_per_core = 1 -> (known after apply)
- disable_api_termination = false -> null
- ebs_optimized = false -> null
get_password_data = false
- hibernation = false -> null
+ host_id = (known after apply)
~ id = "i-0fe53d6817ed0dff9" -> (known after apply)
~ instance_state = "running" -> (known after apply)
instance_type = "t2.micro"
~ ipv6_address_count = 0 -> (known after apply)
~ ipv6_addresses = [] -> (known after apply)
+ key_name = (known after apply)
- monitoring = false -> null
+ network_interface_id = (known after apply)
+ password_data = (known after apply)
+ placement_group = (known after apply)
~ primary_network_interface_id = "eni-0e25fc185305b62f5" -> (known after apply)
~ private_dns = "ip-172-31-38-133.ap-northeast-1.compute.internal" -> (known after apply)
~ private_ip = "172.31.38.133" -> (known after apply)
~ public_dns = "ec2-54-238-133-242.ap-northeast-1.compute.amazonaws.com" -> (known after apply)
~ public_ip = "54.238.133.242" -> (known after apply)
~ security_groups = [
- "default",
] -> (known after apply)
source_dest_check = true
~ subnet_id = "subnet-e623ecae" -> (known after apply)
- tags = {
- "Name" = "example"
} -> null
~ tenancy = "default" -> (known after apply)
+ user_data = "655c303ddd9e02635f849fe2993693f147f4baf1" # forces replacement
~ volume_tags = {} -> (known after apply)
~ vpc_security_group_ids = [
- "sg-774fa903",
] -> (known after apply)
- credit_specification {
- cpu_credits = "standard" -> null
}
+ ebs_block_device {
+ delete_on_termination = (known after apply)
+ device_name = (known after apply)
+ encrypted = (known after apply)
+ iops = (known after apply)
+ kms_key_id = (known after apply)
+ snapshot_id = (known after apply)
+ volume_id = (known after apply)
+ volume_size = (known after apply)
+ volume_type = (known after apply)
}
+ ephemeral_block_device {
+ device_name = (known after apply)
+ no_device = (known after apply)
+ virtual_name = (known after apply)
}
+ network_interface {
+ delete_on_termination = (known after apply)
+ device_index = (known after apply)
+ network_interface_id = (known after apply)
}
~ root_block_device {
~ delete_on_termination = true -> (known after apply)
~ encrypted = false -> (known after apply)
~ iops = 100 -> (known after apply)
+ kms_key_id = (known after apply)
~ volume_id = "vol-0c18661555b5f2b20" -> (known after apply)
~ volume_size = 8 -> (known after apply)
~ volume_type = "gp2" -> (known after apply)
}
}
Plan: 1 to add, 0 to change, 1 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: # yes
aws_instance.example: Destroying... [id=i-0fe53d6817ed0dff9]
aws_instance.example: Still destroying... [id=i-0fe53d6817ed0dff9, 10s elapsed]
aws_instance.example: Still destroying... [id=i-0fe53d6817ed0dff9, 20s elapsed]
aws_instance.example: Still destroying... [id=i-0fe53d6817ed0dff9, 30s elapsed]
aws_instance.example: Still destroying... [id=i-0fe53d6817ed0dff9, 40s elapsed]
aws_instance.example: Destruction complete after 42s
aws_instance.example: Creating...
aws_instance.example: Still creating... [10s elapsed]
aws_instance.example: Still creating... [20s elapsed]
aws_instance.example: Creation complete after 26s [id=i-051a6fde310a77a6e]
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
```
**aws_instance.example must be replaced**
AWSマネジメントコンソール

リソースの更新は
- **既存のリソースをそのまま変更する**
- **リソースが作り直しになる**
ケースが存在する。
**<疑問>**
どういうときにどちらのケースになるのかはよくわからない。追々。。
また、リソース名が反映されていたりされていなかったり。。
- Terraformは`tfstate`ファイルで現在の状態を記録
applyを実行すれば勝手に作成される。
```bash
# cat terraform.tfstate
{
"version": 4,
"terraform_version": "0.12.24",
"serial": 14,
"lineage": "a908d40c-ddc9-106d-b5d2-956395d600de",
"outputs": {},
"resources": [
{
"mode": "managed",
"type": "aws_instance",
"name": "example",
"provider": "provider.aws",
"instances": [
{
"schema_version": 1,
"attributes": {
......
```
### 削除
```bash
# terraform destroy
aws_instance.example: Refreshing state... [id=i-051a6fde310a77a6e]
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
# aws_instance.example will be destroyed
- resource "aws_instance" "example" {
- ami = "ami-02ddf94e5edc8e904" -> null
- arn = "arn:aws:ec2:ap-northeast-1:488656661057:instance/i-051a6fde310a77a6e" -> null
- associate_public_ip_address = true -> null
- availability_zone = "ap-northeast-1a" -> null
- cpu_core_count = 1 -> null
- cpu_threads_per_core = 1 -> null
- disable_api_termination = false -> null
- ebs_optimized = false -> null
- get_password_data = false -> null
- hibernation = false -> null
- id = "i-051a6fde310a77a6e" -> null
- instance_state = "running" -> null
- instance_type = "t2.micro" -> null
- ipv6_address_count = 0 -> null
- ipv6_addresses = [] -> null
- monitoring = false -> null
- primary_network_interface_id = "eni-01439fbd40e0fd5c9" -> null
- private_dns = "ip-172-31-35-176.ap-northeast-1.compute.internal" -> null
- private_ip = "172.31.35.176" -> null
- public_dns = "ec2-13-230-8-239.ap-northeast-1.compute.amazonaws.com" -> null
- public_ip = "13.230.8.239" -> null
- security_groups = [
- "default",
] -> null
- source_dest_check = true -> null
- subnet_id = "subnet-e623ecae" -> null
- tags = {} -> null
- tenancy = "default" -> null
- user_data = "655c303ddd9e02635f849fe2993693f147f4baf1" -> null
- volume_tags = {} -> null
- vpc_security_group_ids = [
- "sg-774fa903",
] -> null
- credit_specification {
- cpu_credits = "standard" -> null
}
- root_block_device {
- delete_on_termination = true -> null
- encrypted = false -> null
- iops = 100 -> null
- volume_id = "vol-0228a2f03aba7400a" -> null
- volume_size = 8 -> null
- volume_type = "gp2" -> null
}
}
Plan: 0 to add, 0 to change, 1 to destroy.
Do you really want to destroy all resources?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: # yes
aws_instance.example: Destroying... [id=i-051a6fde310a77a6e]
aws_instance.example: Still destroying... [id=i-051a6fde310a77a6e, 10s elapsed]
aws_instance.example: Still destroying... [id=i-051a6fde310a77a6e, 20s elapsed]
aws_instance.example: Still destroying... [id=i-051a6fde310a77a6e, 30s elapsed]
aws_instance.example: Destruction complete after 31s
Destroy complete! Resources: 1 destroyed.
# terraform show //terraformの管理下に何もないことを確認
#
```
**aws_instance.example will be destroyed**
AWSマネジメントコンソール
