Write a shell script file on bastion host create using CDK

Viewed 43

In AWS, to gain access to our RDS instance we setup a dedicated EC2 bastion host that we securely access by invoking the SSM Agent in the EC2 dashboard.

This is done by writing a shell script after connecting to the bastion host, now the script usually disappears after a certain time(?). So, is there any way to create this file using CDK when I create the bastion host?

I tried using CFN.init but to no avail.

this.bastionHost = new BastionHostLinux(this, "BastionHost", {
      vpc: inspireStack.vpc,
      subnetSelection: { subnetType: SubnetType.PRIVATE_WITH_NAT },
      instanceType: InstanceType.of(InstanceClass.T2, InstanceSize.MICRO),
      init: CloudFormationInit.fromConfigSets({
        configSets: {
          default: ["install"],
        },
        configs: {
          install: new InitConfig([
            InitCommand.shellCommand("cd ~"),
            InitFile.fromString("jomar.sh", "testing 123"),
            InitCommand.shellCommand("chmod +x jomar.sh"),
          ]),
        },
      })
2 Answers

You can write files to an EC2 instance with cloud-init. Either from an existing file or directly from the TS (a json for instance)

const ec2Instance = new ec2.Instance(this, 'Instance', {
      vpc,
      instanceType: ec2.InstanceType.of(
        ec2.InstanceClass.T4G,
        ec2.InstanceSize.MICRO,
      ),
      machineImage: new ec2.AmazonLinuxImage({
        generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
        cpuType: ec2.AmazonLinuxCpuType.ARM_64,
      }),
      init: ec2.CloudFormationInit.fromConfigSets({
        configSets: {
          default: ['install', 'config'],
        },
        configs: {
          install: new ec2.InitConfig([
            ec2.InitFile.fromObject('/etc/config.json', {
              IP: ec2Eip.ref,
            }),
            ec2.InitFile.fromFileInline(
              '/etc/install.sh',
              './src/asteriskConfig/install.sh',
            ),
            ec2.InitCommand.shellCommand('chmod +x /etc/install.sh'),
            ec2.InitCommand.shellCommand('cd /tmp'),
            ec2.InitCommand.shellCommand('/etc/install.sh'),
          ]),
          config: new ec2.InitConfig([
            ec2.InitFile.fromFileInline(
              '/etc/asterisk/pjsip.conf',
              './src/asteriskConfig/pjsip.conf',
            ),

https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.CloudFormationInit.html

I see there are three simple workarounds:

  • SSM start session contains 'profile' section, where you can add your script as a bash function.
  • You can create an SSM document that will create this file, so before starting the session you will only need to run this document to create a file...
  • Save this script on S3 and just download them

Regarding disappearing file - it's strange... This CDK construct is similar to Instance, try to use it instead, and create your script with user-data.

Related