rubyaws-sdkaws-sdk-ruby

aws-sdk-ruby v3 not giving the iam policy in proper json format


I want to retrieve the policy document associated with the iam role and policy using aws-sdk and ruby. Using aws cli, I am getting the proper output but using aws sdk and ruby getting encrypted json output.

aws iam get-role-policy --role-name=ddp-lambda-s3-ec2 --policy-name=ddp-assumerole-solutionsdev-talos

require 'aws-sdk'
role_name = "ddp-lambda-s3-ec2"
iamclient = Aws::IAM::Client.new()


resp = iamclient.get_role_policy({
  role_name: role_name, # required
  policy_name: "ddp-assumerole-solutionsdev-talos", # required
})

puts resp.policy_document

Using aws cli getting proper output:

$ aws iam get-role-policy --role-name=ddp-lambda-s3-ec2 --policy-name=ddp-assumerole-solutionsdev-talos
{
    "RoleName": "ddp-lambda-s3-ec2",
    "PolicyDocument": {
        "Version": "2012-10-17",
        "Statement": {
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::443233333122:role/ddp_talos_role",
            "Effect": "Allow"
        }
    },
    "PolicyName": "ddp-assumerole-solutionsdev-talos"
}

But when I run above code I get following output:

$ ruby iam.rb
%7B%0D%0A%20%20%20%20%22Version%22%3A%20%222012-10-17%22%2C%0D%0A%20%20%20%20%22Statement%22%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0D%0A%20%20%20%20%20%20%20%20%22Action%22%3A%20%22sts%3AAssumeRole%22%2C%0D%0A%20%20%20%20%20%20%20%20%22Resource%22%3A%20%22arn%3Aaws%3Aiam%3A%3A443299236587%3Arole%2Fddp_talos_role%22%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A

Solution

  • It's always useful to read the API documentation, especially when it doesn't fail but returns something unexpected. Did you see this?

    ...Policies returned by this API are URL-encoded compliant with RFC 3986. You can use a URL decoding method to convert the policy back to plain JSON text... (source)

    URI.decode on your result gives the proper JSON you're looking for...