- Create an S3 bucket,
- Upload a file to the bucket, and
- Attach a bucket policy that grants access to an existing IAM entity.
Creating an S3 Bucket
To create an S3 bucket, we use the AWS S3 bucket resource in Terraform. For more details on the available resource arguments, please refer to the Terraform AWS documentation. Below is an example configuration where we define an S3 bucket with a unique name and attach a descriptive tag.terraform.tfstate file.
Uploading a File to the S3 Bucket
After successfully creating the S3 bucket, the next step is to upload a file. We use the AWS S3 Bucket Object resource to achieve this. The key arguments required are:- The bucket reference,
- The content (or reference to the file), and
- The key, which is the file name.
If you want to upload the actual contents of a file instead of a literal string, use the
file() function. For example, replace the content argument with content = file("/root/finance/finance-2020.doc") to correctly read the file’s contents.terraform apply to upload the file to the S3 bucket.
Applying a Bucket Policy
To grant access to members of an IAM entity named “finance-analysts”, we must attach a bucket policy to the S3 bucket. Note that IAM groups cannot be directly used as principals in S3 bucket policies. Instead, you should use individual IAM users or roles. In this example, we retrieve IAM group details using a data source.IAM groups are not valid principals in S3 bucket policies. To grant access to a group’s members, ensure you reference the ARNs of individual IAM users or roles.
terraform apply, the bucket policy is attached, granting full access to the specified IAM entity.
Below is a sample output when applying the configuration that includes uploading the S3 object:
Conclusion
In this article, we demonstrated how to:- Create an S3 bucket,
- Upload a file to that bucket, and
- Attach a bucket policy using Terraform.