3

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
    )
1
  • In case to use aa environment variable you need to assign it which is outside the userdata block can you have it inside the userdata block? Commented Mar 8, 2021 at 9:53

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.