Unable to add tags when launching EC2 instance via AWS SDK for PHP (no CLI)

454 Views Asked by At

I am able to successfully launch new instances using AWS SDK for PHP. However, I am not able to add tags ('Name' = 'New Instance'). I tried doing it in several ways, with the following seeming the most reasonable. However, upon refreshing the EC2 dashboard, I can see that the new instance is created, however, the name tag is still blank.

        $ec2Client = new Ec2Client([
            'region' => 'xx-xxxx-1',
            'version' => 'latest',
            'profile' => 'default'
        ]);
        // Launch an instance with the key pair and security group
        $result = $ec2Client->runInstances(array(
            'ImageId'           => 'ami-xxxxxxxx',
            'MinCount'          => 1,
            'MaxCount'          => 1,
            'InstanceType'      => 't2.large',
            'KeyName'           => 'xxxxxx',
            'SubnetId'          => 'subnet-xxxxxxxx',
            'VpcId'             => 'vpc-xxxxxxxx',
            'Tags'              => array(
                                        'Key' => 'Name',
                                        'Value' => 'New Instance',
                                    ),
            'SecurityGroups'[1] => 'sg-xxxxxxxx',
        ));
2

There are 2 best solutions below

1
Justinas On

I don't know what version of SDK you are using, but from AWS v2 SDK documentation there is no Tags key.

Try using other function createTags. Note that Tags is double array, not like in your example.

$ec2Client->createTags([
    'Resources' => [$result['Instances'][0]['InstanceId']],
    'Tags' => [
        ['Key' => '', 'Value' => ''],
        ['Key' => '', 'Value' => ''],
    ]
]);
0
Sydrik On

Thank you @Justinas for pointing out using version 2. I am however using the version 3 SDK and had found the answer in https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#runinstances.

Tested and working, the Tag can be done under TagSpecifications under the RunInstances operation as follow:

'TagSpecifications' => [
    [
        'ResourceType' => 'instance',
        'Tags' => [
            [
                'Key' => 'Name',
                'Value' => 'New Instance Name',
            ],
        ],
    ],
],

More information about TagSpecifications array structure can be found here: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#shape-tagspecification, and for Tag structure over here: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-ec2-2016-11-15.html#shape-tag