0
votes

I want to stop my EC2 instance everyday with CloudWatch Events. On console, it works without any problems. By reverse-engineering the configuration I have done with console, a series of commands which is equivalent to it seems to be the following:

aws events put-rule \
  --name stop-ec2-instance \
  --schedule-expression 'cron(0 13 * * ? *)' \
  --description "Stop EC2 instance everyday" \
  --role-arn arn:aws:iam::012345678901:role/AWS_Events_Actions_Execution

aws events put-targets \
  --rule stop-ec2-instance \
  --targets "[{ \
    \"Arn\": \"arn:aws:automation:ap-northeast-1:012345678901:action/EC2StopInstance/EC2StopInstance_stop-ec2-instance\", \
    \"Id\": \"EC2StopInstance_stop-ec2-instance\", \
    \"Input\": \"\\\"arn:aws:ec2:ap-northeast-1:012345678901:instance/i-01234567\\\"\" \
  }]"

.

However, this doesn't work because I get the following error at the first command:

A client error (ValidationException) occurred when calling the PutRule operation: Provided role 'arn:aws:iam::012345678901:role/AWS_Events_Actions_Execution' cannot be assumed by principal 'events.amazonaws.com'.

.

How can I put Amazon CloudWatch Events rule with CLI?

1
It should work without role.Lubo Sach
@LuboSach The execution fails if I remove --role-arn from the first command. In addition, if no role is needed to accomplish the task, what is the role "AWS permissions" requires in "Step 2: Configure rule details" on console?Akihiro HARAI
People on AWS Forum will be hopefully able to help - forums.aws.amazon.comLubo Sach

1 Answers

5
votes

The IAM Role you've created (i.e. arn:aws:iam::012345678901:role/AWS_Events_Actions_Execution) doesn't allow CloudWatch Events to assume it.

Go to the role in the IAM Console, and under the tab "Trust Relationships" make sure your Statement block includes events.amazonaws.com as an accepted Service that can assume the role (aka. sts:AssumeRole action). For example:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}