I want to identify the public ip of the terraform execution environment and add it to the security group

前端 未结 3 457
心在旅途
心在旅途 2021-02-05 07:11

I want to identify the public IP of the terraform execution environment and add it to aws security group inbound to prevent access from other environments.

Currently, I

3条回答
  •  轮回少年
    2021-02-05 07:54

    The most elegant solution I could come up with is to use the "external data source" provider. https://www.terraform.io/docs/providers/external/data_source.html

    This was written for these kind of purposes where people were combining local-exec, null-resource and vars to inject something locally.

    Anyway, I'm sure you can do this without writing a small script. The thing is the "external data source" expects to read JSON. So in my example I just built a JSON string in a program and then call that program. I'm sure this could be done in a one liner using echo or jq...

    Here is my main.tf file:

    data "external" "example" {
      program = ["sh", "test.sh" ]
    }
    
    output "commandout" {
      value = "${data.external.example.result}"
    }
    

    Here is my shell script (test.sh):

    #!/bin/bash
    
    echo {\"ip\":\""`hostname -I`"\"}
    

    Technically once you have this situation you can use:

    ${data.external.example.result}
    

    As your var input.

    Here is my working example with terraform output.

    data.external.example: Refreshing state...
    
    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
    
    Outputs:
    
    commandout = {
      ip = 10.0.2.15
    }
    

    Note that hostname -I is ok if you only have one NIC :) Otherwise use an alternative command or cut the output for your desired results.

提交回复
热议问题