0

I've created a cloudformation script that creates an ec2 instance, a few volumes upon other features. When the ec2 instance has been initialised I want it to run a bash script automatically to mount a volume created in the script (not the root volume) to /var/www/vhosts. But at the moment it creates the directory so I know its running the bash script but doesn't successfully execute the other commands. Here is my cloudformation script. When I run the 3 commands listed below separately when ssh to the ec2 instance they work fine and the volume has been mounted to the correct location.

    "Ec2Instance": {
  "Type": "AWS::EC2::Instance",
  "Properties": {
    "ImageId": {
      "Ref": "ImageIdentification"
    },
    "AvailabilityZone" : "eu-west-1a",
    "InstanceType": {
      "Ref": "InstanceType"
    },
    "SecurityGroupIds" : [
       {
         "Ref": "SecurityGroup"
       }
    ],
    "DisableApiTermination" : "true",
    "KeyName": {
      "Ref": "keyPairName"
    },
    "Tags" : [
      {"Key" : "Name", "Value" : { "Ref" : "EC2InstanceName"}}
    ],
    "UserData" : {"Fn::Base64" : {"Fn::Join" : ["", [
     "#!/bin/bash -v\n",
      "sudo mkdir -p /var/www/vhosts\n",
      "sudo mkfs -t ext4 /dev/xvdh\n",
      "sudo mount /dev/xvdh /var/www/vhosts\n"
    ]]}}
  }
},

Thanks for your help.

  • 2
    The service that runs the user-data script is called `cloud-init`. Check the cloud-init log on the server to see what the issue is: https://stackoverflow.com/questions/18691867/where-to-find-logs-for-a-cloud-init-user-data-script – Mark B Jul 06 '18 at 15:19
  • @MarkB Thanks for your help. That worked perfectly for troubleshooting. For anyone who's reading this I ran the command 'vim /var/log/cloud-init-output.log' to view the log. I also added a sleep command to the bash script and the volume property to the ec2 instance. – Adam Glynn Jul 09 '18 at 10:56

1 Answers1

0

To run the bash script in CloudFormation you need to specify the remote link in the user data section or write down the commands one by one in the user data.

Tags:
    - Key: Name
      Value: test
  UserData:
    Fn::Base64: !Sub |
      #!/bin/bash -xe
      cd /var/tmp
      wget https://raw.githubusercontent.com/installer/cloudformation/install.sh
      sudo bash /var/tmp/install.sh 4  '${CORE.PrivateIp}'
Rohan
  • 3
  • 4