Search code examples
amazon-web-servicesamazon-ec2amazon-cloudfront

Can I access cfn input parameter variable in Userdata script?


Here is what I want to do. My cfn template will be used to spin up different types of EC2 instances: micro, large, etc.

But based on the number of cores on that instance type, I want to do certain things differently in the userdata script section.

I am open to either:

  1. finding out the number of cores programmatically inside the template or
  2. passing the number of cores as an input parameter to the template.

Having said that, here are my 2 questions:

  1. Is it possible to query the system from the template to get the core count? If yes, can someone show me how?

  2. But more importantly, is it possible to use this value in the userdata section of the template?

PS: I have asked the same question on AWS forums also.


Solution

  • I don't know of any way to discover this programmatically [but see below], but you can certainly insert the value of a parameter into the userdata section. Here's an example:

    UserData: {
      "Fn::Base64": {
        "Fn::Join: [
          "",
          [
            "all of the script up to the missing value",
            {"Ref": "NumberOfCoresParameterName"},
            "all of the script after the missing value"
          ]
        ]
      }
    }
    

    In the example, "NumberOfCoresParameterName is the name you give the parameter where you insert the value.

    The "Fn::Base64" function converts its value to a base 64 encoded string, required for UserData.

    "Fn::Join" takes two parameters: a string to insert between the ones you are joining (here it is an empty string), and an array of strings to join. The "Ref" object in the middle of the other strings gets replaced with the value of the parameter.

    Edited to add: I don't know how to get the number of cores, but you can get the AWS instance type with the command

    curl http://169.254.169.254/latest/meta-data/instance-type
    

    That will return a string like t1.micro, m1.large, etc. You can use the AWS documentation to determine how many cores that instance type has. However, I don't know any way you can use this result inside a template. You could write a shell script that did whatever you need in the UserData section.