Error updating configuration template in AWS Bean Stalk - amazon-elastic-beanstalk

I tried to Update the configuration settings of a Configuration Template say "Beta Configuration" on Bean stalk with the following commands, but its throwing a error -
C:\Users\anand\Desktop>elastic-beanstalk-update-configuration-template -a "Application XYZ" -t Beta Configuration -d New Beta Configuration -s 32bit Amazon Linux
running Tomcat 7 -f options.txt
the settings in options.txt are -
<pre>{"ApplicationName"=>"Application XYZ", "DateCreated"=>1314430489.771, "DateUpd
ated"=>1314430489.771, "DeploymentStatus"=>nil, "Description"=>"", "EnvironmentN
ame"=>nil, "OptionSettings"=>[{"Namespace"=>"aws:elasticbeanstalk:sns:topics", "
OptionName"=>"Notification Topic Name", "Value"=>""}, {"Namespace"=>"aws:autosca
ling:trigger", "OptionName"=>"BreachDuration", "Value"=>"5"}, {"Namespace"=>"aws
:autoscaling:trigger", "OptionName"=>"LowerBreachScaleIncrement", "Value"=>"-1"}
, {"Namespace"=>"aws:elasticbeanstalk:application:environment", "OptionName"=>"A
WS_ACCESS_KEY_ID", "Value"=>""}, {"Namespace"=>"aws:elb:healthcheck", "OptionNam
e"=>"UnhealthyThreshold", "Value"=>"5"}, {"Namespace"=>"aws:elasticbeanstalk:app
lication:environment", "OptionName"=>"AWS_SECRET_KEY", "Value"=>""}, {"Namespace
"=>"aws:autoscaling:trigger", "OptionName"=>"LowerThreshold", "Value"=>"10"}, {"
Namespace"=>"aws:elasticbeanstalk:sns:topics", "OptionName"=>"Notification Endpo
int", "Value"=>"sanand#indavest.com"}, {"Namespace"=>"aws:autoscaling:launchco
nfiguration", "OptionName"=>"SecurityGroups", "Value"=>"elasticbeanstalk-default
, default, GSUI-Base"}, {"Namespace"=>"aws:elb:loadbalancer", "OptionName"=>"SSL
CertificateId", "Value"=>""}, {"Namespace"=>"aws:elasticbeanstalk:application:en
vironment", "OptionName"=>"PARAM5", "Value"=>""}, {"Namespace"=>"aws:elasticbean
stalk:application:environment", "OptionName"=>"JDBC_CONNECTION_STRING", "Value"=
>""}, {"Namespace"=>"aws:elb:healthcheck", "OptionName"=>"Timeout", "Value"=>"5"
}, {"Namespace"=>"aws:autoscaling:asg", "OptionName"=>"Cooldown", "Value"=>"360"
}, {"Namespace"=>"aws:autoscaling:asg", "OptionName"=>"Custom Availability Zones
", "Value"=>""}, {"Namespace"=>"aws:elasticbeanstalk:monitoring", "OptionName"=>
"Automatically Terminate Unhealthy Instances", "Value"=>"true"}, {"Namespace"=>"
aws:elasticbeanstalk:container:tomcat:jvmoptions", "OptionName"=>"XX:MaxPermSize
", "Value"=>"512m"}, {"Namespace"=>"aws:autoscaling:trigger", "OptionName"=>"Uni
t", "Value"=>"Percent"}, {"Namespace"=>"aws:elasticbeanstalk:container:tomcat:jv
moptions", "OptionName"=>"Xmx", "Value"=>"512m"}, {"Namespace"=>"aws:elasticbean
stalk:application", "OptionName"=>"Application Healthcheck URL", "Value"=>"/"},
{"Namespace"=>"aws:autoscaling:asg", "OptionName"=>"Availability Zones", "Value"
=>"Any 1"}, {"Namespace"=>"aws:elasticbeanstalk:sns:topics", "OptionName"=>"Noti
fication Topic ARN", "Value"=>""}, {"Namespace"=>"aws:elasticbeanstalk:container
:tomcat:jvmoptions", "OptionName"=>"JVM Options", "Value"=>"-Duser.timezone=Amer
ica/New_York"}, {"Namespace"=>"aws:elasticbeanstalk:application:environment", "O
ptionName"=>"PARAM1", "Value"=>""}, {"Namespace"=>"aws:elb:loadbalancer", "Optio
nName"=>"LoadBalancerHTTPSPort", "Value"=>"OFF"}, {"Namespace"=>"aws:elb:healthc
heck", "OptionName"=>"Interval", "Value"=>"30"}, {"Namespace"=>"aws:autoscaling:
trigger", "OptionName"=>"UpperBreachScaleIncrement", "Value"=>"1"}, {"Namespace"
=>"aws:autoscaling:trigger", "OptionName"=>"UpperThreshold", "Value"=>"70"}, {"N
amespace"=>"aws:autoscaling:launchconfiguration", "OptionName"=>"ImageId", "Valu
e"=>"ami-847xv6ea"}, {"Namespace"=>"aws:autoscaling:asg", "OptionName"=>"MinSize
", "Value"=>"1"}, {"Namespace"=>"aws:elasticbeanstalk:sns:topics", "OptionName"=
>"Notification Protocol", "Value"=>"email"}, {"Namespace"=>"aws:elasticbeanstalk
:hostmanager", "OptionName"=>"LogPublicationControl", "Value"=>"true"}, {"Namesp
ace"=>"aws:autoscaling:launchconfiguration", "OptionName"=>"MonitoringInterval",
"Value"=>"5 minute"}, {"Namespace"=>"aws:elasticbeanstalk:application:environme
nt", "OptionName"=>"PARAM2", "Value"=>""}, {"Namespace"=>"aws:elb:policies", "Op
tionName"=>"Stickiness Cookie Expiration", "Value"=>"0"}, {"Namespace"=>"aws:elb
:healthcheck", "OptionName"=>"HealthyThreshold", "Value"=>"3"}, {"Namespace"=>"a
ws:elasticbeanstalk:application:environment", "OptionName"=>"PARAM4", "Value"=>"
"}, {"Namespace"=>"aws:elb:policies", "OptionName"=>"Stickiness Policy", "Value"
=>"true"}, {"Namespace"=>"aws:autoscaling:trigger", "OptionName"=>"Statistic", "
Value"=>"Average"}, {"Namespace"=>"aws:autoscaling:trigger", "OptionName"=>"Meas
ureName", "Value"=>"CPUUtilization"}, {"Namespace"=>"aws:elasticbeanstalk:applic
ation:environment", "OptionName"=>"PARAM3", "Value"=>""}, {"Namespace"=>"aws:aut
oscaling:launchconfiguration", "OptionName"=>"EC2KeyName", "Value"=>"indavest"},
{"Namespace"=>"aws:autoscaling:asg", "OptionName"=>"MaxSize", "Value"=>"2"}, {"
Namespace"=>"aws:autoscaling:trigger", "OptionName"=>"Period", "Value"=>"5"}, {"
Namespace"=>"aws:elb:loadbalancer", "OptionName"=>"LoadBalancerHTTPPort", "Value
"=>"80"}, {"Namespace"=>"aws:autoscaling:launchconfiguration", "OptionName"=>"In
stanceType", "Value"=>"c1.medium"}, {"Namespace"=>"aws:elasticbeanstalk:containe
r:tomcat:jvmoptions", "OptionName"=>"Xms", "Value"=>"256m"}], "SolutionStackName
"=>"32bit Amazon Linux running Tomcat 7", "TemplateName"=>"Beta Configuration"}
</pre>
The error am getting is -
<pre>710: unexpected token at '{"ApplicationName"=>"General Sentiment", "DateCreated"
=>1314430489.771, "DateUpdated"=>1314430489.771, "DeploymentStatus"=>nil, "Description"=>"", "EnvironmentName"=>nil, "OptionSettings"=>[{"Namespace"=>"aws:elasticbeanstalk:sns:topics", " ....................................</pre>
please suggest me a solution for this error

the options.txt file should only be providing the data for the OptionSettings key in that data structure. Remove this from the top so the file starts with a [:
{
"ApplicationName" = > "Application XYZ", "DateCreated" = > 1314430489.771, "DateUpd
ated" = > 1314430489.771, "DeploymentStatus" = > nil, "Description" = > "", "EnvironmentN
ame" = > nil, "OptionSettings" = > [

Related

Having problems using google cloud functions

message: "Build failed: *** Error compiling './main.py'...
File "./main.py", line 85
"prompt": prompt,
^
SyntaxError: invalid syntax; Error ID: 49c34848"
if user_request == "longer responses":
model_config = {
"engine": "gpt3",
"model": ["text-davinci-002", "text-davinci-003", "text-curie-001", "text-babbage-001", "text-ada-001",]
"prompt": prompt,
"temperature": 0.9, # set the temperature to a high value
"max_tokens": 300, # set the max_tokens filter to 160 tokens
It doesnt work. I tried add ing semicolons. It doesnt work
I think your code is incorrect, it remains } character to write correctly the Python Dict. I also removed a useless coma in the array :
if user_request == "longer responses":
model_config = {
"engine": "gpt3",
"model": ["text-davinci-002", "text-davinci-003", "text-curie-001", "text-babbage-001", "text-ada-001"]
"prompt": prompt,
"temperature": 0.9, # set the temperature to a high value
"max_tokens": 300 # set the max_tokens filter to 160 tokens
}

How to send json message body in aws SNS using console

I am doing a hands on where I want to add an SNS trigger to a lambda function which then sends a message to a slack channel. There is a blueprint for this lambda in python and also a template test event which looks like the following
{
"Records": [
{
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:EXAMPLE",
"EventSource": "aws:sns",
"Sns": {
"SignatureVersion": "1",
"Timestamp": "1970-01-01T00:00:00.000Z",
"Signature": "EXAMPLE",
"SigningCertUrl": "EXAMPLE",
"MessageId": "12345",
"Message": {
"AlarmName": "SlackAlarm",
"NewStateValue": "OK",
"NewStateReason": "Threshold Crossed: 1 datapoint (0.0) was not greater than or equal to the threshold (1.0)."
},
"MessageAttributes": {
"Test": {
"Type": "String",
"Value": "TestString"
},
"TestBinary": {
"Type": "Binary",
"Value": "TestBinary"
}
},
"Type": "Notification",
"UnsubscribeUrl": "EXAMPLE",
"TopicArn": "arn:aws:sns:EXAMPLE",
"Subject": "TestInvoke"
}
}
]
The code in lambda handler from the blueprint is as follows
import boto3
import json
import logging
import os
from base64 import b64decode
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
HOOK_URL = os.environ['kmsEncryptedHookUrl']
SLACK_CHANNEL = os.environ['slackChannel']
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("Event: " + str(event))
message = event['Records'][0]['Sns']['Message']
logger.info("Message: " + str(message))
alarm_name = message['AlarmName']
new_state = message['NewStateValue']
reason = message['NewStateReason']
slack_message = {
'channel': SLACK_CHANNEL,
'text': "%s state is now %s: %s" % (alarm_name, new_state, reason)
}
req = Request(HOOK_URL, json.dumps(slack_message).encode('utf-8'))
try:
response = urlopen(req)
response.read()
logger.info("Message posted to %s", slack_message['channel'])
except HTTPError as e:
logger.error("Request failed: %d %s", e.code, e.reason)
except URLError as e:
logger.error("Server connection failed: %s", e.reason)
When I run the test event, the lambda runs successfully.
I wanted to publish a message in SNS topic from the console to see if the lambda is triggered correctly. But when I try to publish the JSON object as a message body, I am getting the error
[ERROR] TypeError: string indices must be integersTraceback (most recent call last):  File "/var/task/lambda_function.py", line 21, in lambda_handler    alarm_name = message['AlarmName']
I tried giving plain json
{
"AlarmName": "PublishedAlarm",
"NewStateValue": "OK",
"NewStateReason": "This alarm is published"
}
I tried giving a stringified JSON
"{\"AlarmName\": \"PublishedAlarm\",\"NewStateValue\": \"OK\",\"NewStateReason\": \"This alarm is published\"}"
I tried choosing Custom payload for each delivery message structure and then gave the following message body
{
"default": "Sample fallback message",
"email": "Sample message for email endpoints",
"sqs": "Sample message for Amazon SQS endpoints",
"lambda": "{\"AlarmName\": \"PublishedAlarm\",\"NewStateValue\": \"OK\",\"NewStateReason\": \"This alarm is published\"}",
"http": "Sample message for HTTP endpoints",
"https": "Sample message for HTTPS endpoints",
"sms": "Sample message for SMS endpoints",
"firehose": "Sample message for Amazon Kinesis Data Firehose endpoints",
"APNS": "{\"aps\":{\"alert\": \"Sample message for iOS endpoints\"} }",
"APNS_SANDBOX": "{\"aps\":{\"alert\":\"Sample message for iOS development endpoints\"}}",
"APNS_VOIP": "{\"aps\":{\"alert\":\"Sample message for Apple VoIP endpoints\"}}",
"APNS_VOIP_SANDBOX": "{\"aps\":{\"alert\": \"Sample message for Apple VoIP development endpoints\"} }",
"MACOS": "{\"aps\":{\"alert\":\"Sample message for MacOS endpoints\"}}",
"MACOS_SANDBOX": "{\"aps\":{\"alert\": \"Sample message for MacOS development endpoints\"} }",
"GCM": "{ \"data\": { \"message\": \"Sample message for Android endpoints\" } }",
"ADM": "{ \"data\": { \"message\": \"Sample message for FireOS endpoints\" } }",
"BAIDU": "{\"title\":\"Sample message title\",\"description\":\"Sample message for Baidu endpoints\"}",
"MPNS": "<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification xmlns:wp=\"WPNotification\"><wp:Tile><wp:Count>ENTER COUNT</wp:Count><wp:Title>Sample message for Windows Phone 7+ endpoints</wp:Title></wp:Tile></wp:Notification>",
"WNS": "<badge version=\"1\" value=\"42\"/>"
}
Nothing worked. I've also subscribed an email address to the topic and I'm getting emails without any issues.
How can I simulate the test event given in lambda event templates from the SNS?
When you send your plain json message using SNS, it will be delivered to lambda in in the format:
'Message': '{\n "AlarmName": "PublishedAlarm",\n "NewStateValue": "OK",\n "NewStateReason": "This alarm is published"\n}'
You can parse it using ast' literal_eval method:
import ast
#...
#...
def lambda_handler(event, context):
logger.info("Event: " + str(event))
message = event['Records'][0]['Sns']['Message']
logger.info("Message: " + str(message))
message = ast.literal_eval(event['Records'][0]['Sns']['Message'])
alarm_name = message['AlarmName']
new_state = message['NewStateValue']
reason = message['NewStateReason']
#...
#...

i got empty value when print json key in lua code

this is the json response plus "\x00" in the end from server :
{
"STATUS": [{
"STATUS":"S",
"When":1470180059,
"Code":11,
"Msg":"Summary",
"Description":"nsgminer 0.9.2"
}],"SUMMARY": [{
"Elapsed":2061,
"MHS av":0.00,
"Found Blocks":0,
"Getworks":76,
"Accepted":0,
"Rejected":0,
"Hardware Errors":0,
"Utility":0.00,
"Discarded":209,
"Stale":0,
"Get Failures":3,
"Local Work":293,
"Remote Failures":0,
"Network Blocks":14,
"Total MH":0.0000,
"Work Utility":0.00,
"Difficulty Accepted":0.00000000,
"Difficulty Rejected":0.00000000,
"Difficulty Stale":0.00000000,
"Best Share":0
}],
"id":1
}\x00
i want to use the json in lua code :
local output = stdnse.output_table()
local json_string = tostring(result:sub(1, -2))
local pos, value = json.parse(json_string)
output["Description"] = value["STATUS"][0]["Description"]
return output
when i print it out, i got null value
i solve that with covert json to string and convert string into json table
local pos, value = json.parse(tostring(json_string))
output["Description"] = value["STATUS"][1]["Description"]

How to schedule a downtime in icinga2 by using icinga-api with groovy?

I'm searching for a way to schedule a downtime in icinga2 with a groovy script.
I already tried creating a small groovy script. Tried using the examples from icinga documentation:
curl -u root:icinga -k -s 'https://localhost:5665/v1/actions/schedule-downtime?type=Host&filter=host.vars.os==%22Linux%22' -d '{ "author" : "michi", "comment": "Maintenance.", "start_time": 1441136260, "end_time": 1441137260, "duration": 1000 }' -X POST | python -m json.tool
but adapting this to my script didn't work. Very important are the " around each attribute name, I noted.
Solution was this way:
Using wslite as webservice client. This is the minimal example.
Now I connect to my server with api enabled. The certificate is self signed, why "sslTrustAllCerts" was needed.
I select all services from my host "testserver" and set the downtime (duration in seconds).
#Grab('com.github.groovy-wslite:groovy-wslite:1.1.2')
import wslite.rest.*
import wslite.http.auth.*
def client = new RESTClient("https://myicinga2server:5665/")
client.authorization = new HTTPBasicAuthorization("root", "secret")
def timeFrom = System.currentTimeMillis() / 1000L
def timeDurationSec = 600
def timeTo = timeFrom + timeDurationSec
try
{
def response = client.post(
path: '/v1/actions/schedule-downtime?type=Service&filter=host.name==%22testserver%22',
headers: ["Accept": "application/json"],
sslTrustAllCerts: true)
{
json "author":"mstein", "comment":"Test-Downtime", "start_time": timeFrom, "end_time": timeTo, "duration": timeDurationSec, "fixed": true
}
assert 200 == response.statusCode
print response.text
}
catch (Exception exc)
{
println "Error: " + exc.getClass().toString()
println "Message: " + exc.getMessage()
println "Response: " + exc.getResponse()
System.exit(1)
}
That worked for me!

Error : Exception calling "MoveTo" with "1" argument(s): "The server is unwilling to process the request. "

I am trying to write a script to move OU of users in AD 2008
$Alias = "hareeshvm"
# Finding the location of the user account harveesm:
$Root = [ADSI]("LDAP://DC=corp,DC=bharatpetroleum,DC=com")
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectClass=user)(mailNickName= $Alias))"
$User = $searcher.findone()
# Binding the user account to $AUser and the OU to move to to $MovetoOU
$ADSPath = $User.Properties.adspath
$MoveToOU = [ADSI]("LDAP://OU=Temp,DC=corp,DC=bharatpetroleum,DC=com")
$AUser = [ADSI]("$ADSPath")
# Command to Do the actual move
$AUser.PSBase.moveto($MoveToOU)
And I am getting below mentioned error
Exception calling "MoveTo" with "1" argument(s): "The server is unwilling to process the request.
"
At D:\Ashish\MS Exchange\New User\newuserscreation.ps1:39 char:21
+ $AUser.PSBase.moveto <<<< ($MoveToOU)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
thx in advance