How to fetch the action value from AWS policy document and store it as list? - python-3.x

I need to fetch "Action" values from the AWS policy document.
In some policies, the action values are having a list of values(like Policy 1) and in some policies, the action is having a single value which is a string (like Policy 2).
What I need is:
I want to get the action value from the policy and store it as a list.
(Here, Policy 1 is giving expected output but policy 2 is failing.)
Policy 1:
document_values:
[{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': ['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed'],'Resource': ['arn:aws:iam::*:policy/*','arn:aws:iam::*:instance-profile/*']}, {'Sid': 'VisualEditor1', 'Effect': 'Allow', 'Action': ['iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups'],'Resource': '*'}]}]
Output - Policy 1:
['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed','iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups']
Policy 2:
document_values:
[{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': 'sts:AssumeRole', 'Resource':'*"}]}]
Output-Policy2:
['s', 't', 's', ':', 'A', 's', 's', 'u', 'm', 'e', 'R', 'o', 'l', 'e']
Expected output from policy2:
['sts:AsseumeRole']
Python-Code:
I'm executing the same code for both the policies.
inline_services = [j for i in [i['Action'] for i in document_values[0]['Statement']] for j in i]
print(inline_services)
How to fetch the action value from the policy document irrespective of string or list..?

Instead of writing long list comprehension, you could just create simple function:
p1 = [{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': ['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed'],'Resource': ['arn:aws:iam::*:policy/*','arn:aws:iam::*:instance-profile/*']}, {'Sid': 'VisualEditor1', 'Effect': 'Allow', 'Action': ['iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups'],'Resource': '*'}]}]
p2 = [{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': 'sts:AssumeRole', 'Resource':'*'}]}]
def get_actions(policy_doc):
actions_list = []
for i in policy_doc[0]['Statement']:
actions_list += i['Action'] if isinstance(i['Action'], list) else [i['Action']]
return actions_list
print(get_actions(p1))
print(get_actions(p2))
Output:
['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed', 'iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups']
['sts:AssumeRole']

Related

Syntax Error: TypeError: Cannot read property 'kind' of null for Enum using Vue 3 and TypeScript

I'm defining an enum within a Vue 3 component like so:
<script lang="ts">
import { defineComponent } from 'vue'
export enum PieceType
{
None,
Pawn,
Rook,
Knight,
Bishop,
Queen,
King
}
export interface Piece
{
position: Position,
type: PieceType,
}
export interface Position
{
row: number,
col: number
}
export default defineComponent({
props: {
type: String,
row: Number,
col: Number
},
setup(props) {
const getPiece = (piece: string) =>
{
console.log("Piece is:", piece)
switch(piece)
{
case "R": return PieceType.Rook;
case "K": return PieceType.Knight;
case "B": return PieceType.Bishop;
case "Q": return PieceType.Queen;
case "K": return PieceType.King;
case "P": return PieceType.Pawn;
case "-": return PieceType.None;
default: throw new Error("Invalid piece.")
}
}
return {
type: getPiece(props.type),
position: {row: props.row, col: props.col}
}
}
})
</script>
When I import the component into another component (the component equals Piece):
<script lang="ts">
import { defineComponent } from '#vue/composition-api';
import { Piece } from "../components/Piece";
export default defineComponent({
components: [Piece],
props: {
},
setup() {
const board =
[
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
];
return { board }
}
})
</script>
I get the following error:
Syntax Error: TypeError: Cannot read property 'kind' of null
Occurred while linting > .\components\Piece.vue:39
at Array.forEach (<anonymous>)
at Array.forEach (<anonymous>)
# ./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/components/Board.vue?vue&type=script&lang=ts 3:0-44 6:15-20
# ./src/components/Board.vue?vue&type=script&lang=ts
# ./src/components/Board.vue
# ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/App.vue?vue&type=script&lang=js
# ./src/App.vue?vue&type=script&lang=js
# ./src/App.vue
# ./src/main.js
# multi (webpack)-dev-server/client?http://192.168.3.235:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
The error is occurring at the line:
case "R": return PieceType.Rook
I noticed that if I get rid of the Enum and replace it with strings then it works, but I don't see why the Enum isn't working. The error isn't showing up in my intellisense in vscode and I'm not using the component in a for loop anywhere to trigger the "Array.ForEach" in the error. Any help would be appreciated!
My issue was I didn't run "vue add typescript" to add typescript to the project. I had other issues with how I declared the components, but that was ultimately the issue.

password generator with logging

import random, logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
file_handler = logging.FileHandler('student.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
mylist = ['Aa', 'Bb', 'Cc', 'Dd', 'Ee', 'Ff', 'Gg', 'Hh', 'Ii', 'Jj', 'Kk', 'Ll', 'Mm', 'Nn',
'Oo', 'Pp', 'Qq', 'Rr', 'Ss', 'Tt', 'Uu', 'Vv', 'Ww', 'Xx', 'Yy', 'Zz', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '!', '#', '#', '$', '%', '^', '&', '*', '~']
def generatePassword(num):
password = ''
for x in range(mylist):
return password
logging.debug(generatePassword,16)
When I execute the code, complier says that x is an unused variable. Is there a way to fix this? Also, is there any error with how I wrote the logging functions?
You are currently not using x inside your loop, hence the unused variable warning.
Regardless, consider using random.choices if you want to allow the password to possibly contain the same character twice or or random.sample if you don't:
import random
def generate_password(length, unique_chars_ignore_case=False):
my_list = [
'Aa', 'Bb', 'Cc', 'Dd', 'Ee', 'Ff', 'Gg', 'Hh', 'Ii', 'Jj', 'Kk', 'Ll',
'Mm', 'Nn', 'Oo', 'Pp', 'Qq', 'Rr', 'Ss', 'Tt', 'Uu', 'Vv', 'Ww', 'Xx',
'Yy', 'Zz', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '#',
'#', '$', '%', '^', '&', '*', '~'
]
random_func = random.choices if not unique_chars_ignore_case else random.sample
return ''.join([
x if len(x) == 1 else x[random.randint(0, 1)]
for x in random_func(my_list, k=length)
])
Example Usage allows repeats:
>>> generate_password(6)
C9#cs2
Example Usage only unique characters ignore case:
>>> generate_password(6, unique_chars_ignore_case=True))
k*065#

Pulling item properties from Microsoft Sharepoint document library with Microsoft Graph API

I'm able to successfully pull file metadata from my SharePoint library with the Microsoft Graph API, but am having trouble pulling the properties of an item:
I can get a partial list of properties using this endpoint:
https://graph.microsoft.com/v1.0/sites/{site-id}/drives/{}/items/{}/children?$expand=listItem($expand=fields)
But the list that comes from this endpoint doesn't match the list of properties that exists on the item.
For example, below is a list of fields that come from that endpoint - you can see that '.Push Too Salsify.' (one of the fields I need) is not present. There are also other fields that exist but don't appear in the item properties:
{'ParentLeafNameLookupId': '466', 'CLIPPING_x0020_STATUS': 'Not Started', 'Edit': '0', 'EditorLookupId': '67', '_ComplianceTagWrittenTime': '', 'RequiredField': 'teams/WORKFLOWDEMO/Shared Documents/1062CQP6.Phase4/1062CQP-Phase4-Size.tif', 'PM_x0020_SIGN_x0020_OFF': 'No', 'QA_x0020_APPROVED': 'No', 'ImageWidth': 3648, 'PM_x0020_Approval_x0020_Status': '-', 'AuthorLookupId': '6', 'SelectedFlag': '0', 'NameOrTitle': '1062CQP-Phase4-Size.tif', 'ItemChildCount': '0', 'FolderChildCount': '0', 'LinkFilename': '1062CQP-Phase4-Size.tif', 'ParentVersionStringLookupId': '466', 'PHOTOSTATUS': 'Not Started', '#odata.etag': '"c4b7516e-64df-46d2-b916-a1ee6f29d24a,8"', 'Thumbnail': '3648', '_x002e_Approval_x0020_Status_x002e_': 'Approved', 'Date_x0020_Created': '2019-10-09T04:25:40Z', '_CommentCount': '', 'Created': '2019-10-09T04:25:33Z', 'PreviewOnForm': '0', '_ComplianceTag': '', 'FileLeafRef': '1062CQP-Phase4-Size.tif', 'ImageHeight': 3648, 'LinkFilenameNoMenu': '1062CQP-Phase4-Size.tif', '_ComplianceFlags': '', 'ContentType': 'Document', 'Preview': '3648', 'ImageSize': '3648', 'Product_x0020_Category': 'Baseball', 'DATE_x0020_ASSIGNED': '2019-10-09T04:25:40Z', 'DateCreated': '2019-10-09T04:25:40Z', 'WORKFLOW_x0020_SELECTION': ['Select'], 'Predecessors': [], 'FileType': 'tif', 'LEGAL_x0020_APPROVED': 'No', 'PUSH_x0020_READY': False, 'FileSizeDisplay': '74966432', 'id': '466', '_LikeCount': '', '_ComplianceTagUserId': '', 'Modified': '2019-10-09T14:41:25Z', 'DocIcon': 'tif', '_UIVersionString': '0.7', '_CheckinComment': ''}
Any help would be greatly appreciated. I've scoured the documentation and can't seem to find the correct endpoint to pull item properties from a Sharepoint DriveItem.

how to attach AWS scp-organization unit's (OUs) policies to particular organization unit(OU) using python script?

YAML file:
Organization-unit:
xyz
Organization-unit:
xyz2
Policies:
- name: scp-xyz
description:
- name: scp-xyz2
description:
using python how to attach xyz organization unit to scp-xyz only under aws organization.
output: list of policies and organization unit info
{'Policies': [{'Id': 'p-xw7j86as', 'Arn': '', 'Name': 'scp-xyz', 'Description': 'Allows access to every operation', 'Type': 'SERVICE_CONTROL_POLICY', 'AwsManaged': True}
{'Policies': [{'Id': 'p-xw7j006as', 'Arn': '', 'Name': 'scp-xyz2', 'Description': 'Allows access to every operation', 'Type': 'SERVICE_CONTROL_POLICY', 'AwsManaged': True}
{'OrganizationalUnit': {'Id': 'ou-uwjh-87', 'Arn': 'a', 'Name': 'xyz'}
{'OrganizationalUnit': {'Id': 'ou-uw-87', 'Arn': 'a', 'Name': 'xyz2'}
I have below sample to attach policy to OU:
response = client.attach_policy(
PolicyId='string', #policy ID string requires "p-" followed by from 8 to
128 lower-case letters or digits.
TargetId='string' # ID of OU
)
Can anyone please guide me how can I do this task ?
REsult should be like below :
[![SCP-xyz policy should attach with xyz organization unit][1]][1]

how to make parse of list(string) not list(char) in parse argument of list?

I use flask_restful in flask
My code like:
from flask_restful import Resource, reqparse
apilink_parser = reqparse.RequestParser()
apilink_parser.add_argument('provider_id', type=int,required=True)
apilink_parser.add_argument('name', type=str, required=True)
apilink_parser.add_argument('func_id', type=int)
apilink_parser.add_argument('method', type=str)
apilink_parser.add_argument('url', type=str)
apilink_parser.add_argument('parameter',type=list)
apilink_parser.add_argument("expectreturn", type=list)
#marshal_with(apilink_fields)
def post(self):
args = apilink_parser.parse_args()
print(args)
# user owns the task
task = APILink.create(**args)
return task, 201
My json post data like:
{
"name":"riskiqwhois",
"provider_id":1,
"func_id":1,
"url":"myurl",
"parameter":["query"], //******//
"expectreturn":[],
"method":"post"
}
but when I print the arrgs the result is:
{
'provider_id': 1,
'name': 'riskiqwhois',
'func_id': 1,
'method': 'post',
'url': 'myurl',
'parameter': ['q', 'u', 'e', 'r', 'y'], //******//
'expectreturn': None
}
I want
You can see I want parameter is list of string which is only one element named "query", but the real parameter tranlate into the database is ['q', 'u', 'e', 'r', 'y'], How to make the parameter is list of string not list of char? how to make sure the data is list(string)?
Well, you forgot to set action="append" and you should change from type=list to type=str.
If not, you will still be getting a result like [['q', 'u', 'e', 'r', 'y']].
...
apilink_parser.add_argument('parameter',type=str, action='append')
apilink_parser.add_argument("expectreturn", type=str, action='append')
You can solve this problem by adding action="append" to your request parser
like below
apilink_parser.add_argument('parameter',type=str,action="append")
apilink_parser.add_argument("expectreturn", type=list,action="append")
this will return you below output
{
'provider_id': 1,
'name': 'riskiqwhois',
'func_id': 1,
'method': 'post',
'url': 'myurl',
'parameter': ['query'],
'expectreturn': None
}

Resources