Skip to content

Instantly share code, notes, and snippets.

@karlkranich
Last active July 15, 2021 21:43
Show Gist options
  • Save karlkranich/cd27f8bda64aa9e1cdab6cb52eaafcd8 to your computer and use it in GitHub Desktop.
Save karlkranich/cd27f8bda64aa9e1cdab6cb52eaafcd8 to your computer and use it in GitHub Desktop.
CloudFormation templates (json and yml) that conditionally include a user and a statement
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Bucket policy testing",
"Parameters": {
"ReadWriteUser": {
"Type": "String",
"Default": "",
"Description": "arn of read-write user to add to bucket policy"
},
"ReadOnlyUser": {
"Type": "String",
"Default": "",
"Description": "arn of read-only user to add to bucket policy"
}
},
"Conditions": {
"HasReadWriteUser": {
"Fn::Not": [
{
"Fn::Equals": [
{
"Ref": "ReadWriteUser"
},
""
]
}
]
},
"HasReadOnlyUser": {
"Fn::Not": [
{
"Fn::Equals": [
{
"Ref": "ReadOnlyUser"
},
""
]
}
]
}
},
"Resources": {
"KwkBucketPolicy": {
"Type": "AWS::S3::BucketPolicy",
"Properties": {
"Bucket": "kwk-bucket-policy-tests",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:Get*",
"s3:Put*"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::kwk-bucket-policy-tests/*",
"Principal": {
"AWS": [
"arn:aws:iam::123456789012:user/user1",
{
"Fn::If": [
"HasReadWriteUser",
{
"Ref": "ReadWriteUser"
},
{
"Ref": "AWS::NoValue"
}
]
}
]
}
},
{
"Fn::If": [
"HasReadOnlyUser",
{
"Action": [
"s3:Get*"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::kwk-bucket-policy-tests/*",
"Principal": {
"AWS": {
"Ref": "ReadOnlyUser"
}
}
},
"Ref": "AWS::NoValue"
]
}
]
}
}
}
}
}
AWSTemplateFormatVersion: 2010-09-09
Description: Bucket policy testing
Parameters:
ReadWriteUser:
Type: String
Default: ""
Description: arn of read-write user to add to bucket policy
ReadOnlyUser:
Type: String
Default: ""
Description: arn of read-only user to add to bucket policy
Conditions:
HasReadWriteUser: !Not
- !Equals
- !Ref ReadWriteUser
- ""
HasReadOnlyUser: !Not
- !Equals
- !Ref ReadOnlyUser
- ""
Resources:
KwkBucketPolicy:
Type: "AWS::S3::BucketPolicy"
Properties:
Bucket: kwk-bucket-policy-tests
PolicyDocument:
Version: 2012-10-17
Statement:
- Action:
- "s3:Get*"
- "s3:Put*"
Effect: Allow
Resource: "arn:aws:s3:::kwk-bucket-policy-tests/*"
Principal:
AWS:
- "arn:aws:iam::123456789012:user/user1"
- !If
- HasReadWriteUser
- !Ref ReadWriteUser
- !Ref "AWS::NoValue"
- !If
- HasReadOnlyUser
- Action:
- "s3:Get*"
Effect: Allow
Resource: "arn:aws:s3:::kwk-bucket-policy-tests/*"
Principal:
AWS: !Ref ReadOnlyUser
- !Ref "AWS::NoValue"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment