Terraform, getting output from null_resource, local-exec and the AWS CLI

big_tommy_7bb picture big_tommy_7bb · Jul 25, 2016 · Viewed 13.6k times · Source

I'm using Terraform to automate provision of Cognito Identity Pools in AWS. The AWS provider doesn't support Cognito yet so I've been using null_resource and local-exec to call the AWS CLI.

I have the following resource:

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"
    }
}

which gives the following output:

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

The next step is to add some roles, which I've already created, to the identity pool:

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"
    }
}

The issue is that I'm unable to extract the IdentityPoolId, ${null_resource.create-identitypool.IdentityPoolId}, to use in the second resource. I understand the null_resource doesn't have output attributes, so how can I get this JSON object out of the command line output. I'll also want to use tirggers and run aws cognito-identity list-identity-pools and possibly delete-identity-pool to make this all repeatable from which I'll also need the output.

Any ideas? And apologies if I've missed this information somewhere else. I've also asked this question on the Terraform mailing list, but I thought I'd try for a wider audience.

Thanks, Tim

Answer

Paul Tyng picture Paul Tyng · Dec 12, 2016

There is a new data source in Terraform 0.8, external that allows you to run external commands and extract output. See data.external.

The data source should only be used for the retrieval of the Cognito data, not the execution of it. Since this is a Terraform data source, it should not have any side effects.