Wednesday, 21 September 2016

Cloudinit to provision EC2 users

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
https://cloudinit.readthedocs.io/en/latest/
#cloud-config
hostname: <hostname>
repo_update: true
repo_upgrade: all
users:
  - name: <username2>
    sudo: ALL=(ALL) NOPASSWD:ALL  #Alows them to sudo
    shell: /bin/bash
    ssh-authorized-keys:
      - ssh-rsa <Key>
  - name: <username1>
    sudo: ALL=(ALL) NOPASSWD:ALL
    shell: /bin/bash
    ssh-authorized-keys:
      - ssh-rsa <Key>

# run commands
# default: none
# runcmd contains a list of either lists or a string
# each item will be executed in order at rc.local like level with
# output to the console
# - runcmd only runs during the first boot
# - if the item is a list, the items will be properly executed as if
#   passed to execve(3) (with the first arg as the command).
# - if the item is a string, it will be simply written to the file and
#   will be interpreted by 'sh'
#
# Note, that the list has to be proper yaml, so you have to quote
# any characters yaml would eat (':' can be problematic)
runcmd:
 - [ ls, -l, / ]
 - [ sh, -xc, "echo $(date) ': hello world!'" ]
 - [ sh, -c, echo "=========hello world'=========" ]
 - ls -l /root
 - [ wget, "http://slashdot.org", -O, /tmp/index.html ]
This will update the packages, provision the users with keys and run commands on boot. Once the instance is booted the users will be able to login using ssh.

Alternatively, just use bash:
#!/bin/bash

yum update -y
USER1=member1
USER2=member2

adduser $USER1 && mkdir /home/$USER1/.ssh && chmod 700 /home/$USER1/.ssh
echo "member1 public ssh key goes here)" > /home/$USER1/.ssh/authorized_keys
chmod 600 /home/$USER1/.ssh/authorized_keys
chown -R $USER1:$USER1 /home/$USER1/.ssh
echo "$USER1 ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

adduser $USER2 && mkdir /home/$USER2/.ssh && chmod 700 /home/$USER2/.ssh
echo "<member2 public ssh key goes here>" > /home/$USER2/.ssh/authorized_keys
chmod 600 /home/$USER2/.ssh/authorized_keys
chown -R $USER2:$USER2 /home/$USER2/.ssh

No comments:

Post a Comment