简体   繁体   中英

AWS CLI retrieve the ARN of the newly created policy

I want to create an IAM policy and attach it to some IAM role using AWS command-line interface.

Creating policy is quite simple:

aws iam create-policy --policy-name "${policy_name}" --policy-document file://policy.json

But to attach the newly created policy to the target role I must know the ARN of the policy:

aws iam attach-role-policy --role-name "${role_name}" --policy-arn "${policy_arn}"

What is the correct way to retrieve ARN of the newly created policy?

Right now I'm construcing policy_arn myself using policy_name and the account_id :

policy_arn=arn:aws:iam::"${account_id}":policy/"${policy_name}"

This is how I retrieve the account_id :

account_id=$(aws ec2 describe-security-groups --query 'SecurityGroups[0].OwnerId' --output text)

However this feels quite hacky.

Is there a better way to find out ARN of the created policy?

If you add --output text to your create-policy , it will print the ARN.

aws iam create-policy --policy-name "${policy_name}" --policy-document file://policy.json --output text

You can get the policies and their ARN:

aws iam list-policies --query 'Policies[*].[PolicyName, Arn]' --output text

To get the ARN for just one policy:

aws iam list-policies --query 'Policies[?PolicyName==`FullAccess`].Arn' --output text

Output:

arn:aws:iam::aws:policy/FullAccess

You may also try this

POLICY_ARN=$(aws iam create-policy --policy-name xxx --policy-document file://xxx.json --output text --query Policy.Arn)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM