当前位置: 首页 > 知识库问答 >
问题:

Terraform/lambda/IAM根据标签停止ec2

相洛华
2023-03-14

这是任何人试图测试它的资源https://cloudywithachanceofbigdata.com/really-simple-terraform-infrastructure-automation-using-aws-lambda/.

我的tf脚本创建:

  • Lambda功能的IAM角色和相关策略
  • Lambda函数
  • Cloudwatch事件规则和触发器

我的地形版本:

Terraform v0.13.4

我的主菜。tf如下:

#
# Module Provider
#

provider "aws" {
    region = "us-west-1"
    shared_credentials_file = "~/.aws/credentials"
    profile                 = "default"
}

#
# Create IAM Role and Policy for Lambda Function
#

resource "aws_iam_role" "lambda_stop_ec2" {
  name = "lambda_stop_ec2"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "lambda.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy" "lamdba_ec2_shutdown_policy" {
  name = "lamdba_ec2_shutdown_policy"
  role = "${aws_iam_role.lambda_stop_ec2.id}"
  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ec2:Stop*",
        "ec2:DescribeInstances"
      ],
      "Resource": "*"
    }
  ]
}
EOF
}

#
# Create ZIP Archive for Function Source Code
#

data "archive_file" "lambda_stop_ec2_zip" {
  type = "zip"
  output_path = "/home/test/scheduler/repo/simple-lambda-ec2-scheduler/lambda_stop_ec2_zip"
  source_dir = "/home/test/scheduler/repo/simple-lambda-ec2-scheduler/function_source_code/"
}

#
# Create Lambda Function
#
 
resource "aws_lambda_function" "lambda_stop_ec2" {
  filename = "lambda_stop_ec2_zip"
  function_name    = "lambda_stop_ec2"
  timeout          = 10  
  role             = "${aws_iam_role.lambda_stop_ec2.arn}"
  handler          = "lambda_stop_ec2.lambda_handler"
  runtime          = "python3.8"
}

#
# Create CloudWatch Event Rule
#

resource "aws_cloudwatch_event_rule" "stop_ec2_event_rule" {
  name        = "stop-ec2-event-rule"
  description = "Stop running EC2 instance at a specified time each day"
  schedule_expression = "${var.schedule_expression}"
}

#
# Create CloudWatch Event Target
#

resource "aws_cloudwatch_event_target" "stop_ec2_event_rule_target" {
  rule      = "${aws_cloudwatch_event_rule.stop_ec2_event_rule.name}"
  target_id = "TriggerLambdaFunction"
  arn       = "${aws_lambda_function.lambda_stop_ec2.arn}"
  input     = "{\"name\":\"${var.name}\"}"
}

#
# Add Lamdba Permission
#

resource "aws_lambda_permission" "allow_cloudwatch" {
  statement_id  = "AllowExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = "${aws_lambda_function.lambda_stop_ec2.function_name}"
  principal     = "events.amazonaws.com"
  source_arn    = "${aws_cloudwatch_event_rule.stop_ec2_event_rule.arn}"
}

我的地形。TFVAR:

schedule_expression = "cron(0 17 * * ? *)"
name = "instanceScheduler"

我的变量。tf:

variable "schedule_expression" {}
variable "name" {}

我的函数\u源代码/lambda\u停止\u ec2。派克

import boto3
region = 'us-west-1'

def lambda_handler(event, context):
    name = event["name"]
    print("stopping all instances in the %s name" % (name))
    ec2 = boto3.client('ec2', region_name=region)
    response = ec2.describe_instances(
        Filters=[
            {
                'Name': 'tag:Name',
                'Values': [name]
            }
        ]
    )
    for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
            print("instance [%s] is in [%s] state" % (instance["InstanceId"], instance["State"]["Name"]))
            if instance["State"]["Name"] == "running":
                print("stopping instance [%s]" % (instance["InstanceId"]))
                ec2.stop_instances(InstanceIds=[instance["InstanceId"]])
                print("instance [%s] stopped" % (instance["InstanceId"]))

我的运行命令:

terraform init
terraform apply

我得到的是:

Plan: 6 to add, 0 to change, 0 to destroy.


Warning: Interpolation-only expressions are deprecated

  on main.tf line 38, in resource "aws_iam_role_policy" "lamdba_ec2_shutdown_policy":
  38:   role = "${aws_iam_role.lambda_stop_ec2.id}"

