在Docker中运行Terraform和Terragrunt

为什么想要在Docker上运行Terraform?

    • 環境やバージョンの違いで動かない問題が起きなくなるので保守性があがる。

 

    Terraformの定義ファイル内でバージョン固定しなくてもよくなる*もちろん固定してもいいが余計なエラーに悩まされることがなくなる。

制作物

    准备三个文件:Dockerfile、docker-compose.yml和makefile选项。

Dockerfile: Docker文件

FROM python:3.6

ARG pip_installer="https://bootstrap.pypa.io/get-pip.py"
ARG AWSCLI_VERSION
ARG TERRAFORM_VERSION
ARG TERRAGRUNT_VERSION

# install aws-cli
RUN pip install awscli==${AWSCLI_VERSION}

# install command.
RUN apt-get update && apt-get install -y less vim wget unzip jq

# install terraform
RUN wget https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip && \
  unzip ./terraform_${TERRAFORM_VERSION}_linux_amd64.zip -d /usr/local/bin/ \
  && rm ./terraform_${TERRAFORM_VERSION}_linux_amd64.zip

# install terargrunt
RUN wget https://github.com/gruntwork-io/terragrunt/releases/download/v${TERRAGRUNT_VERSION}/terragrunt_linux_amd64 \
  && chmod +x ./terragrunt_linux_amd64 \
  && mv ./terragrunt_linux_amd64 /usr/local/bin/terragrunt

# COPY terraform related files
COPY ./terraform /terraform

docker-compose.yml 的含义是 Docker Compose 配置文件。

version: "2"
services:
  terraform:
    container_name: "terraform"
    build:
      context: ../ #Dockerfileのパスを指定する
      dockerfile: Dockerfile
      args:
        AWSCLI_VERSION: "1.16.168"
        TERRAFORM_VERSION: "1.0.1"
        TERRAGRUNT_VERSION: "0.31.0"
    env_file: ./.env
    working_dir: /terraform
    tty: true

还需要准备一个makefile

.PHONY: build plan apply destroy

default:build

build:
    @docker-compose build

plan: build
    @docker-compose run --rm terraform terragrund plan

apply: build
    @docker-compose run --rm terraform terragrunt apply

destroy: build
    @docker-compose run --rm terraform terragrunt destroy

通过这样做,您将能够使用make apply或类似方法来应用Terraform。

请参考下列文章。

广告
将在 10 秒后关闭
bannerAds