[英]How to create a policy using the AWS CLI
我正在尝试使用 AWS CLI 创建策略。 在此命令中, file://policy
指的是什么?
aws iam create-policy --policy-name my-policy --policy-document file://policy
我试过了:
aws iam create-policy --policy-name mypolicy --policy-document file://mypolicy.json
这是创建策略的正确方法吗?
另外,当我们使用 AWS CLI 创建策略时,有没有一种方法可以直接使用策略 json 的内容? 如果是,请分享一些例子。
file://policy 是指包含您希望用于定义您正在创建的策略的策略声明的本地 json 文件。
您可以使用 CLI 内联执行此操作。 以推荐的 EKS Autoscaler 策略为例:
aws iam create-policy \
--policy-name AmazonEKSClusterAutoscalerPolicy \
--policy-document \
'{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeAutoScalingInstances",
"autoscaling:DescribeLaunchConfigurations",
"autoscaling:DescribeTags",
"autoscaling:SetDesiredCapacity",
"autoscaling:TerminateInstanceInAutoScalingGroup",
"ec2:DescribeLaunchTemplateVersions"
],
"Resource": "*",
"Effect": "Allow"
}
]
}'
我不知道“直接使用 json”是什么意思。 如果您以编程方式创建 json,则可以使用进程替换作为 aws-cli 的文件。
说我有这个“template.json”
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:REGION:ACCOUNT:secret:SECRET"
}
]
}
在这里,我将用sed
替换这些值(我已经包含了命令的标准输出):
% sed 's/REGION/my-region-1/; s/ACCOUNT/my-account-id/; s/SECRET/my-secret-id/' template.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:my-region-1:my-account-id:secret:my-secret-id"
}
]
}
并提供此命令作为进程替换(如临时文件):
aws iam create-policy \
--policy-name MyPolicy \
--policy-document file://<(sed 's/REGION/my-region-1/; s/ACCOUNT/my-account-id/; s/SECRET/my-secret-id/' template.json)
另外,当我们使用 AWS CLI 创建策略时,有没有一种方法可以直接使用策略 json 内容?
有同样的问题,显然,这是不可能的。 很可能他们没有添加对此的支持,因为 JSON 内容有很多空格、换行符等,这会弄乱命令行输入。
我想以自动方式生成多个策略,并使用以下方法:定义一个蓝图 JSON 文件,创建一个读取它的脚本,搜索并替换相关部分,写入一个新文件,并在 aws 中使用该新文件iam 命令。
例如, Powershell 中的这个脚本将标签“NUMBER”替换为“1”:
$nr = "1"
$policy = Get-Content -Path 'policy.json'
$policy_letter = $policy -replace 'NUMBER', $nr
$fileOutput = 'policy_' + $nr+ '.json'
$policy_letter | Set-Content -Path $fileOutput
然后使用此输出文件创建 AWS 策略:
$cmd = "aws iam create-policy --policy-name policy" + $nr + " --policy-document file://./policy_" + $nr + ".json"
cmd /c $cmd
从 json 文件创建策略
aws iam create-policy --policy-name <your-policy-nam> \
--policy-document file://<your-policy-template>.json
如果你想检索策略 arn,你可以:
POLICY_ARN=$(aws iam create-policy --policy-name <your-policy-nam> \
--policy-document file://<your-policy-template>.json \
--output text --query Policy.Arn)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.