Accessing bucket name from terraform in python script

I have created a bucket using terraform.
That tf code looks like this:
module “s3_bucket_name” {
source = “”
bucket_name = “${local.bucket_name}”
default_tags = local.default_tags

Is there a way I can access this bucket name in a python script that’s within the same project?

Hi @ShaynaFishmanMH,

There are two main ways to integrate results from Terraform into other software.

The first and most common way is to add a resource to your Terraform configuration which publishes the relevant information into some sort of configuration store, such as AWS SSM Parameter Store, and then configure your application to read the setting from that same location. This approach is nice because it decouples the Terraform configuration from the application: as long as they both agree on which SSM Parameter Name (or similar) to use, neither subsystem knows any details about the other.

If that isn’t an option then an alternative would be to publish your bucket name as an output value from your root module:

output "bucket_name" {
  value = local.bucket_name

Then after you’ve run terraform apply you can run terraform output -json to get all of the output values together in JSON format, or alternatively terraform output -raw bucket_name to get just the bucket name as a plain string, and then pass that output into your application code. This approach implies some greater coupling between the two, and will probably require some kind of wrapper script which orchestrates the process of running terraform apply, running the relevant terraform output command, and then running your application with the output.


My practice: getting the information from the terraform.tfstate file directly.

After creating the bucket using terraform, the bucket name will be written to the terraform.tfstate in plain text. You can find the section describing that bucket.

Usually, for aws bucket, the format is:

    "bucket": "my-bucket-name"

For Linux shell scripts, it is very easy to get the info my system utils such as sed, awk, or grep.

For Python scripts, you may also find an easy way to get the bucket name by reading the terraform.tfstate file.

A reminder: extracting information from tfstate file is not recommended because the terraform team reserves the right to change the format of this file.