Terraform 0.11 and earlier required all non-constant expressions to be
provided via interpolation syntax, but this pattern is now deprecated. To
silence this warning, remove the "${ sequence from the start and the }"
sequence from the end of this expression, leaving just the inner expression.

Template interpolation syntax is still used to construct strings from
expressions when the template includes multiple interpolation sequences or a
mixture of literal strings and interpolations. This deprecation applies only
to templates that consist entirely of a single interpolation sequence.

(and 6 more similar warnings elsewhere)

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_cloudwatch_event_rule.stop_ec2_event_rule: Creating...
aws_iam_role.lambda_stop_ec2: Creating...
aws_iam_role.lambda_stop_ec2: Creation complete after 1s [id=lambda_stop_ec2]
aws_iam_role_policy.lamdba_ec2_shutdown_policy: Creating...
aws_lambda_function.lambda_stop_ec2: Creating...
aws_cloudwatch_event_rule.stop_ec2_event_rule: Creation complete after 2s [id=stop-ec2-event-rule]
aws_lambda_function.lambda_stop_ec2: Still creating... [10s elapsed]
aws_lambda_function.lambda_stop_ec2: Creation complete after 16s [id=lambda_stop_ec2]
aws_lambda_permission.allow_cloudwatch: Creating...
aws_cloudwatch_event_target.stop_ec2_event_rule_target: Creating...
aws_lambda_permission.allow_cloudwatch: Creation complete after 1s [id=AllowExecutionFromCloudWatch]
aws_cloudwatch_event_target.stop_ec2_event_rule_target: Creation complete after 1s [id=stop-ec2-event-rule-TriggerLambdaFunction]

Error: Error putting IAM role policy lamdba_ec2_shutdown_policy: MalformedPolicyDocument: Partition "aws" is not valid for resource "arn:aws:logs:*:*:*".
        status code: 400, request id: b2e4b11e-da82-4b1d-b482-8cc2a3afd242

请帮忙!!

共有1个答案

空翼
2023-03-14

在https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-identity-based-access-control-cwl.html所示的策略示例中

资源是“arn:aws:logs:**”

请参见3个星号。你的只有一个。我已经在IAM策略模拟器上测试了您的策略(https://policysim.aws.amazon.com/)由于缺少星号,它是无效的

完整的政策示例:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "logs:DescribeLogStreams"
    ],
      "Resource": [
        "arn:aws:logs:*:*:*"
    ]
  }
 ]
}
 类似资料:
  • AWS Identity and Access Management (IAM) Terraform module Features Cross-account access. Define IAM roles using iam_assumable_role or iam_assumable_roles submodules in "resource AWS accounts (prod, st

  • iam-policy-json-to-terraform Small tool to convert an IAM Policy in JSON format into a Terraform aws_iam_policy_document Web Version Check out a web version of the tool here. For command line usage an

  • AWS Lambda Terraform module Terraform module, which creates almost all supported AWS Lambda resources as well as taking care of building and packaging of required Lambda dependencies for functions and

  • 实际上,我正在开发一个应用程序,它需要处理一个NFC标签,使用户能够使用这个应用程序。 这个活动是在应用程序启动和简历时调用的。 编辑:我注意到这是因为,即使屏幕没有变黑,cpu或NFC阅读器进入睡眠模式,我也必须锁定和解锁手机,使它再次工作,我现在正在寻找一种方法,使cpu一直运行,我已经尝试过: 仅适用于Galaxy Xcover 3(Android 6.0.1) 我仍然无法使它在Galaxy

  • AWS Lambda the Terraform Way The objective of this tutorial is to understand AWS Lambda in-depth, beyond executing functions, using Terraform.This tutorial walks through setting up Terraform, dependen

  • 问题内容: 我想使用AJAX来确定表单的值对我来说是否可以接受(这不是表单验证)。AJAX 将确定是否提交表单。 下面,你会看到,当表单提交并根据返回什么我执行一个AJAX调用(无论是空白这是可以接受的,或者这是不能接受的错误信息),我想还是在。 我怀疑我的麻烦在于AJAX的。请帮助我摆脱AJAX呼叫,以便我可以执行类似的操作。 加工: 原版的: 问题答案: 由于ajax调用是异步的,因此必须阻止