用于创建专色实例的Terraform服务角色

时间:2018-01-29 04:09:01

标签: amazon-web-services amazon-iam terraform

我是terraform的新手,我正在尝试创建一个服务角色来创建一个现场实例,请让我知道我应该用于点实例的服务名称是什么?服务:" ec2.amazonaws.com"有助于创建现场实例?

我还注意到在aws控制台中,我们可以选择为ec2 spot实例选择一个用例。 terraform是否也可以选择用例?

Terraform版本:Terraform v0.11.0

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

1 个答案:

答案 0 :(得分:0)

您所拥有的是为EC2实例创建实例配置文件以承担IAM角色的步骤的一部分(下面的步骤3)。

  1. 为角色创建IAM策略。
  2. 创建IAM角色并附加策略。
  3. 授予EC2实例承担角色的权限。
  4. resource "aws_iam_role_policy" "test_policy" {
    
     name = "test_policy"
    
     role = "${aws_iam_role.test_role.id}"
      policy = <<EOF
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Action": [
            "ec2:Describe*"
          ],
          "Effect": "Allow",
          "Resource": "*"
        }
      ]
    }
    EOF
    }
    
    resource "aws_iam_role" "test_role" {
      name = "test_role"
    
      assume_role_policy = <<EOF
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Action": "sts:AssumeRole",
          "Principal": {
            "Service": "ec2.amazonaws.com"
          },
          "Effect": "Allow",
          "Sid": ""
        }
      ]
    }
    EOF
    }
    
    resource "aws_spot_fleet_request" "cheap_compute" {
      iam_fleet_role      = "arn:aws:iam::12345678:role/spot-fleet"
      spot_price          = "0.03"
      allocation_strategy = "diversified"
      target_capacity     = 6
      valid_until         = "2019-11-04T20:44:20Z"
    
      launch_specification {
        instance_type     = "m4.10xlarge"
        ami               = "ami-1234"
        spot_price        = "2.793"
        placement_tenancy = "dedicated"
      }
    
      launch_specification {
        instance_type     = "m4.4xlarge"
        iam_instance_profile = "${aws_iam_role.test_role.name}"
        ami               = "ami-5678"
        key_name          = "my-key"
        spot_price        = "1.117"
        availability_zone = "us-west-1a"
        subnet_id         = "subnet-1234"
        weighted_capacity = 35
    
        root_block_device {
          volume_size = "300"
          volume_type = "gp2"
        }
    
        tags {
          Name = "spot-fleet-example"
        }
      }
    }
    

    https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html

    https://www.terraform.io/docs/providers/aws/r/instance.html#iam_instance_profile

    https://www.terraform.io/docs/providers/aws/r/iam_role_policy.html

    https://www.terraform.io/docs/providers/aws/r/spot_fleet_request.html