【AWS x Terraform】通过编码学习AWS 〜入门篇〜

你好,我是株式会社运动通信社的后端工程师横山。我寻找与我有相同条件的人。

    • AWS知識に自信がないので勉強したい

 

    Terraformに興味がある

让我们一起动手学习,踏上学习之旅吧。

这篇文章的目标

    Terraformを実行できる環境の作成

前提条件 (Qian ti tiao jian)

    • Mac OS Big Sur 11.2.3

 

    • Docker for Mac version 20.10.6

 

    • aws-cli 2.3.4

 

    AWSアカウントを持っていること

预先准备

使用 Terraform CLI 创建 IAM 用户

首先,让我们使用Terraform CLI创建一个IAM用户。

image.png

设置概要资料

让我们在aws-cli中添加配置文件信息。

# プロファイル名
> aws configure --profile terraform

AWS Access Key ID [None]: ***** # 上記7. 取得したアクセスキーID
AWS Secret Access Key [None]: ***** # 上記7. 取得したシークレットアクセスキー
Default region name [None]: ap-northeast-1 # デフォルトのリージョンを東京
Default output format [None]: json # デフォルトの出力形式をjson

# 名前付きプロファイルが追加されたことを確認
> cat ~/.aws/credentials

[terraform]
aws_access_key_id = *****
aws_secret_access_key = *****

使用 Terraform 创建容器。

我们可以使用HashiCorp公司官方提供的hashicorp/terraform镜像来构建容器,该镜像包装了Terraform执行文件。让我们创建以下Compose文件。

version: '3'

services:
  terraform:
    container_name: terraform
    image: hashicorp/terraform:latest
    volumes:
      - type: bind
        source: ".."
        target: "/src"
      - type: bind
        source: "${HOME}/.aws"
        target: "/root/.aws"
    working_dir: /src
    entrypoint: [ "/bin/ash" ]
    tty: true
    • 学習用のためlatestタグ

 

    • Terraformは開発が盛んなため実運用ではタグを固定しましょう。

 

    • IAMの認証情報はホスト側の{home}/.awsをマウント

 

    • env_fileで別途ファイルを分けて環境変数としてIAMの認証情報をコンテナに設定するのが主流らしいが、こちらの方が開発・本番などで環境ごとにprofileを分けている場合切り替えをしやすい。

 

    • entrypoint: [ “/bin/ash” ]

 

    デタッチモードでコンテナを起動したままにしたいが、ベースイメージの方でENTRYPOINT [“/bin/terraform”]が指定されている影響でできない。そのため上書き。

创建项目

我们将以最小的构成进行制作。

    将上述的Compose文件放置在(项目根目录)/docker/docker-compose.yml中。
(root)
  └── docker
      └── docker-compose.yml
    拉取镜像并启动容器
# Composeファイルが置いてあるディレクトリへ移動
> cd (プロジェクトroot)/docker/

# イメージをPull&デタッチモードでコンテナ起動
> docker-compose up -d

Creating network "docker_default" with the default driver
Creating terraform ... done

# コンテナが起動されていることを確認
> docker container ls

CONTAINER ID   IMAGE                        COMMAND                  CREATED          STATUS          PORTS                                                 NAMES
04db7023a025   hashicorp/terraform:latest   "/bin/ash"               34 seconds ago   Up 32 seconds                                                         terraform

# コンテナのシェル起動
> docker-compose exec terraform ash

# コンテナ内でTerraform CLIを使えることを確認
> terraform -version

Terraform v1.1.5 # その時の最新版のバージョン
on linux_amd64

# exit
> exit

确认动作

真是很长时间啊,辛苦了。终于可以用Terraform进行操作验证了。

(root)
  ├── docker
  │   └── docker-compose.yml
  └── ** maint.tf **

Terraform使用.tf文件作为其扩展名作为源代码。
我们创建main.tf文件,并尝试创建一个名为hello-terraform的IAM用户作为简单的操作确认。

provider "aws" {
  profile = "terraform" # 使用するプロファイル
  region  = "ap-northeast-1" # デフォルトのリージョン
}

# IAMユーザー作成
resource "aws_iam_user" "hello-terraform" {
  name = "hello-terraform" # IAMユーザ名
}

只设定IAM用户的名称,然后进行最小程度的执行尝试。
关于详细描述的内容将在另一个时机涉及,暂且确保功能可以正常运行。

# Composeファイルが置いてあるディレクトリへ移動
> cd (プロジェクトroot)/docker/

# コンテナのシェル起動
> docker-compose exec terraform ash

# 初期化
> terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v3.74.1...
- Installed hashicorp/aws v3.74.1 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

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.


# IAMユーザを実際に生成
> terraform apply -auto-approve

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_iam_user.hello-terraform will be created
  + resource "aws_iam_user" "hello-terraform" {
      + arn           = (known after apply)
      + force_destroy = false
      + id            = (known after apply)
      + name          = "hello-terraform"
      + path          = "/"
      + tags_all      = (known after apply)
      + unique_id     = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.
aws_iam_user.hello-terraform: Creating...
aws_iam_user.hello-terraform: Creation complete after 1s [id=hello-terraform]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

请确认在项目文件夹中创建了一些文件。

(root)
  ├── docker
  │   └── docker-compose.yml
  ├── maint.tf
  ├── .terraform
  ├── .terraform.lock.hcl
  └── terraform.tfstate

现在让我们通过AWS控制台确认由terraform apply -auto-approve创建的IAM用户是否成功创建。

image.png

你好,可以确认 hello-terraform 已经存在!辛苦了!
以上就是 Terraform 环境的构建了。

下一次

在进行本次环境配置之前,先了解一下Terraform到底是什么,
IAM和EC2这些基本服务的描述方法
自动生成文件组是什么,
希望能够随后写一篇详细文章来介绍如何团队合作使用Terraform的方法。

广告
将在 10 秒后关闭
bannerAds