简体   繁体   English

如何将 cdktf 与“计数”属性结合使用?

[英]How can I use cdktf in combination with the "count" attribute?

I am using cdktf for typescript and I am facing the situation that I only want to add a resource under a given condition.我正在为 typescript 使用 cdktf,我面临的情况是我只想在给定条件下添加资源。 To solve this problem, I found a couple of questions on SO and I figured that we might want to use count in order to solve this problem.为了解决这个问题,我在 SO 上发现了几个问题,我想我们可能想使用count来解决这个问题。

So I came up with this code:所以我想出了这段代码:

    const zipBuild = new DataArchiveFile(this, 'zipBuild', {
      type: 'zip',
      sourceDir: asset.path,
      outputPath: join(asset.path, 'dist.zip'),
      excludes: ['dist.zip'], // don't zip the zip
    });
    zipBuild.addOverride("count", "${var.my_condition} ? 1 : 0");

    const build = new GoogleStorageBucketObject(this, 'build', {
      name: `gcp-fancy-bucket-name/${zipBuild.outputSha}.zip`,
      bucket: deployBucket.stringValue,
      source: zipBuild.outputPath, // <<<< This is the offending line
      timeouts: {
        create: '15m',
        update: '15m',
      },
    });
    zipBuild.addOverride("count", "${var.my_condition} ? 1 : 0");

But when I want to synthesise this code to terraform, I get an error during the terraform validate step:但是,当我想将此代码合成为 terraform 时,在terraform validate步骤中出现错误:

Error validating cdktf {
  err: Error: Command failed: terraform validate -no-color
  
  Error: Missing resource instance key
  
    on cdk.tf.json line 122, in resource.google_storage_bucket_object.build_088E518B:
   122:         "name": "gcp-fancy-bucket-name/${data.archive_file.zipBuild_FD7BC769.output_sha}.zip",
  
  Because data.archive_file.zipBuild_FD7BC769 has "count"
  set, its attributes must be accessed on specific instances.
  
  For example, to correlate with indices of a referring resource, use:
      data.archive_file.zipBuild_FD7BC769[count.index]
  
  Error: Missing resource instance key
  
    on cdk.tf.json line 123, in resource.google_storage_bucket_object.build_088E518B:
   123:         "source": "${data.archive_file.zipBuild_FD7BC769.output_path}",
  
  Because data.archive_file.zipBuild_FD7BC769 has "count"
  set, its attributes must be accessed on specific instances.
  
  For example, to correlate with indices of a referring resource, use:
      data.archive_file.zipBuild_FD7BC769[count.index]

I checked the cdktf code of DataArchiveFile , TerraformDataSource and TerraformElement but I couldn't find a method to access zipBuild.outputPath (or another property) for an array object, rather than the single object.我检查了DataArchiveFileTerraformDataSourceTerraformElement的 cdktf 代码,但我找不到一种方法来访问数组 object 的zipBuild.outputPath (或其他属性),而不是单个 object。

Does anyone used count before in combination with cdktf and knows how to handle it?有没有人在结合 cdktf 之前使用过count并且知道如何处理它?

Also I tried this, but this also failed:我也试过这个,但这也失败了:

    const build = new GoogleStorageBucketObject(this, 'build', {
      name: `gcp-fancy-bucket-name/${zipBuild.outputSha}.zip`,
      bucket: deployBucket.stringValue,
      source: "${" + zipBuild.fqn + ".outputPath[count.index]}",
      timeouts: {
        create: '15m',
        update: '15m',
      },
    });

because the .fqn will give me an additional set of ${} :因为.fqn会给我额外的一组${}

\\"bucket\\": \\"${${google_storage_bucket_object.build}.bucket[count.index]}\\",

I worked out how one array element can be accessed in this context:我弄清楚了如何在这种情况下访问一个数组元素:

The key was a combination from propertyAccess and Fn.lookup :-)关键是propertyAccessFn.lookup的组合:-)

    const zipBuild = new DataArchiveFile(this, 'zipBuild', {
      type: 'zip',
      sourceDir: asset.path,
      outputPath: join(asset.path, 'dist.zip'),
      excludes: ['dist.zip'], // don't zip the zip
    });
    zipBuild.addOverride("count", "${var.my_condition} ? 1 : 0");

    const realZipBuild = propertyAccess(zipBuild.fqn, [0]);
    const zipBuildOutputPath = Fn.lookup(realZipBuild, 'output_path', '') as string;

    const build = new GoogleStorageBucketObject(this, 'build', {
      name: `gcp-fancy-bucket-name/${zipBuild.outputSha}.zip`,
      bucket: deployBucket.stringValue,
      source: zipBuildOutputPath,
      timeouts: {
        create: '15m',
        update: '15m',
      },
    });
    zipBuild.addOverride("count", "${var.my_condition} ? 1 : 0");

Given that conditionals and looping are one of the primary reasons to use cdktf, my suggestion would be to use standard Terraform for your project.鉴于条件和循环是使用 cdktf 的主要原因之一,我的建议是为您的项目使用标准 Terraform。

I have worked with cdktf and count using typescript. The best way i was able to tackle the count was to use interpolation to get desired value.我曾使用 cdktf 并使用 typescript 进行计数。我能够处理计数的最佳方法是使用插值来获得所需的值。 Example例子

 new VolumeAttachment(this,"example-disk-attachment",{
  deviceName: "/dev/sdh",
  volumeId : `\${element(aws_ebs_volume.example-disk.*.id, count.index)}`,
  instanceId: `\${element(aws_instance.example-machine.*.id, count.index)}`,
  dependsOn : [ec2Instance,exampleVolume],
  count: networkCount
})

This is just an example how i used interpolation with terraform cdk to make count work.这只是我如何使用 terraform cdk 插值来使计数工作的示例。 I can share more context to this if you want as it worked perfectly fine for me.如果您愿意,我可以与您分享更多背景信息,因为它对我来说效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM