LoginSignup
11
6

More than 3 years have passed since last update.

Terraformのcredential情報をリポジトリ外で管理する

Posted at

TerraformでAWSを操作する際、credential情報をどこかに記載しておく必要があります。ただ、Gitの管理下に置くのはマズイということで、リポジトリ外で管理する方法を探したところ、いくつか方法があるようです。

それらのうち、~/.aws/credentialsを参照する方法が一番便利に感じたので、その方法をメモしておきます。

やり方

まず、~/.aws/credentialsにcredential情報を記述します。

credentials
[default]
aws_access_key_id=***********
aws_secret_access_key=*********
region=ap-northeast-1

[sample]
aws_access_key_id=***********
aws_secret_access_key=*********
region=ap-northeast-1

defaultはその名の通り、AWS CLIでコマンドを打つ際、profileを指定しない場合に使われるcredential情報です。

複数のプロジェクトに関わっている場合、AWSのcredentialを複数管理することになるでしょうから、[sample]のようにprofileを設定します。

こうすることで、aws ls s3 などと打てばdefaultのcredential情報が参照され、aws ls s3 --profile sampleと打てばsampleが参照されるようになります。

Terraformから参照する

方法はシンプルで、providerの中にprofileプロパティを追加するだけです。

config.tf
provider "aws" {
  region = "ap-northeast-1"
  profile = "sample"
}

これなら、TerraformリポジトリにAccessKeyをハードコーディングせずに済みますね。

これでよし...とterraform initを実行すると...

動かない

-> % terraform init

Initializing the backend...

Error: Failed to get existing workspaces: AccessDenied: Access Denied
    status code: 403, request id: *********, host id: ******************************

あら...?

ここで結構詰まりました。いろいろ調べているうち、コマンド実行時にAWS_PROFILE=sampleと明示的に打つ必要があるとの記述を見かけたので、試したところ...

-> % AWS_PROFILE=sample terraform init

Initializing the backend...

Initializing provider plugins...

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.32"

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.

無事に動きました。よかった。

~/.aws/credentialsを参照する他にも、環境変数で指定する方法などがあったので、使いやすさなど検討して選んでみるといいかもしれません。

11
6
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
11
6