Python Forum
multiple values as parameters to POST command..
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
multiple values as parameters to POST command..
#11
sorry for multiple iterations, but I'm not able to test myself
boto.resultset.ResultSet is light wrapper around python list class according to docs, yet what you post does not look like list
I have run out of ideas
Reply
#12
looking further - something doesn't look right with the response you post
see this https://stackoverflow.com/a/18950563/4046632
the response there is [Reservation:r-xxxx, Reservation:r-xxxx]
that is response that is consistent with what the docs say, also with the error in your post#6
the last line of the error (I SHOULD have seen this earlier!!!) says TypeError: Reservation:r-00000f4510a2551 "not JSON serializable

note that Reservation:r-00000f4510a2551 is exactly the same format that is returned in the example from SO and does not present in your example response
Reply
#13
Thank you buran for all your patience !

what i posted is what i got....it seems to be issue with response.. though not sure about thie one

but what i believe there is no correct mechenanism to convert boto result set into string output which i was searching

Hmm..
Reply
#14
Hi buran,

at last i am able to get what i need...but there is small issue i am getting formatted text and it posted to slack channel. But the problem now is its posting for one item only..actually i have two server running. However from command line its printing both instance details but onto slack its posting only one of it

#!/usr/bin/env python
#
import json
import subprocess
import sys
import requests

# Function

def awsdescribe():
    p = subprocess.Popen(["aws", "ec2", "describe-instances"], stdout=subprocess.PIPE)
    (output, err) = p.communicate()
    return output
# MAIN
desc = {}
try:
    desc = json.loads(awsdescribe())
except ValueError as ve:
    print
    "Oops! Something went wrong: {}".format(ve)
    sys.exit(1)

for reservations in desc['Reservations']:
    for instances in reservations['Instances']:
        public_ip_address = instances.get('PublicIpAddress', "-") or "-"
        private_ip_address = instances.get('PrivateIpAddress', "-") or "-"
        public_dns_name = instances.get('PublicDnsName', "-") or "-"
        private_dns_name = instances.get('PrivateDnsName', "-") or "-"

        for tags in instances['Tags']:
            key = tags['Key']
            value = tags['Value']
            if key == 'Name':
                tag_name = "{}\t".format(value)
SLACK_CHANNEL = "#xxxxxxx"
HOOK_URL = "https://hooks.slack.com/services/xxxxxx/xxxxxx/xxxxxxxxxx"
MESSAGE = {'text': tag_name + "   "    "is   " + instances['State']['Name']}
response = requests.post(
    HOOK_URL, data=json.dumps(MESSAGE),
    headers={'Content-Type': 'application/json'})

if response.status_code != 200:
    raise ValueError(
        'Request to slack returned an error %s, the response is:\n%s'
        % (response.status_code, response.text)
When I execute from command line, its showing all the instances
State Tag name
stopped abcustomvpcsubnet1
running KNginx

but when i checked slack channel its only showing..

running KNginx

how ever other instance named abcustomvpcsubnet1 not posted to slack channel

do you see placement of POST not proper ? any guidance, why its showing on screen all the records, but not on to slack...

Regards
ASP
Reply
#15
You construct the Message out of the loop, so it has info only for last Instances (why plural by the way?) and last tag_name
I guess when print, you print to screen you do so from within the loop

msg_list = []
for reservation in desc['Reservations']:
    for instance in reservation['Instances']:
        public_ip_address = instance.get('PublicIpAddress', "-") or '-'
        private_ip_address = instance.get('PrivateIpAddress', "-") or '-'
        public_dns_name = instance.get('PublicDnsName', "-") or '-'
        private_dns_name = instance.get('PrivateDnsName', "-") or '-'
        status = instance['State']['Name']
        for tag in instance['Tags']:
            if tag['Key'] == 'Name':
                tag_name = tag["Value"]
                break
        msg_text = '{} is {}'.format(tag_name, status)
        msg_list.append(msg_text)
MESSAGE = {'text': '\n'.join(msg_list)}
Note that the problem still valid for ip addresses - you don't store them anywhere, so out of the loop you will have only last values
Reply
#16
(Feb-23-2018, 11:58 AM)buran Wrote: You construct the Message out of the loop, so it has info only for last Instances (why plural by the way?) and last tag_name
I guess when print, you print to screen you do so from within the loop

msg_list = []
for reservation in desc['Reservations']:
    for instance in reservation['Instances']:
        public_ip_address = instance.get('PublicIpAddress', "-") or '-'
        private_ip_address = instance.get('PrivateIpAddress', "-") or '-'
        public_dns_name = instance.get('PublicDnsName', "-") or '-'
        private_dns_name = instance.get('PrivateDnsName', "-") or '-'
        status = instance['State']['Name']
        for tag in instance['Tags']:
            if tag['Key'] == 'Name':
                tag_name = tag["Value"]
                break
        msg_text = '{} is {}'.format(tag_name, status)
        msg_list.append(msg_text)
MESSAGE = {'text': '\n'.join(msg_list)}
Note that the problem still valid for ip addresses - you don't store them anywhere, so out of the loop you will have only last values

Dance

Beautiful...it works like charm now :) I see both messages in Slack...

How can I just print OK if status is running if other status then its Failed.. within the loop it self ?

Thank you Buran..Much gratitude, Hope to become expert like you soon :)
Reply
#17
>>> x = 'running'
>>> status = x == 'running' and 'OK' or 'Failed'
>>> status
'OK'
>>> x = 'stopped'
>>> status = x == 'running' and 'OK' or 'Failed'
>>> status
'Failed'
>>>
alternative

statuses = {'running': 'OK'}
for reservation in desc['Reservations']:
    for instance in reservation['Instances']:
        status = statuses.get(instance['State']['Name'], 'Failed')
Of course good old if/else would also do the job
Reply
#18
(Feb-23-2018, 12:57 PM)buran Wrote:
>>> x = 'running'
>>> status = x == 'running' and 'OK' or 'Failed'
>>> status
'OK'
>>> x = 'stopped'
>>> status = x == 'running' and 'OK' or 'Failed'
>>> status
'Failed'
>>>
alternative

statuses = {'running': 'OK'}
for reservation in desc['Reservations']:
    for instance in reservation['Instances']:
        status = statuses.get(instance['State']['Name'], 'Failed')
Of course good old if/else would also do the job

Thank you so much buran ! the problem resolved :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  __init__() got multiple values for argument 'schema' dawid294 4 1,876 Jan-03-2024, 09:42 AM
Last Post: buran
  How to combine multiple column values into 1? cubangt 15 2,625 Aug-11-2022, 08:25 PM
Last Post: cubangt
  Substitue multiple substrings in one command Pavel_47 0 799 Jul-18-2022, 01:24 PM
Last Post: Pavel_47
  function accepts infinite parameters and returns a graph with those values edencthompson 0 812 Jun-10-2022, 03:42 PM
Last Post: edencthompson
  Function - Return multiple values tester_V 10 4,316 Jun-02-2021, 05:34 AM
Last Post: tester_V
  How to input & output parameters from command line argument shantanu97 1 2,504 Apr-13-2021, 02:12 PM
Last Post: Larz60+
  Xlsxwriter: Create Multiple Sheets Based on Dataframe's Sorted Values KMV 2 3,441 Mar-09-2021, 12:24 PM
Last Post: KMV
  Looking for help in Parse multiple XMLs and update key node values and generate Out.. rajesh3383 0 1,844 Sep-15-2020, 01:42 PM
Last Post: rajesh3383
  Assigning multiple values using tuple sivacg 2 2,224 Aug-06-2020, 10:29 PM
Last Post: perfringo
  Function parameters and values as string infobound 1 1,728 Jul-24-2020, 04:28 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020