I’m trying to create an Event bridge target using terraform script. This Event Bridge target creation is part of creating Event Bridge Rule which runs on every 20 minutes schedule and triggers an SSM Document which in turn runs an existing python script in an existing EC2 instance. Below is the Terraform script I’m using, below the script I’m also pasting the error which I’m getting while doing Terraform Apply.
Request to all Terraform and AWS experts to help me here.
`provider “aws” {
region = “us-east-1”
}
Attach IAM Policy to the Role for Systems Manager Run Command
resource “aws_iam_role_policy_attachment” “ssm_run_command_attachment” {
# role = aws_iam_role.ssm_run_command_role.name
role = “Amazon_EventBridge_Invoke_Run_Command_87839596”
policy_arn = “arn:aws:iam::123-sample:policy/service-role/Amazon_EventBridge_Invoke_Run_Command_123456”
}
Create an SSM document
resource “aws_ssm_document” “batch_job_script_2” {
name = “batch-job-script-2”
document_type = “Command”
content = <<EOF
{
“schemaVersion”: “2.2”,
“description”: “Batch job SSM Document to run shell script”,
“parameters”: {
“commands”: {
“type”: “StringList”,
“description”: “(Required) The list of commands to execute.”,
“default”: [
“echo Hello World”
]
}
},
“mainSteps”: [
{
“action”: “aws:runShellScript”,
“name”: “runShellScript”,
“inputs”: {
“runCommand”: [
“python3 ./scheduler_script.py”
]
}
}
]
}
EOF
}
Create an EventBridge rule
resource “aws_cloudwatch_event_rule” “hw_eb_rule” {
name = “hello-world-eventbridge-rule”
description = “Rule to trigger shell script every 20 minutes”
schedule_expression = "rate(20 minutes)"
}
Create a target for the EventBridge rule to run the SSM document on the EC2 instance
resource “aws_cloudwatch_event_target” “batch_job_2_target” {
rule = aws_cloudwatch_event_rule.hw_eb_rule.name
arn = aws_ssm_document.batch_job_script_2.arn
role_arn = “arn:aws:iam::1234567898:role/service-role/Amazon_EventBridge_Invoke_Run_Command_123456”
target_id = “batch-job-script-2”
input = jsonencode({
"InstanceIds": ["id-12345"]
"Parameters": {
"commands": ["/usr/bin/python3 ./scheduler_script.py"]
}
})
}`
Error: creating EventBridge Target (hello-world-eventbridge-rule-batch-job-script-2): ValidationException: Parameter RunCommandParameters is not valid for target batch-job-script-2.
│ status code: 400, request id: f147023c-3bd9-4bc1-b1f2-ad8e9ab31a32
│
│ with aws_cloudwatch_event_target.batch_job_2_target,
│ on main.tf line 53, in resource “aws_cloudwatch_event_target” “batch_job_2_target”:
│ 53: resource “aws_cloudwatch_event_target” “batch_job_2_target” {
I have tried creating the Event Bridge target manually and that is working fine absolutely and the script in the ec2 instance is being called in the specified interval.
However when trying to create with Terraform script I’m unable to create that target part only. Rest all the resources like IAM Role, policy attachment, SSM document, Event Bridge Rule are also able to create through the given terraform script.