LoginSignup
0
0

More than 3 years have passed since last update.

Terraform環境をdockerで構築

Posted at

概要

AWSのリソースは基本的にTerraformで構築していますが、人によってTerraform実行環境に差分が発生していたことが気になったので、Dockerを使用しできるだけ差分をなくすことが目標です。
ここでは、Terraformを実行するための最低限のセットアップを行っています。

前提条件

前提条件は以下の通りです。

  • Dockerがインストール済みであること。

構成

ディレクトリ構成は以下の通りです。

.
├── .aws (awsの認証情報を格納)
│   ├── config
│   └── credentials
├── docker-compose.yml
├── dockerfile
└── src (Terraformソースを格納)

Dockerfileは以下の通りです。
aws-cli、Terraformなど最低限必要なものをインストールしています。

FROM python:3.6

# install aws-cli
RUN pip install awscli

# install command
RUN apt-get update && apt-get install -y vim wget unzip vim sudo

# install terraform
RUN wget https://releases.hashicorp.com/terraform/0.13.0/terraform_0.13.0_linux_amd64.zip
RUN unzip ./terraform_0.13.0_linux_amd64.zip -d /usr/local/bin/

RUN mkdir ~/.aws

# 初期ディレクトリ
WORKDIR /opt

Docker-compose.ymlは以下の通りです。

docker-compose.yml
version: '3'
services:
  terraform_env:
    build: .
    volumes:
      - ./src:/opt/src
      - ./.aws:/root/.aws

構築

実際にDocker環境を構築します。
手順は以下の通りです。

  • イメージのビルド

以下コマンドを実行し、イメージのビルドを行います。

$ docker-compose build
  • コンテナの立ち上げ

以下コマンドを実行し、イメージからコンテナを立ち上げます。
コマンド実行後、コンテナの/optにログインされます。

$ docker-compose run --rm terraform_env bash
Creating work_terraform_env_run ... done
root@cd820124c743:/opt# ls
src
  • コマンドの確認

Terraform、aws-cliがインストールされている確認します。

root@1a285d2a39e4:/opt# aws --version
aws-cli/1.19.60 Python/3.6.13 Linux/5.10.25-linuxkit botocore/1.20.60
root@1a285d2a39e4:/opt# terraform --version

Your version of Terraform is out of date! The latest version
is 0.15.1. You can update by downloading from https://www.terraform.io/downloads.html
Terraform v0.13.0

後は src/以下にTerraformのファイルを作成し、実際にリソースを構築していきましょう。

備考

credentials をプロフィール毎に分ける際は、Terraformの provider でどの環境を使用するか定義する必要があります。

  • credentials
[test_env]
aws_access_key_id = xxxxxxxxxx
aws_secret_access_key = xxxxxxxxxx

[test]
aws_access_key_id = xxxxxxxxxx
aws_secret_access_key = xxxxxxxxxx
provider.tf
provider "aws" {
  region  = "ap-northeast-1"
  profile = "test_env"
}
0
0
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
0