json .decoder.JSONDecodeError: Ожидаемое значение: строка 1, столбец 1 (символ 0), эта ошибка возникает при выполнении кода - PullRequest
0 голосов
/ 13 марта 2020

Я пытаюсь запустить этот python код для создания и обновления стека в AWS путем развертывания шаблона облачной информации. Я поместил шаблон в корзину s3

from __future__ import division, print_function, unicode_literals

from datetime import datetime
import logging
import json
import sys

import boto3
import botocore

cf = boto3.client('cloudformation')
log = logging.getLogger('deploy.cf.create_or_update') 

def lambda_handler(event, context):
    cf = boto3.client('cloudformation')  
    log = logging.getLogger('deploy.cf.create_or_update') 
    main(event['stack_name'], event['template_bucket'], event['template_key'])
def main(stack_name, template_bucket, template_key):
    s3_client = boto3.client('s3')
    cf = boto3.client('cloudformation') 

    template_data = s3_client.get_object(Bucket=template_bucket,Key=template_key)
    template_json_data = template_data['Body'].read(template_data['ContentLength'])
    template_d =json.loads(str(template_json_data))
    template_data_sudeep = str(_parse_template(template_data))
      params = {
        'StackName': stack_name,
        'TemplateBody':template_d
        }

    try:
        if _stack_exists(stack_name):
            print('Updating {}'.format(stack_name))
            stack_result = cf.update_stack(**params)
            waiter = cf.get_waiter('stack_update_complete')
        else:
            print('Creating {}'.format(stack_name))
            stack_result = cf.create_stack(**params)
            waiter = cf.get_waiter('stack_create_complete')
            print("...waiting for stack to be ready...")
            waiter.wait(StackName=stack_name)
    except botocore.exceptions.ClientError as ex:
        error_message = ex.response['Error']['Message']
        if error_message == 'No updates are to be performed.':
            print("No changes")
        else:
            raise
    else:
        print(json.dumps(
            cf.describe_stacks(StackName=stack_result['StackId']),
            indent=2,
            default=json_serial
        ))


def _parse_template(template_data_sudeep):
    with open(template_data_sudeep) as template_fileobj:
     template_data_sudeep = template_fileobj.read()
    cf.validate_template(TemplateURL='https://bu123456.s3.ap-south-1.amazonaws.com/cloudtemplate.json')
    return template_data_sudeep



def _stack_exists(stack_name):
    stacks = cf.list_stacks()['StackSummaries']
    for stack in stacks:
        if stack['StackStatus'] == 'DELETE_COMPLETE':
            continue
        if stack_name == stack['StackName']:
            return True
    return False


def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""
    if isinstance(obj, datetime):
        serial = obj.isoformat()
        return serial
    raise TypeError("Type not serializable")


if __name__ == '__main__':
 main("sudeepstack", "bu123456", "cloudtemplate.json")

Это мой шаблон облачной информации который я поместил в ведро s3.

{
    "Resources": {
        "Ec2Instance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "SecurityGroups": [
                    {
                        "Ref": "InstanceSecurityGroup"
                    }
                ],
                "ImageId": "ami-0d9462a653c34dab7",
                "InstanceType": "t2.micro",
                "AvailabilityZone": "ap-south-1a"
            }
        },
        "InstanceSecurityGroup": {
            "Type": "AWS::EC2::SecurityGroup",
            "Properties": {
                "GroupDescription": "Enable SSH access via port 22",
                "SecurityGroupIngress": [
                    {
                        "IpProtocol": "tcp",
                        "FromPort": "22",
                        "ToPort": "22",
                        "CidrIp": "0.0.0.0/0"
                    }
                ]
            }
        }
    }
}

Я не могу понять проблему. Было бы здорово, если бы кто-нибудь помог мне с этим вопросом. Спасибо.

Traceback (последний последний вызов):

  File "d:/pythonwork/createstacks3.py", line 96, in <module>
    main("sudeepstack", "bu123456", "cloudtemplate.json")
  File "d:/pythonwork/createstacks3.py", line 25, in main
    template_d =json.loads(str(template_json_data))
  File "C:\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

изначально я написал этот код

from __future__ import division, print_function, unicode_literals

from datetime import datetime
import logging
import json
import sys

import boto3
import botocore

cf = boto3.client('cloudformation')  
log = logging.getLogger('deploy.cf.create_or_update')  

def lambda_handler(event, context):
    cf = boto3.client('cloudformation')  
    log = logging.getLogger('deploy.cf.create_or_update')  
    main(event['stack_name'], event['template_bucket'], event['template_key'])
def main(stack_name, template_bucket, template_key):
    s3_client = boto3.client('s3')
    cf = boto3.client('cloudformation') 

    template_data = s3_client.get_object(Bucket=template_bucket,Key=template_key)
    template_json_data = template_data['Body'].read(template_data['ContentLength'])


    template_data = _parse_template(template_data)

    params = {
        'StackName': stack_name,
        'TemplateBody':template_json_data
        }

    try:

        if _stack_exists(stack_name):
            print('Updating {}'.format(stack_name))
            stack_result = cf.update_stack(**params)
            waiter = cf.get_waiter('stack_update_complete')
        else:
            print('Creating {}'.format(stack_name))
            stack_result = cf.create_stack(**params)
            waiter = cf.get_waiter('stack_create_complete')
            print("...waiting for stack to be ready...")
            waiter.wait(StackName=stack_name)
    except botocore.exceptions.ClientError as ex:
        error_message = ex.response['Error']['Message']
        if error_message == 'No updates are to be performed.':
            print("No changes")
        else:
            raise
    else:
        print(json.dumps(
            cf.describe_stacks(StackName=stack_result['StackId']),
            indent=2,
            default=json_serial
        ))


def _parse_template(template_data):
    with open(template_data) as template_fileobj:
     template_data = template_fileobj.read()
    cf.validate_template(TemplateURL='https://bu123456.s3.ap-south-1.amazonaws.com/cloudtemplate.json')
    return template_data





def _stack_exists(stack_name):
    stacks = cf.list_stacks()['StackSummaries']
    for stack in stacks:
        if stack['StackStatus'] == 'DELETE_COMPLETE':
            continue
        if stack_name == stack['StackName']:
            return True
    return False


def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""
    if isinstance(obj, datetime):
        serial = obj.isoformat()
        return serial
    raise TypeError("Type not serializable")


if __name__ == '__main__':

    main("sudeepstack", "bu123456", "cloudtemplate.json")

, но у меня есть эта ошибка

Traceback (most recent call last):
  File "d:/pythonwork/createstacks3.py", line 97, in <module>
    main("sudeepstack", "bu123456", "cloudtemplate.json")
  File "d:/pythonwork/createstacks3.py", line 31, in main
    template_data = _parse_template(template_data)
  File "d:/pythonwork/createstacks3.py", line 65, in _parse_template
    with open(template_data) as template_fileobj:
TypeError: expected str, bytes or os.PathLike object, not dict

Затем я добавил template_d = json .loads (str (template_json_data))

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...