Get the arguments registered in CloudWatch with Java running on Lambda.
The Lambda function that starts and stops EC2 created in the previous article, CloudWatchEvents' Cron was designed to start at multiple times, such as 8:00, 9:00, 17:00, and 18:00. But I forgot which instance I tried to launch at what time, I had to check the arguments registered in CloudWatch Events one by one. It was a hassle, so I created a function to get the arguments. (If you take a memo, you have to synchronize the registered argument with the memo, so I wanted to avoid it.)
・ Eclipse Preparation ・ Registration execution (someday) -Implementation-Stop / Start EC2 -Implementation-Check CloudWatch arguments -Implementation Tips --Get Instance Name from Reagion and Instance ID
[Same as last time](https://qiita.com/t_ookubo/items/3b12bd985a65a73b4c59#%E3%81%A8%E3%82%8A%E3%81%82%E3%81%88%E3%81%9A % E3% 82% AF% E3% 83% A9% E3% 82% B9% E4% BD% 9C% E6% 88% 90)
//Create a CloudWatchEvents object
AmazonCloudWatchEvents event = AmazonCloudWatchEventsClientBuilder.defaultClient();
ListRulesResult retRule = event.listRules(new ListRulesRequest());
for(Rule rule : retRule.getRules()) {
// rule.getName()、rule.getDescription()
}
This part of the console As the method name suggests, you can get the name and description of the rule.
// get target information from rule
ListTargetsByRuleRequest req = new ListTargetsByRuleRequest().withRule(rule.getName());
ListTargetsByRuleResult retTarget = event.listTargetsByRule(req);
List<Target> cloudWatchTargets = retTarget.getTargets();
for (Target target : cloudWatchTargets) {
// do loop each cloud watch rule's target
}
This part of the console
target.getArn()
Now each target will be returned in the form below arn:aws:lambda:region:xxxxxx:function:functionName
So narrow down with endWith
if (target.getArn().endsWith("Function name you want to narrow down")) {
//
}
This part of the console (in the case of this console screen, there is only one in the first place, so it doesn't matter whether you do it or not.)
target.getInput()
This part of the console
//Since the Input of cloudWatch is described in json, convert from json to bean
SomethingBean cloudWatchInput = Jackson.fromJsonString(target.getInput(), SomethingBean.class);
After that, format the rule name, description, arguments, etc. of CloudWatchEvents that you have acquired so far into the form you want to output, and return it to output to finish.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-cloudwatch</artifactId>
<version>1.11.99</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-events</artifactId>
<version>1.11.719</version>
<scope>compile</scope>
</dependency>
Recommended Posts