padmasree
padmasree

Reputation: 149

how do we update an already existing iam policy with a new json file using aws cli commands

How do we update an already existing iam policy with a new json file using aws cli commands?

I already have a policy named mypolicy. I want to update this policy with a new json file (which has access to different resources). How do I perform this using aws cli command?

I tried to find the cli command. I found the command below from an AWS page:

aws organizations update-policy \
    --policy-id p-examplepolicyid111 \
    --content "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}}"

However, with this command I did not find any way to replace the policy with new json.

Upvotes: 9

Views: 8870

Answers (2)

Freddie
Freddie

Reputation: 1075

If you have more than 4 policies you will not be able to run the aws iam create-policy-version command. To account for this in one script you can do the following:

#!/bin/bash

POLICY_ARN='arn:aws:iam::1234567890:policy/my-policy'

if [ "$(aws iam list-policy-versions --policy-arn ${POLICY_ARN} | jq -r '.Versions[].VersionId' | wc -l)" -gt 4 ]; then
    OLDEST_VERSION=$(aws iam list-policy-versions --policy-arn ${POLICY_ARN} | \
      jq -r '.Versions |= sort_by(.CreateDate) | .Versions[0].VersionId')
    echo "You have more than 4 versions of ${POLICY_ARN}."
    echo "Deleting oldest version: ${OLDEST_VERSION}"
    aws iam delete-policy-version --policy-arn ${POLICY_ARN} \
       --version-id "${OLDEST_VERSION}"
fi

aws iam create-policy-version --policy-arn ${POLICY_ARN} \
   --policy-document file://new-policy.json --set-as-default

This will delete the oldest version and then create a new version using the policy found in the local file new-policy.json. This file must already exist before you run the above command.

Upvotes: 1

Arun Kamalanathan
Arun Kamalanathan

Reputation: 8583

create policy version.

aws iam create-policy-version 
 --policy-arn arn:aws:iam::123456789012:policy/MyPolicy 
 --policy-document file://NewPolicyVersion.json --set-as-default

https://docs.aws.amazon.com/cli/latest/reference/iam/create-policy-version.html

list policies managed by customer

aws iam list-policies --scope Local

get a policy by arn

aws iam get-policy --policy-arn arn:aws:iam::123456789012:policy/MyPolicy

Upvotes: 8

Related Questions