3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Terraform】外部ファイルで変数を使用

Posted at

Lambdaをデプロイする際などスクリプト内で変数を使用したい場合などに、template_fileとlocal_fileを組み合わせる事でterraformのvariables内で変数を定義する

使用するData SourcesとResourceは以下の通り

ディレクトリ構造

.
├── template.py
├── variables.tf
└── lambda
    └── example #変数に値をセットした後のファイルの出力先

ファイル内容

template.py
...
        Instances={
            'InstanceGroups': [
                {
                    'Name': 'Master nodes',
                    'Market': 'SPOT',
                    'InstanceRole': 'MASTER',
                    'InstanceType': '${instance_type}',
                    'InstanceCount': ${instance_count_master},
...
variables.tf
# template.pyを読み込み、変数に値を渡す
data "template_file" "example" {
  template = "${file("${path.module}/template.py")}"
  vars = {
    instance_size         = "c4.large"
    instance_count_master = "1"
    instance_count_core   = "2"
    
  }
}

# template_fileをファイルに出力
resource "local_file" "example" {
  content  = "${data.template_file.example.rendered}"
  filename = "${path.module}/lambda/example/lambda_function.py"
}

使用方法

通常のTerraformと同じく、terraform applyする。teffarorm destroyする事で生成されたファイルが削除される

> terraform apply

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:

  # local_file.example will be created
  + resource "local_file" "example" {
      + content              = <<-EOT
...省略
Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:  # yes入力後Enter押下

...省略
local_file.example: Creating...
local_file.example: Creation complete after 0s [id=b0e33cd03e3451033468b33361454f71cb2d8c4b]

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

結果

./lambda/example/lambda_function.py
...
        Instances={
            'InstanceGroups': [
                {
                    'Name': 'Master nodes',
                    'Market': 'SPOT',
                    'InstanceRole': 'MASTER',
                    'InstanceType': 'c4.large',
                    'InstanceCount': 1
...
3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?