Bootstrap FreeKB - Amazon Web Services (AWS) - Get Canonical User ID using Terraform
Amazon Web Services (AWS) - Get Canonical User ID using Terraform

Updated:   |  Amazon Web Services (AWS) articles

This assumes you have setup Terraform with the Amazon Web Services (AWS) provider. If not, check out my article Amazon Web Services (AWS) Getting Started with Terraform.

Let's say you have the following files on your Terraform server.

├── required_providers.tf
├── canonical_user_id (directory)
│   ├── userid.tf
│   ├── provider.tf

 

required_providers.tf will almost always have this.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

 

Let's say provider.tf in the network_load_balancer directory has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.

provider "aws" {
  alias   = "default"
  profile = "default"
  region  = "default"
}

 

And userid.tf could have the following.

data "aws_canonical_user_id" "current" {}

 

And then data.aws_canonical_user_id.current.id can be used to fetch the Canonical User ID. In this example, data.aws_canonical_user_id.current.id is used when setting an S3 Bucket Access Control Lists (ACLs).

data "aws_canonical_user_id" "current" {}

resource "aws_s3_bucket_acl" "bucket_acl" {

  bucket = "my-bucket-abdefg"

  access_control_policy {

    grant {
      grantee {
        id   = data.aws_canonical_user_id.current.id
        type = "CanonicalUser"
      }
      permission = "FULL_CONTROL"
    }

    grant {
      grantee {
        type = "Group"
        uri  = "http://acs.amazonaws.com/groups/s3/LogDelivery"
      }
      permission = "FULL_CONTROL"
    }
    owner {
      id = data.aws_canonical_user_id.current.id
    }
  }
}

 

You may need to issue or reissue the terraform init command.

terraform init

 

The terraform plan command can be used to see what Terraform will try to do.

terraform plan

 

And the terraform apply command can be used to create the S3 Bucket and set the S3 Bucket Access Control Lists (ACLs).

terraform apply

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b28e44 in the box below so that we can be sure you are a human.