簡體   English   中英

TypeError:列表索引必須是整數,而不是str

[英]TypeError : list indices must be integers not str

我想在隊列“ myDownlinQueue”中創建一個指標(觸發器)為roximateNumberOfMessagesVisible的警報,該警報將執行自動縮放AutoScalingGroup的動作。 但是基於我正在編寫的代碼,我得到標題中提到的錯誤。 也許我做錯了,但是下面是導致此錯誤的代碼。

# ==== AutoSCaling config =======================
autoscaling_group = {
"name": "myAG", #descriptive name for your auto scaling group
"min_size": 0 , #Minimum number of instances that should be running at all times
"max_size": 0   #Maximum number of instances that should be running at all times
}


lc_name = 'myLG' #Descriptive name for your launch configuration

#=================AMI to launch======================================================
as_ami = {
"id": "ami-******c", #The AMI ID of the instance your Auto Scaling group will launch
"VpcId" : "vpc-0c805575",
"security_groups": "sg-xxxxxxxa", #The security group(s) your instances will belong to
"instance_type": "t2.micro", #The size of instance that will be launched
"instance_monitoring": True #Indicated whether the instances will be launched with detailed monitoring enabled. Needed to enable CloudWatch
}


conn_reg = boto.ec2.connect_to_region(region_name=awsRegion)
zones = conn_reg.get_all_zones()

zoneStrings = []
for zone in zones:
    zoneStrings.append(zone.name)
    print " Available zones : " + zone.name

conn_vpc = boto.connect_vpc()
subnetids = conn_vpc.get_all_subnets()


conn_as = AutoScaleConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)

lc = LaunchConfiguration(name = lc_name, 
                         image_id = as_ami["id"],
                         instance_type = as_ami["instance_type"],
                         user_data = "user-data.bls",
                         associate_public_ip_address = True,
                         instance_monitoring=as_ami["instance_monitoring"])

conn_as.create_launch_configuration(lc)

ag = AutoScalingGroup(group_name = autoscaling_group["name"], 
                      availability_zones= zoneStrings,
                      vpc_zone_identifier = subnetList,
                      launch_config=lc, min_size = autoscaling_group["min_size"], 
                      max_size = autoscaling_group["max_size"])
conn_as.create_auto_scaling_group(ag)


#=================Create Scaling Policies===================================
# Policy for scaling the number of servers up and down

scalingUpPolicy = ScalingPolicy(name = "myScaleUpPolicy",
                                          adjustment_type ="ChangeInCapacity",
                                          as_name=ag.name,
                                          scaling_adjustment = numInstances ,
                                          cooldown=180)

scalingDownPolicy = ScalingPolicy(name = "myScaleDownPolicy",
                                           adjustment_type= "ExactCapacity",
                                           as_name=ag.name,
                                           scaling_adjustment= 0 ,
                                           cooldown=180)

conn_as.create_scaling_policy(scalingUpPolicy)
conn_as.create_scaling_policy(scalingDownPolicy)


scalingUpPolicy = conn_as.get_all_policies(as_group="myAG", policy_names=["myScaleUpPolicy"])[0]
scalingDownPolicy = conn_as.get_all_policies(as_group="myAG",policy_names=["myScaleDownPolicy"])[0]


# =========== CloudWatch Connection =============
cw = connect_to_region(awsRegion)    

# ===========  SNS Connection ===================
sns = connect_to_region(awsRegion)

cw = CloudWatchConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)
sqs = SQSConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY)



# ==== Alarm =================
numberOfMessages = 1
metric_object = cw.list_metrics(dimensions={"QueueName":"myDownlinkQueue"}, metric_name = "ApproximateNumberOfMessagesVisible",namespace = "AWS/SQS")

alarm_name = "myAlarm"

metric_object["ApproximateNumberOfMessagesVisible"].create_alarm(name =alarm_name, 
                                             comparison=">=", 
                                             threshold = numberOfMessages, 
                                             period = 60, 
                                             evaluation_periods = 1, 
                                             statistic = "Average", 
                                             alarm_actions=[scalingDownPolicy.policy_arn])

錯誤在於最后一種方法-創建警報,精確縮放到DownDownPolicy.policy_arn

OP可能會誤讀文檔或感到困惑。

根據boto2 cloudwatch.list_metric() ,該項目將返回一個list

list_metrics(next_token =無,尺寸=無,metric_name =無,名稱空間=無)

返回有效指標的列表,已記錄數據可用。

因此, metric_object["ApproximateNumberOfMessagesVisible"]TypeError : list indices must be integers not str錯誤TypeError : list indices must be integers not str

OTH,boto3 cloudwatch.list_object返回一個字典。 而且它們不兼容。 但是,沒有一個字典鍵具有roximateNumberOfMessagesVisible。

{
    'Metrics': [
        {
            'Namespace': 'string',
            'MetricName': 'string',
            'Dimensions': [
                {
                    'Name': 'string',
                    'Value': 'string'
                },
            ]
        },
    ],
    'NextToken': 'string'
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM