SAT9/.resources/ba3c312a4e2be0fa7930407b450745034e520bf70267d4902135376199c71020
2025-04-18 19:44:27 +04:00

103 lines
2.7 KiB
Plaintext

from urllib2_aws4auth import aws_urlopen, Request
from urllib2 import HTTPError
from urllib import urlencode
import json
import system
import boto3
from pprint import pformat
REGION ='us-west-2'
def openSession():
CREDS = boto3.Session().get_credentials()
AWS_ACCESS_KEY_ID = CREDS.access_key
AWS_SECRET_ACCESS_KEY = CREDS.secret_key
TOKEN = CREDS.token
CREDSRETURN = {'AccessKeyId':AWS_ACCESS_KEY_ID,
'SecretAccessKey':AWS_SECRET_ACCESS_KEY,
'SessionToken':TOKEN}
# OPENER = aws_urlopen(
# AWS_ACCESS_KEY_ID,
# AWS_SECRET_ACCESS_KEY,
# REGION,
# SERVICE,
# session_token=TOKEN,
# verify=False)
# return OPENER
return CREDSRETURN
def DynamoWriter(payload):
import json
from pprint import pformat
import boto3
from datetime import datetime
from decimal import Decimal
import time
LOGGER = system.util.getLogger('notify_to_dynamodb_log')
roleArn = 'arn:aws:iam::533266954132:role/ignition_to_aws_scada_notify'
# Get STAGE variable
STAGE = 'alpha'
# Make sure STAGE is valid. no gamma stage configured
if STAGE not in ['alpha', 'beta', 'gamma', 'prod']:
STAGE = 'beta'
if STAGE == 'gamma':
STAGE = 'beta'
STAGE_CONFIG = {
'alpha':{
'region' : 'us-west-2',
'roleArn' : roleArn,
'tableName' : 'NotificationsEntries'
},
'beta': {
'region':'us-west-2',
'roleArn': roleArn,
'tableName' : 'NotificationsEntries'
},
'prod': {
'region':'us-west-2',
'roleArn': roleArn,
'tableName' : 'NotificationsEntries'
}
}
# create sts session to get credentials from EC2
sts_client = boto3.client('sts')
region_name = STAGE_CONFIG.get(STAGE, 'beta').get('region', 'us-west-2')
assume_role_response = sts_client.assume_role(
RoleArn = STAGE_CONFIG.get(STAGE, 'alpha').get('roleArn',roleArn),
RoleSessionName = 'AssumeRole'
)
# arn:aws:iam::905418448057:role/ignition_to_aws_scada_notify
temp_credentials = assume_role_response['Credentials']
# create session using the temp creds
b3_session = boto3.Session(
aws_access_key_id = temp_credentials['AccessKeyId'],
aws_secret_access_key = temp_credentials['SecretAccessKey'],
aws_session_token = temp_credentials['SessionToken'],
region_name = 'us-west-2',
)
# create a dynamodb session
dynamodb = b3_session.resource('dynamodb')
table = dynamodb.Table(STAGE_CONFIG.get(STAGE, 'beta').get('tableName', 'NotificationsEntries'))
# write data directly to dynamodb table
try:
response = table.put_item(TableName='NotificationsEntries',Item= payload)
# system.perspective.print(response)
system.perspective.print('Write to NotificationsEntries DynamoDB Table Successful')
except Exception as e:
system.perspective.print('Write to NotificationsEntries DynamoDB Table NOT Successful')
system.perspective.print(str(e))
LOGGER.error(str(e))