🌊

terraformコマンドを"hashicorp/terraform"Dockerイメージから実行する方法

2022/06/19に公開

目的

terraformコマンドを hashicorp/terraformDockerイメージから実行する

問題その1

ドキュメント記載のコマンドを実行すると以下のようにエラーになる.

$ docker run -i -t hashicorp/terraform:latest plan
│ Error: No configuration files
│
│ Plan requires configuration to be present. Planning without a configuration would mark everything for destruction, which is normally not what is desired. If you
│ would like to destroy everything, run plan with the -destroy option. Otherwise, create a Terraform configuration file (.tf file) and try again.

問題その2

-vオプションを付与しボリュームをマウントして実行してみる:

$ docker run -v $(pwd):/workdir -w /workdir hashicorp/terraform:latest init

S3をBackendとしてTerraformを実行しているため,credentialsが無くエラーに.

Initializing the backend...
╷
│ Error: error configuring S3 Backend: no valid credential sources for S3 Backend found.
│
│ Please see https://www.terraform.io/docs/language/settings/backends/s3.html
│ for more information about providing credentials.
│
│ Error: NoCredentialProviders: no valid providers in chain. Deprecated.
│       For verbose messaging see aws.Config.CredentialsChainVerboseErrors

問題その3

--env-fileオプションを付与し,.aws/credentials内の情報をexportしようと試みる.

$ docker run \
    -v $(pwd):/workdir \
    -w /workdir \
    --env-file $(echo ~)/.aws/credentials \
    hashicorp/terraform:latest init

周知のとおり,.aws/credentialsではKeyとValue間にスペースがあるため,それが原因でコケる.

docker: poorly formatted environment: variable 'aws_access_key_id ' contains whitespaces.
See 'docker run --help'.

解決策

ごちゃごちゃ感が否めないが,とりあえず以下で実行できた.

$ docker run \
    -v $(pwd):/workdir \
    -w /workdir \
    -e AWS_ACCESS_KEY_ID=$(grep aws_access_key_id $(echo ~)/.aws/credentials | awk '{print $3}') \
    -e AWS_SECRET_ACCESS_KEY=$(grep aws_secret_access_key $(echo ~)/.aws/credentials | awk '{print $3}') \
    hashicorp/terraform:latest init

↓↓↓

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v3.75.2

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.

Discussion