Reputation: 7424
How to hand over a json resource policy file in AWS CLI create-gateway
command? In this AWS link, it is described how the json itself is passed with the command: Create and Attach an API Gateway Resource Policy to an API - Amazon API Gateway
However, it is cleaner to pass the policy in a file and I tried the following:
aws apigateway create-rest-api \
--name "api-name" \
--policy "file:PolicyDocument.json"
Here is the PolicyDocument.json
that is valid when I copy it via Management Console in the resource policies of the API gateway:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/*",
"Condition": {
"IpAddress": {
"aws:SourceIp": [
"100.101.102.103/32"
]
}
}
}
]
}
It returned the following error:
An error occurred (BadRequestException) when calling the CreateRestApi operation: Invalid policy document. Please check the policy syntax and ensure that Principals are valid.
Upvotes: 0
Views: 1669
Reputation: 2385
It looks like for that CLI command it expects a string value https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-rest-api.html
--policy (string) A stringified JSON policy document that applies to this RestApi regardless of the caller and Method configuration.
I was able to do this with this syntax:
aws apigateway create-rest-api --name 'My First API' --description 'This is my first API' --policy '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"execute-api:Invoke","Resource":"execute-api:/*","Condition":{"IpAddress":{"aws:SourceIp":["100.101.102.103/32"]}}}]}'
OUTPUT:
{
"id": "1122334455",
"name": "My First API",
"description": "This is my first API",
"createdDate": 1561818588,
"apiKeySource": "HEADER",
"endpointConfiguration": {
"types": [
"EDGE"
]
},
"policy": "{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Principal\\\":\\\"*\\\",\\\"Action\\\":\\\"execute-api:Invoke\\\",\\\"Resource\\\":\\\"arn:aws:execute-api:us-east-1:111122223333:91co7q5lj0\\/*\\\",\\\"Condition\\\":{\\\"IpAddress\\\":{\\\"aws:SourceIp\\\":\\\"100.101.102.103\\/32\\\"}}}]}"
}
So the JSON string will need to have it's breaklines and spaces removed in the command. I used this online tool to minify the JSON. https://www.browserling.com/tools/json-minify
You should also be able to minify the json using this command as well.
cat PolicyDocument.json | jq -c
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"execute-api:Invoke","Resource":"execute-api:/*","Condition":{"IpAddress":{"aws:SourceIp":["100.101.102.103/32"]}}}]}
EDIT I just found out that this works as well:
aws apigateway create-rest-api --name 'My First API' --description 'This is my first API' --policy file://PolicyDocument.json
we just needed a //
in front of the path
Upvotes: 1