Requesting help with yaml syntax for CloudFormation condition function !Join
to specify multiple resource arn values.
I cannot figure out the correct yaml syntax to generate a valid json IAM policy.
Any help would be greatly appreciated.
- CloudFormation Template (yaml):
AWSTemplateFormatVersion: 2010-09-09
Parameters:
AdminRoleHaveRLP:
Type: String
Default: 'Yes'
AllowedValues:
- 'Yes'
- 'No'
TestPolicyName:
Type: String
Default: test-service-role-policy
TestServiceRole1:
Type: String
Default: test-service-role1
TestServiceRole2:
Type: String
Default: test-service-role2
Conditions:
AdminRoleHasRLP: !Equals
- 'Yes'
- !Ref AdminRoleHaveRLP
Resources:
Policy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
ManagedPolicyName: !Ref TestPolicyName
Path: /
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: ServiceRolePolicy
Effect: Allow
Action:
- 'iam:AttachRolePolicy'
Resource:
- !If
- AdminRoleHasRLP
- !Join ['', ['arn:aws:iam::*:role/', !Ref TestServiceRole1,',', 'arn:aws:iam::*:role/', !Ref TestServiceRole2]]
- 'arn:aws:iam::*:role/*'
- IAM Policy Output When Parameter AdminRoleHaveRLP=Yes:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"iam:AttachRolePolicy"
],
"Resource": [
"arn:aws:iam::*:role/test-service-role1,arn:aws:iam::*:role/test-service-role2"
],
"Effect": "Allow",
"Sid": "ServiceRolePolicy"
}
]
}
- Expected Policy Output:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"iam:AttachRolePolicy"
],
"Resource": [
"arn:aws:iam::*:role/test-service-role1",
"arn:aws:iam::*:role/test-service-role2"
],
"Effect": "Allow",
"Sid": "ServiceRolePolicy"
}
]
}
CodePudding user response:
The normal and easier way to to define your policy is with Sub
, not Join
:
AWSTemplateFormatVersion: 2010-09-09
Parameters:
AdminRoleHaveRLP:
Type: String
Default: 'Yes'
AllowedValues:
- 'Yes'
- 'No'
TestPolicyName:
Type: String
Default: test-service-role-policy
TestServiceRole1:
Type: String
Default: test-service-role1
TestServiceRole2:
Type: String
Default: test-service-role2
Conditions:
AdminRoleHasRLP: !Equals
- 'Yes'
- !Ref AdminRoleHaveRLP
Resources:
Policy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
ManagedPolicyName: !Ref TestPolicyName
Path: /
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: ServiceRolePolicy
Effect: Allow
Action:
- 'iam:AttachRolePolicy'
Resource:
!If
- AdminRoleHasRLP
- - !Sub 'arn:aws:iam::*:role/${TestServiceRole1}'
- !Sub 'arn:aws:iam::*:role/${TestServiceRole2}'
- 'arn:aws:iam::*:role/*'