Getting IAM username in terraform

We have many IAM users creating a self-service infrastructure on EC2 using Terraform. Users do not necessarily set a key for their instances, so it’s difficult to bind an instance to a specific user. I understand that we could dig through CloudTrail to find out which users create the instances, but it seems that it would be easier to mark the instances with the current IAM username.

The problem is that Terraform does not show this: I can use aws_caller_identityor aws_canonical_user_id, but both of them return an organizational account, not a specific IAM username. Is there a data source in Terraform that will return the IAM user creating the instances?

+4
source share
2 answers

It seems that it does not actually invoke the STS GetCallerId endpoint, which can provide the necessary information, in particular, the UserId and Arn of the user executing the command. aws_caller_identity

Instead, it accepts a simpler option and simply uses the accountidrecord that the AWS client has already defined and simply returns it.

, . , aws_caller_identity aws_caller_identity STS GetCallerId, .

, Terraform , Terraform, , - -, , , UserId Arn.

, , , - , EC2:

resource "aws_instance" "instance" {
    ami = "ami-123456"
    instance_type = "t2.micro"
    tags {
        Name = "HelloWorld"
    }
    lifecycle {
        ignore_changes = [ "tags.Owner" ]
    }
    provisioner "local-exec" {
        command = <<EOF
owner='aws sts get-caller-identity --output text --query 'Arn' | cut -d"/" -f2'
aws ec2 create-tags --resources ${self.id} --tags Key=Owner,Value=$${owner}
EOF
    }
}

Terraform EC2 , "". , / IAM , "" , .

+2

( ), :

resource "aws_instance" "instance" {
    count           = "${var.instance_number}"
    ami             = "ami-xxxxxx"
    instance_type   = "${var.instance_type}"
    security_groups = "${concat(list("sg-xxxxxx"),var.security_groups)}"
    disable_api_termination = "${var.termination_protection}"
    subnet_id       = "${var.subnet_id}"
    iam_instance_profile = "test_role"
    tags {
            Name        = "prod-${var.cluster_name}-${var.service_name}-${count.index+1}"
            Environment = "prod"
            Product     = "${var.cluster_name}"
    }
    lifecycle {
        ignore_changes = [ "tags.LaunchedBy" ]
    }
    provisioner "local-exec" {
        command = <<EOF
launched_by='aws iam get-user --profile prod | python -mjson.tool | grep UserName | awk '{print $2;exit; }''
aws ec2 create-tags --resources ${self.id} --tags Key=LaunchedBy,Value=$${launched_by}
EOF
    }
}
0

Source: https://habr.com/ru/post/1670136/


All Articles