Naeem
Naeem

Reputation: 227

Pass variable in user data using boto3 while creating EC2 Instance

I am creating EC2 instance and want to pass user data to attach a filesystem, but I don't know how to pass file system ID as a variable.

The file system ID will be passed using the API gateway. I have tried following but user data contains $aa not aa values.

aa='fs-ce99bd38'
user_data = """#!bin/bash
sudo yum -y install nfs-utils
sudo mount -t efs -o tls $aa:/ efs
"""

client = boto3.client('ec2', region_name=REGION)

def lambda_handler(event, context):

    instance = client.run_instances(
        ImageId=AMI,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        UserData=user_data,
        MaxCount=min_max_add,
        MinCount=min_max_add
    )

Upvotes: 3

Views: 1841

Answers (1)

Maurice
Maurice

Reputation: 13197

That's now how you insert a variable into a string :-)

If you have a reasonably modern Python version you can use f-strings like this:

aa='fs-ce99bd38'
user_data = f"""#!bin/bash
sudo yum -y install nfs-utils
sudo mount -t efs -o tls {aa}:/ efs
"""

Otherwise good old format will do the trick as well:

aa='fs-ce99bd38'
user_data = """#!bin/bash
sudo yum -y install nfs-utils
sudo mount -t efs -o tls {}:/ efs
""".format(aa)

Or the even older % operator

aa='fs-ce99bd38'
user_data = """#!bin/bash
sudo yum -y install nfs-utils
sudo mount -t efs -o tls %s:/ efs
""" % aa

Upvotes: 6

Related Questions