21

我正在使用 Terraform 在 AWS 中自动提供 Cognito 身份池。AWS 提供商还不支持 Cognito,所以我一直在使用 null_resource 和 local-exec 来调用 AWS CLI。

我有以下资源:

resource "null_resource" "create-identitypool" {
    provisioner "local-exec" {
        command = "aws cognito-identity create-identity-pool --identity-pool-name terraform_identitypool --no-allow-unauthenticated-identities --developer-provider-name login.terraform.myapp"
    }
}

给出以下输出:

null_resource.create-identitypool (local-exec): {
null_resource.create-identitypool (local-exec):     "IdentityPoolId": "eu-west-1:22549ad3-1611-......",
null_resource.create-identitypool (local-exec):     "AllowUnauthenticatedIdentities": false,
null_resource.create-identitypool (local-exec):     "DeveloperProviderName": "login.terraform.myapp",
null_resource.create-identitypool (local-exec):     "IdentityPoolName": "terraform_identitypool"
null_resource.create-identitypool (local-exec): }
null_resource.create-identitypool: Creation complete

下一步是将我已经创建的一些角色添加到身份池中:

resource "null_resource" "attach-policies-identitypool" {
    provisioner "local-exec" {
        command = "aws cognito-identity set-identity-pool-roles --identity-pool-id ${null_resource.create-identitypool.IdentityPoolId} --roles authenticated=authroleXXX,unauthenticated=unauthroleXXX"
    }
}

问题是我无法提取 IdentityPoolId ${null_resource.create-identitypool.IdentityPoolId} 以在第二个资源中使用。我知道 null_resource 没有输出属性,所以我怎样才能从命令行输出中获取这个 JSON 对象。我还想使用 tirggers 并运行 aws cognito-identity list-identity-pools 和可能的 delete-identity-pool 以使这一切都可以重复,我还需要输出。

有任何想法吗?如果我在其他地方错过了这些信息,我们深表歉意。我也在 Terraform 邮件列表上问过这个问题,但我想我会尝试更广泛的受众。

谢谢,蒂姆

4

2 回答 2

13

Terraform 0.8 中有一个新的数据源external,允许您运行外部命令并提取输出。见data.external

数据源应用于检索 Cognito 数据,而不是执行它。由于这是一个 Terraform 数据源,它不应该有任何副作用。

于 2016-12-12T16:00:12.047 回答
3

保罗的回答是正确的。但是,外部数据只有在 shell 脚本以 JSON 格式发回数据时才有效,这需要更多的工作。

因此,Matti Paksula 为此制作了一个模块。(https://github.com/matti/terraform-shell-resource)。

使用该模块,我们可以获得任何 shell 脚本 local-exec 调用的 stdout、stderr 和退出状态。

这是一个示例 main.tf 文件。您可以以任何方式修改它,以运行您想要的任何命令,包括您问题中的命令。

#  Defining a variable , we will feed to the shell script
variable "location" { default = "us-central1-f" }


# Calling Matti's Module
module "shell_execute" {
  source  = "github.com/matti/terraform-shell-resource"
  command = "./scripts/setenv.sh"
}


# Creating a shell script on the fly
resource "local_file" "setenvvars" {
  filename = "./scripts/setenv.sh"
  content  = <<-EOT
    #!/bin/bash
    export LOCATION=${var.modinput_location}
    echo LOCATION $LOCATION
  EOT
}

#  Now, we get back the output of the script
output "shell_stdout" {
  value = module.shell_execute.stdout
}

#  Now, we get back if there are any errors
output "shell_stderr" {
  value = module.shell_execute.stderr
}

#  Now, we get back exit status of the script
output "shell_exitstatus" {
  value = module.shell_execute.exitstatus
}

于 2020-11-25T20:53:54.610 回答