2
votes

I've specified an EC2 instance in my CloudFormation template, and I want to tag it with it's own InstanceId, like so:

"Resources": {
    "myInstance": {
        ...
        "Tags": [
            { "Key": "instance.id", "Value": { "Ref": "myInstance" } },
            ...
        ]
    }
}

But trying to create a stack from this template generates a AmazonCloudFormationException: "Circular dependency between resources: [myInstance]"

Running instances and tagging them using the EC2 API is very straightforward:

//this is C#, but that's not significant

var instance = ec2Client.RunInstances(...) ...;
var id = instance.InstanceId;
ec2Client.CreateTags(new CreateTagRequest
{
    Resources = { id },
    Tags = { new Tag { Key = "instance.id", Value = id } }
});

This approach arises naturally from the fact that instance tags cannot be created as part of the RunInstances operation, so all tags, not just the self-identifier, must be applied in a subsequent API operation.

So... can I accomplish the same thing using CloudFormation? Thanks very much!

(cross-posted to the AWS Forums)

2
What is the purpose of this tag?bsvingen

2 Answers

3
votes

I don't think you can. CloudFormation only lets you tag a resource at creation time, and the value of the tag you want doesn't exist until the resource is created.

But I don't think this has to be a problem. The two use cases I can think of for tags are looking at an instance and seeing the tag values, or finding instances with certain tag values. You can see or find by instance-id without having a tag containing it.

3
votes

You can always create a startup script which will update the tag of the instance after the startup. You can use the following (AWS CLI):

aws ec2 create-tags --resources `wget -q -O - http://169.254.169.254/latest/meta-data/instance-id` --tags Key=id,Value=`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`

However, if you only want to use the instance id inside your application, you can use wget -q -O - http://169.254.169.254/latest/meta-data/instance-id to fetch the instance id.