Node AWS SDK: Launch and Tag Instances
Let's take a look at a more interesting example. We would actually provision some resources. We would create some infrastructure. Here's an example where I'm using, I'm loading the credentials from a config file. The command would be AWS.config.loadFromPath, and I provide the path to my config.json. I'm using dot slash to signify that this file, it's in the same folder that my Node.js script is, which is provision-infra.js.
We continue with the same file, provision-infra.js. We create a new EC2 instance by providing the API version. In this case I'm not specifying the region because I specified it in my config file. This will allow you to have more flexibility by sweeping and by swapping and changing the config files. We can provision exactly the same infrastructure, which will describe in this file in multiple regions, and maybe using different users as well, maybe in different accounts as well. You can see exactly the same parameters that you would use with AWS CLI, such as the account number, only here, it's used as a range minimum and maximum, image ID, exactly the same. Just pay attention to the names. Here we are using first letter is capital. There is no dashes, and everything else after the first is camelCase, so it's capitalized as well, so it's "UserData".
Here's the trick. Here's the quick function for you. It's synchronous, and I'm reading from user-data.sh, and right there in the readFileSync, I can provide the encoding, which is base64. So it's very convenient thanks to this built-in module fs that Node platform provides. I don't need to convert, I don't need to do anything extra to convert to base64, just when I'm reading the file I can specify base64, and I'll get exactly what I need. So here I cannot just say "file://", like I did with AWS CLI here. It's lower level implementation, so I have to do a little bit extra. I need to actually convert it manually, but again, thanks to the Node.js module, it's just one-liner. And why I'm using synchronous? Well, actually, this script is not meant to be used by many clients. It's not a web server. It's gonna be just used by me, by a single client, and I don't really care if this code readFileSync, would be blocking something else, I just want to execute and read that file and it's okay if it's in a sequential order in a synchronous manner.
And then I want to create tags, so I'm executing "EC2.createTags". At the very last statement inside of my callback. Why it's inside? Well, actually, I cannot execute it outside because my instance would not be created. I need to grab that instance ID, which I will be using in the params for the create tags. That's why create tags, it's going into the callback of run instances.