简体   繁体   中英

TypeError : list indices must be integers not str

I'd like to create an alarm whose metric (trigger) is ApproximateNumberOfMessagesVisible in a Queue 'myDownlinQueue', the alarm takes the action of autoscaling an AutoScalingGroup. However based on the code I am writing I get the error mentioned in the title. Maybe I am doing it wrong, but below is the code that causes this error.

# ==== 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])

The error is in the last method - creating an alarm, precisely scalingDownPolicy.policy_arn

Either OP misread the documentation or confuse.

According to boto2 cloudwatch.list_metric() , the item will return a list .

list_metrics(next_token=None, dimensions=None, metric_name=None, namespace=None)

Returns a list of the valid metrics for which there is recorded data available.

So metric_object["ApproximateNumberOfMessagesVisible"] will kick error TypeError : list indices must be integers not str

OTH, boto3 cloudwatch.list_object return a dict. And they are NOT compatible. However, none of the dictionary key having ApproximateNumberOfMessagesVisible.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM