Bottom Page

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
Quote
#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
Quote
#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..
Quote
#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
Quote
#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
Quote
#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 :)
Quote
#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
Quote
#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 :)
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  How to pass multiple values from one sample to nc variable? Baloch 0 95 Jun-01-2020, 09:27 PM
Last Post: Baloch
  Inserting values from multiple lists sqlite azulu 1 257 May-24-2020, 08:40 AM
Last Post: ibreeden
  UnUnloading values from multiple widgets in a container UGuntupalli 3 248 Apr-20-2020, 08:53 PM
Last Post: UGuntupalli
  Taking Multiple Command Line Argument Input bwdu 6 267 Mar-29-2020, 05:52 PM
Last Post: buran
  Save all values to pandas of multiple classes jenniferruurs 0 260 Sep-13-2019, 12:10 PM
Last Post: jenniferruurs
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 522 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Try for multiple values bluethundr 1 574 Mar-07-2019, 09:04 PM
Last Post: bluethundr
  Help with passing command line input to HTTP POST json sf05wrx 2 489 Feb-25-2019, 11:19 PM
Last Post: sf05wrx
  Get multiple values from function and total it. nirlep 5 784 Feb-05-2019, 06:54 AM
Last Post: nirlep
  comparing multiple values Skaperen 5 7,138 Dec-06-2017, 03:25 AM
Last Post: wavic

Forum Jump:


Users browsing this thread: 1 Guest(s)