Skip to content

Instantly share code, notes, and snippets.

@realBjornRoden
Last active September 21, 2019 01:56
Show Gist options
  • Save realBjornRoden/2915399d2a8cd55eb374e92cbedf56f2 to your computer and use it in GitHub Desktop.
Save realBjornRoden/2915399d2a8cd55eb374e92cbedf56f2 to your computer and use it in GitHub Desktop.

AWS Create SOLO AMIv2 Linux Virtual Machine (VM)

Actions

  1. Open a command line session using Terminal/xterm/putty or equiv

  2. Ensure login key configuration is made with the aws configure for the user with sufficient Policy permissions
    NB. Below is performed with the group set to the policy AmazonEC2FullAccess and for the aws pricing the policy AWSPriceListServiceFullAccess

  3. Create SSH key pair with aws ec2 create-key-pair and store the secret key .pem file securely with need-to-know access only.

    $ aws ec2 create-key-pair --key-name ec2-vmadmin-key --region us-east-2 > ec2-vmadmin-key.pem
    $ chmod 400 ec2-vmadmin-key.pem
    
  4. Use the aws ec2 run-instances to create a VM; if not specified, the account default Security Group named default will apply aws-ec2-run-instance

    $ aws ec2 run-instances --region us-east-2 --image-id ami-00c03f7f7f2ec15c3 --instance-type t2.micro --key-name ec2-vmadmin-key --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=vm-solo-03}]' --output json > vm-solo-03.json
    

    Or without a name (in AWS the name is a tag and identification of a VM is through the InstanceId

    $ aws ec2 run-instances --region us-east-2 --image-id ami-0d8f6eb4f641ef691 --instance-type t2.micro --key-name ec2-vmadmin-key
    
  5. Use the aws ec2 describe-instances to display details of the VM cli-usage-output

    $ aws ec2 describe-instances --region us-east-2 --query 'Reservations[*].Instances[*].{"2.Instance":InstanceId,"5.AvailabilityZone":Placement.AvailabilityZone,"1.Name":Tags[?Key==`Name`]|[0].Value,"3.InstanceType":InstanceType,"7.PrivateIpAddress":PrivateIpAddress,"8.PublicIpAddress":PublicIpAddress,"6.State":State.Name,"9.Hypervisor":Hypervisor,"4.Processors":CpuOptions.CoreCount}' --output table
    ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    |                                                                           DescribeInstances                                                                          |
    +------------+----------------------+-----------------+---------------+---------------------+-------------+---------------------+---------------------+----------------+
    |   1.Name   |     2.Instance       | 3.InstanceType  | 4.Processors  | 5.AvailabilityZone  |   6.State   | 7.PrivateIpAddress  |  8.PublicIpAddress  | 9.Hypervisor   |
    +------------+----------------------+-----------------+---------------+---------------------+-------------+---------------------+---------------------+----------------+
    |  vm-solo-03|  i-0e5641b24d9618aa8 |  t2.micro       |  1            |  us-east-2b         |  running    |  172.31.26.155      |  3.16.167.39        |  xen           |
    +------------+----------------------+-----------------+---------------+---------------------+-------------+---------------------+---------------------+----------------+
    
  6. Use the aws ec2 describe-instances or the aws ec2 describe-network-interfaces to display IP-address of VMs

    $ aws ec2 describe-instances --region us-east-2 --query 'Reservations[*].Instances[*].[Tags[?Key==`Name`]|[0].Value,InstanceId,PrivateIpAddress,PublicIpAddress]' --output text
    vm-solo-03    i-0e5641b24d9618aa8    172.31.26.155    3.16.167.39    running
    
    $ aws ec2 describe-network-interfaces --region us-east-2 --query 'NetworkInterfaces[*].[Attachment.InstanceId,PrivateIpAddress,Association.PublicIp]' --output text
    i-0e5641b24d9618aa8    172.31.26.155    3.16.167.39
    
    $ alias lsvm="aws ec2 describe-instances --region us-east-2 --query 'Reservations[*].Instances[*].[Tags[?Key==\`Name\`]|[0].Value,InstanceId,PrivateIpAddress,PublicIpAddress,Placement.AvailabilityZone,State.Name]' --output text"
    
    $ lsvm
    vm-solo-03    i-0e5641b24d9618aa8    172.31.26.155    3.16.167.39    us-east-2b    running
    
    1. Use the aws ec2 aws ec2 describe-instance-status to display the status of a VM
    $ aws ec2 describe-instance-status --instance-id i-0e5641b24d9618aa8 --region us-east-2
    INSTANCESTATUSES    us-east-2c    i-0e5641b24d9618aa8
    INSTANCESTATE    16    running
    INSTANCESTATUS    ok
    DETAILS    reachability    passed
    SYSTEMSTATUS    ok
    DETAILS    reachability    passed
    
  7. Use the aws ec2 authorize-security-group-ingress to enable SSH access to the VM

    • List the Security Group for the VM
      $ aws ec2 describe-instance-attribute --instance-id i-0e5641b24d9618aa8 --attribute groupSet --region us-east-2
      i-0e5641b24d9618aa8
      GROUPS    sg-ebf9c788
      
    • Display the ingress and egress specification for the VM assigned Security Group
      $ aws ec2 describe-security-groups --group-name default  --region us-east-2
      SECURITYGROUPS    default VPC security group    sg-ebf9c788    default    598691507898    vpc-5076823b
      IPPERMISSIONSEGRESS    -1
      IPRANGES    0.0.0.0/0
      
    • Display the ingress and egress specification for the default Security Group (same as above)
      $ aws ec2 describe-security-groups --group-name default  --region us-east-2
      SECURITYGROUPS    default VPC security group    sg-ebf9c788    default    598691507898    vpc-5076823b
      IPPERMISSIONSEGRESS    -1
      IPRANGES    0.0.0.0/0
      
    • Get the workstation Internet external IP-address by probing ifconfig.co or equivalent service, if it don't work, temporarily use --cidr "0.0.0.0/0"
      $ curl ifconfig.co # or LANG=C wget -qO- ifconfig.co
      123.204.213.49
      
    • Set the Security Group VM ingress to allow SSH from the workstation Internet external IP-address
      $ aws ec2 authorize-security-group-ingress --group-id sg-ebf9c788 --protocol tcp --port 22 --cidr "123.204.213.49/24" --region us-east-2
      
    • Display the Security Group VM ingress and egress specification for the VM assigned Security Group
      $  aws ec2 describe-security-groups --group-id sg-ebf9c788  --region us-east-2
      SECURITYGROUPS    default VPC security group    sg-ebf9c788    default    598691507898    vpc-5076823b
      IPPERMISSIONS    22    tcp    22
      IPRANGES    123.204.213.0/24
      IPPERMISSIONSEGRESS    -1
      IPRANGES    0.0.0.0/0
      
  8. Use the aws ec2 describe-volumes to display the VM DISK ID

    $ aws ec2 describe-volumes --region us-east-2 --query 'Volumes[*].[Attachments[0].InstanceId,AvailabilityZone,VolumeId,Size]'
    i-06ada2bc32da15446    us-east-2b    vol-0cc41c407d9deb7eb    8
    
    $ alias lsvol="aws ec2 describe-volumes --region us-east-2 --query 'Volumes[*].[Attachments[0].InstanceId,AvailabilityZone,VolumeId,Size]'"
    
  9. Use the aws ec2 describe-subnets to display the VM SUBNETS

    $ aws ec2 describe-subnets --region us-east-2 --query 'Subnets[*].[VpcId,SubnetId,AvailabilityZone,CidrBlock,State]'
    vpc-5076823b    subnet-d38e339f    us-east-2c    172.31.32.0/20    available
    vpc-5076823b    subnet-9da9b5f5    us-east-2a    172.31.0.0/20     available
    vpc-5076823b    subnet-7524710f    us-east-2b    172.31.16.0/20    available
    
    $ alias lsnet=" aws ec2 describe-subnets --region us-east-2 --query 'Subnets[*].[VpcId,SubnetId,AvailabilityZone,CidrBlock,State]'"
    
  10. Use the aws ec2 describe-network-acls to display the VM SUBNET ACLs (Access Control List)
    NB. Entries[].Egress indicates whether the rule is an egress rule (True) traffic leaving the subnet, or an ingress rule (False) traffic arrving to the subnet

    $ aws ec2 describe-network-acls --region us-east-2 --query 'NetworkAcls[*].[VpcId,IsDefault,Associations[].NetworkAclId,Associations[].SubnetId,Entries[].CidrBlock,Entries[].Egress,Entries[].Protocol,Entries[].RuleAction,Entries[].IcmpTypeCode[].Code,Entries[].IcmpTypeCode[].Type]' 
    vpc-5076823b    True
    acl-e865b683    acl-e865b683    acl-e865b683
    subnet-9da9b5f5    subnet-d38e339f    subnet-7524710f
    0.0.0.0/0    0.0.0.0/0    0.0.0.0/0    0.0.0.0/0
    True    True    False    False
    -1    -1    -1    -1
    allow    deny    allow    deny
    

  1. Use SSH to login to the VM
    NB. Use the default [user name] (https://docs.aws.amazon.com/en_pv/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-get-info-about-instance), such as ec2-user.
    $ ssh -i "ec2-vmadmin-key.pem" ec2-user@ec2-3-16-167-39.us-east-2.compute.amazonaws.com
    The authenticity of host 'ec2-3-16-167-39.us-east-2.compute.amazonaws.com (3.16.167.39)' can't be established.
    ECDSA key fingerprint is SHA256:zJIOSADz3yfFt1045eNyS6lgOh4Nd47ATASrehF/UxY.
    Are you sure you want to continue connecting (yes/no)? yes
    Warning: Permanently added 'ec2-3-16-167-39.us-east-2.compute.amazonaws.com,3.16.167.39' (ECDSA) to the list of known hosts.
    
    __|  __|_  )
    _|  (     /   Amazon Linux 2 AMI
    ___|\___|___|
    
    https://aws.amazon.com/amazon-linux-2/
    7 package(s) needed for security, out of 10 available
    Run "sudo yum update" to apply all updates.
    [ec2-user@ip-3-16-167-39 ~]$ 
    
    • Customize the login environment on the VM
    [ec2-user@ip-3-16-167-39 ~]$ cat >> .bashrc
    export LC_CTYPE=C
    export PS1="\u@\h:\w$ "
    set -o vi
    <CTRL-D>
    
    [ec2-user@ip-3-16-167-39 ~]$ . ./.bashrc
    
    ec2-user@vm-solo-03:~$ uname -a
    Linux vm-solo-03 4.14.123-111.109.amzn2.x86_64 #1 SMP Mon Jun 10 19:37:57 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
    
    ec2-user@vm-solo-03:~$ egrep -i 'processor|model n|cpu [mc]|flags' /proc/cpuinfo
    processor	: 0
    model name	: Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz
    cpu MHz		: 2400.061
    cpu cores	: 1
    flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx rdtscp lm constant_tsc rep_good nopl xtopology cpuid pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm cpuid_fault invpcid_single pti fsgsbase bmi1 avx2 smep bmi2 erms invpcid xsaveopt
    
    Customize the VM, such as installing software and basic verification that it's working
    ec2-user@vm-solo-03:~$ sudo yum -y update
    Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
    Resolving Dependencies
    ...
    Updated:
    amazon-linux-extras.noarch 0:1.6.9-1.amzn2                             amazon-linux-extras-yum-plugin.noarch 0:1.6.9-1.amzn2     amazon-ssm-agent.x86_64 0:2.3.662.0-1.amzn2       
    cloud-utils-growpart.noarch 0:0.31-1.amzn2                             curl.x86_64 0:7.61.1-11.amzn2.0.2                         dracut.x86_64 0:033-535.amzn2.1.3                 
    dracut-config-generic.x86_64 0:033-535.amzn2.1.3                       ec2-hibinit-agent.noarch 0:1.0.0-4.amzn2                  ec2-instance-connect.noarch 0:1.1-10.amzn2        
    glib2.x86_64 0:2.56.1-4.amzn2                                          libcurl.x86_64 0:7.61.1-11.amzn2.0.2                      libssh2.x86_64 0:1.4.3-12.amzn2.2.1               
    mariadb-libs.x86_64 1:5.5.64-1.amzn2                                   nss-softokn.x86_64 0:3.36.0-5.amzn2.0.1                   nss-softokn-freebl.x86_64 0:3.36.0-5.amzn2.0.1    
    systemtap-runtime.x86_64 0:4.1-0.20190208git4e76869512d2.amzn2.0.2    
    
    Complete!   
    
    ec2-user@vm-solo-03:~$ sudo yum -y install gcc
    ...
    
    ec2-user@vm-solo-03:~$ gcc --version
    gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)
    Copyright (C) 2017 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    
    ec2-user@vm-solo-03:~$ python --version
    Python 2.7.16
    
    ec2-user@vm-solo-03:~$ amazon-linux-extras list
    ...
     38  nginx1                   available    [ =stable ]
    ...
    
    ec2-user@vm-solo-03:~$ sudo amazon-linux-extras install nginx1
    Installing nginx
    ...
    Install  1 Package (+20 Dependent packages)
    
    Total download size: 4.2 M
    Installed size: 11 M
    Is this ok [y/d/N]: y
    ...
    Installed:
      nginx.x86_64 1:1.12.2-2.amzn2.0.2                                                                                                                                                  
    
    Dependency Installed:
      fontconfig.x86_64 0:2.10.95-11.amzn2.0.2               fontpackages-filesystem.noarch 0:1.44-8.amzn2                 gd.x86_64 0:2.0.35-26.amzn2.0.2                               
      gperftools-libs.x86_64 0:2.6.1-1.amzn2                 libX11.x86_64 0:1.6.5-2.amzn2.0.2                             libX11-common.noarch 0:1.6.5-2.amzn2.0.2                      
      libXau.x86_64 0:1.0.8-2.1.amzn2.0.2                    libXpm.x86_64 0:3.5.12-1.amzn2.0.2                            libpng.x86_64 2:1.5.13-7.amzn2.0.2                            
      libxcb.x86_64 0:1.12-1.amzn2.0.2                       libxslt.x86_64 0:1.1.28-5.amzn2.0.2                           nginx-all-modules.noarch 1:1.12.2-2.amzn2.0.2                 
      nginx-filesystem.noarch 1:1.12.2-2.amzn2.0.2           nginx-mod-http-geoip.x86_64 1:1.12.2-2.amzn2.0.2              nginx-mod-http-image-filter.x86_64 1:1.12.2-2.amzn2.0.2       
      nginx-mod-http-perl.x86_64 1:1.12.2-2.amzn2.0.2        nginx-mod-http-xslt-filter.x86_64 1:1.12.2-2.amzn2.0.2        nginx-mod-mail.x86_64 1:1.12.2-2.amzn2.0.2                    
      nginx-mod-stream.x86_64 1:1.12.2-2.amzn2.0.2           stix-fonts.noarch 0:1.1.0-5.amzn2                            
    
    Complete!
    ...
     38  nginx1=latest            enabled      [ =stable ]
    
    ec2-user@vm-solo-03:~$ netstat -an|grep 'tcp .*'
    tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN     
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN     
    tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
    tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN     
    tcp        0     36 172.31.41.242:22        123.204.213.49:46134    ESTABLISHED
    
    ec2-user@vm-solo-03:~$ sudo systemctl enable nginx
    Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
    
    ec2-user@vm-solo-03:~$ sudo systemctl start nginx
    ec2-user@vm-solo-03:~$ netstat -an|grep 'tcp .*80'
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN     
    
    ec2-user@vm-solo-03:~$ ip -brief -4 address
    lo               UNKNOWN        127.0.0.1/8 
    eth0             UP             172.31.41.242/20 
    
    ec2-user@vm-solo-03:~$ curl --silent -q http://172.31.41.242:80 | grep -i welcome
    <h1>Welcome to <strong>nginx</strong> on Amazon Linux!</h1>
    
    ec2-user@vm-solo-03:~$ exit
    logout
    Connection to 3.16.167.39 closed.
    
    • Open port 80 for the VM; verify access
    $ aws ec2 describe-instance-attribute --instance-id i-0e5641b24d9618aa8 --attribute groupSet --region us-east-2
    i-0e5641b24d9618aa8
    GROUPS    sg-ebf9c788
    
    $ aws ec2 authorize-security-group-ingress --group-id sg-ebf9c788 --protocol tcp --port 80 --cidr "0.0.0.0/0" --region us-east-2
    
    $ curl --silent -q http://3.16.167.39:80 | grep -i welcome
    <h1>Welcome to <strong>nginx</strong> on Amazon Linux!</h1>
    
    • Continue customize the VM...
    $ ssh -v -v -v -i "ec2-vmadmin-key.pem" ec2-user@ec2-3-16-167-39.us-east-2.compute.amazonaws.com
    ...
    
    $ ec2-user@vm-solo-03:~$ sudo yum -y install mariadb-server
    ...
    
    ec2-user@vm-solo-03:~$ sudo systemctl start mariadb
    
    ec2-user@vm-solo-03:~$ sudo systemctl enable mariadb
    Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
    
    ec2-user@vm-solo-03:~$ sudo systemctl status mariadb
    * mariadb.service - MariaDB database server
       Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
       Active: active (running) since Sat 2019-09-21 00:35:13 UTC; 3min 10s ago
    ...
    
    ec2-user@vm-solo-03:~$ sudo mysql_secure_installation
    
    NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
          SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
    
    In order to log into MariaDB to secure it, we'll need the current
    password for the root user.  If you've just installed MariaDB, and
    you haven't set the root password yet, the password will be blank,
    so you should just press enter here.
    
    Enter current password for root (enter for none): 
    OK, successfully used password, moving on...
    
    Setting the root password ensures that nobody can log into the MariaDB
    root user without the proper authorisation.
    
    Set root password? [Y/n] 
    New password: 
    Re-enter new password: 
    Password updated successfully!
    Reloading privilege tables..
     ... Success!
    
    By default, a MariaDB installation has an anonymous user, allowing anyone
    to log into MariaDB without having to have a user account created for
    them.  This is intended only for testing, and to make the installation
    go a bit smoother.  You should remove them before moving into a
    production environment.
    
    Remove anonymous users? [Y/n] 
     ... Success!
    
    Normally, root should only be allowed to connect from 'localhost'.  This
    ensures that someone cannot guess at the root password from the network.
    
    Disallow root login remotely? [Y/n] 
     ... Success!
    
    By default, MariaDB comes with a database named 'test' that anyone can
    access.  This is also intended only for testing, and should be removed
    before moving into a production environment.
    
    Remove test database and access to it? [Y/n] 
     - Dropping test database...
     ... Success!
     - Removing privileges on test database...
     ... Success!
    
    Reloading the privilege tables will ensure that all changes made so far
    will take effect immediately.
    
    Reload privilege tables now? [Y/n] 
     ... Success!
    
    Cleaning up...
    
    All done!  If you've completed all of the above steps, your MariaDB
    installation should now be secure.
    
    Thanks for using MariaDB!
    
    ec2-user@vm-solo-03:~$ mysql -u root -p
    Enter password: 
    Welcome to the MariaDB monitor.  Commands end with ; or \g.
    Your MariaDB connection id is 10
    Server version: 5.5.64-MariaDB MariaDB Server
    
    Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    MariaDB [(none)]> CREATE DATABASE userdb;
    Query OK, 1 row affected (0.00 sec)
    
    MariaDB [(none)]> USE userdb;
    Database changed
    MariaDB [userdb]> CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY,name VARCHAR(8) NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
    Query OK, 0 rows affected (0.01 sec)
    
    MariaDB [userdb]> LOAD DATA LOCAL INFILE "/tmp/users.csv",INTO TABLE users,FIELDS TERMINATED BY ",",LINES TERMINATED BY "\n" ;
    ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INTO TABLE users,FIELDS TERMINATED BY ",",LINES TERMINATED BY "\n"' at line 1
    MariaDB [userdb]> LOAD DATA LOCAL INFILE "/tmp/users.csv"
        -> INTO TABLE users
        -> FIELDS TERMINATED BY ","
        -> LINES TERMINATED BY "\n" ;
    Query OK, 27 rows affected, 31 warnings (0.01 sec)   
    Records: 27  Deleted: 0  Skipped: 0  Warnings: 31
    
    MariaDB [userdb]> SELECT * FROM users;
    +-------+----------+---------------------+
    | id    | name     | created_at          |
    +-------+----------+---------------------+
    |     0 | root     | 2019-09-21 00:42:55 |
    |     1 | bin      | 2019-09-21 00:42:55 |
    |     2 | daemon   | 2019-09-21 00:42:55 |
    ...
    |   998 | ec2-inst | 2019-09-21 00:42:55 |
    |   999 | libstora | 2019-09-21 00:42:55 |
    |  1000 | ec2-user | 2019-09-21 00:42:55 |
    | 65534 | nfsnobod | 2019-09-21 00:42:55 |
    +-------+----------+---------------------+
    27 rows in set (0.00 sec)
    
    MariaDB [userdb]> DROP TABLE users;
    Query OK, 0 rows affected (0.00 sec)
    
    MariaDB [userdb]> DROP DATABASE userdb;
    Query OK, 0 rows affected (0.00 sec)
    
    MariaDB [(none)]> exit
    Bye
    ec2-user@vm-solo-03:~$ exit
    logout
    Connection to 3.16.167.39 closed.
    
    • Clone the VM; deploy the cloned image of the VM; verify
    $ aws ec2 describe-volumes --region us-east-2 --query 'Volumes[*].[Attachments[0].InstanceId,AvailabilityZone,VolumeId,Size]'
    
    $ aws ec2 create-image --instance-id i-0acc276625f356ab4 --name "image-cloned-amiv2" --region us-east-2
    ami-00eb03b823d707ba9
    
    $ aws ec2 describe-images --image-ids ami-00eb03b823d707ba9 --region us-east-2
    IMAGES    x86_64    2019-09-21T01:28:38.000Z    True    xen    ami-00eb03b823d707ba9    598691507898/image-cloned-amiv2    machine    image-cloned-amiv2    598691507898    False    /dev/xvda    ebs    simple    available    hvm
    BLOCKDEVICEMAPPINGS    /dev/xvda
    EBS    True    False    snap-00319d160bdebfb88    8    gp2
    
    $ aws ec2 run-instances --region us-east-2 --image-id ami-00eb03b823d707ba9 --instance-type t2.micro --key-name ec2-vmadmin-key --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=vm-clone-03}]' --output json > vm-clone-03.json
    
    $ lsvm
    vm-clone-03    i-06235481dbc79d393    172.31.26.67    3.17.147.19    us-east-2b    pending
    vm-solo-03     i-0acc276625f356ab4    172.31.41.242   3.16.167.39    us-east-2c    running
    
    $ lsvm
    vm-clone-03    i-06235481dbc79d393    172.31.26.67    3.17.147.19    us-east-2b    running
    vm-solo-03     i-0acc276625f356ab4    172.31.41.242   3.16.167.39    us-east-2c    running
    
    $ curl --silent -q http://3.16.167.39:80 | grep -i welcome
            <h1>Welcome to <strong>nginx</strong> on Amazon Linux!</h1>
    

  • Use the aws ec2 start-instances to start a stopped VM
$ aws ec2 start-instances --instance-id i-0acc276625f356ab4 --region us-east-2
STARTINGINSTANCES    i-0acc276625f356ab4
CURRENTSTATE    0    pending
PREVIOUSSTATE    80    stopped
  • Use the aws ec2 stop-instances to shutdown a VM
$ aws ec2 stop-instances --instance-id i-0acc276625f356ab4 --region us-east-2
STOPPINGINSTANCES    i-0acc276625f356ab4
CURRENTSTATE    64    stopping
PREVIOUSSTATE    16    running
  • Use the aws ec2 stop-instances --hibernate to hibernate a VM
    NB. Require VM type supporting hibernation and configured at launch (--hibernation-options '{"Configured": true}').
  • Use the aws ec2 terminate-instances to delete a VM
    NB. After the instance is terminated, it remains visible on the console for a short while, and then the entry is deleted.
$ aws ec2 terminate-instances --instance-id i-0acc276625f356ab4 --region us-east-2
TERMINATINGINSTANCES    i-0acc276625f356ab4
CURRENTSTATE    48    terminated
PREVIOUSSTATE    80    stopped

$ aws ec2 terminate-instances --instance-id i-0acc276625f356ab4 --region us-east-2
TERMINATINGINSTANCES    i-0acc276625f356ab4
CURRENTSTATE    32    shutting-down
PREVIOUSSTATE    16    running

  • Prepare deciding the VM LOCATION using the aws ec2 describe-regions (if no default region is configured, specify one to access the information from); will show the regions that are currently available (enabled for the account) aws-regions
$ aws ec2 describe-regions --region us-east-2 --query "Regions[]" --output table
--------------------------------------------------------
|                    DescribeRegions                   |
+-----------------------------------+------------------+
|             Endpoint              |   RegionName     |
+-----------------------------------+------------------+
|  ec2.eu-north-1.amazonaws.com     |  eu-north-1      |
|  ec2.ap-south-1.amazonaws.com     |  ap-south-1      |
|  ec2.eu-west-3.amazonaws.com      |  eu-west-3       |
|  ec2.eu-west-2.amazonaws.com      |  eu-west-2       |
|  ec2.eu-west-1.amazonaws.com      |  eu-west-1       |
|  ec2.ap-northeast-2.amazonaws.com |  ap-northeast-2  |
|  ec2.ap-northeast-1.amazonaws.com |  ap-northeast-1  |
|  ec2.sa-east-1.amazonaws.com      |  sa-east-1       |
|  ec2.ca-central-1.amazonaws.com   |  ca-central-1    |
|  ec2.ap-southeast-1.amazonaws.com |  ap-southeast-1  |
|  ec2.ap-southeast-2.amazonaws.com |  ap-southeast-2  |
|  ec2.eu-central-1.amazonaws.com   |  eu-central-1    |
|  ec2.us-east-1.amazonaws.com      |  us-east-1       |
|  ec2.us-east-2.amazonaws.com      |  us-east-2       |
|  ec2.us-west-1.amazonaws.com      |  us-west-1       |
|  ec2.us-west-2.amazonaws.com      |  us-west-2       |
+-----------------------------------+------------------+
  • Prepare deciding the VM SIZE using the aws pricing get-attribute-values , in this case selecting only t2.micro ec2-instance-type
    NB. Require adding the Policy AWSPriceListServiceFullAccess to the GROUP, othwerise error:
    An error occurred (AccessDeniedException) when calling the GetAttributeValues operation: User: arn:aws:iam::598691507898:user/ec2admin is not authorized to perform: pricing:GetAttributeValues
$ aws pricing get-attribute-values --region us-east-1 --service-code=AmazonEC2 --attribute-name=instanceType |awk '/t2\./{print $2}'
t2.2xlarge
t2.large
t2.medium
t2.micro
t2.nano
t2.small
t2.xlarge
  • Prepare deciding the VM IMAGE using the aws ec2 describe-images (region specific), in this case selecting only ami-hvm-2.0 Amazon Machine Image (ami) Hardware Virtualized Machine (hvm) v2.0
$ aws ec2 describe-images --region us-east-2 --owners amazon --filters 'Name=name,Values=amzn2-ami-hvm-2.?.????????-x86_64-gp2' 'Name=state,Values=available' --output json | jq -r '.Images | sort_by(.CreationDate) | last(.[]).ImageId'
ami-0d8f6eb4f641ef691

$ aws ec2 describe-images --image-ids ami-0d8f6eb4f641ef691 --region us-east-2 --output table
----------------------------------------------------------------------------
|                              DescribeImages                              |
+--------------------------------------------------------------------------+
||                                 Images                                 ||
|+---------------------+--------------------------------------------------+|
||  Architecture       |  x86_64                                          ||
||  CreationDate       |  2019-06-19T21:59:15.000Z                        ||
||  Description        |  Amazon Linux 2 AMI 2.0.20190618 x86_64 HVM gp2  ||
||  EnaSupport         |  True                                            ||
||  Hypervisor         |  xen                                             ||
||  ImageId            |  ami-0d8f6eb4f641ef691                           ||
||  ImageLocation      |  amazon/amzn2-ami-hvm-2.0.20190618-x86_64-gp2    ||
||  ImageOwnerAlias    |  amazon                                          ||
||  ImageType          |  machine                                         ||
||  Name               |  amzn2-ami-hvm-2.0.20190618-x86_64-gp2           ||
||  OwnerId            |  137112412989                                    ||
||  Public             |  True                                            ||
||  RootDeviceName     |  /dev/xvda                                       ||
||  RootDeviceType     |  ebs                                             ||
||  SriovNetSupport    |  simple                                          ||
||  State              |  available                                       ||
||  VirtualizationType |  hvm                                             ||
|+---------------------+--------------------------------------------------+|
|||                          BlockDeviceMappings                         |||
||+-----------------------------------+----------------------------------+||
|||  DeviceName                       |  /dev/xvda                       |||
||+-----------------------------------+----------------------------------+||
||||                                 Ebs                                ||||
|||+-------------------------------+------------------------------------+|||
||||  DeleteOnTermination          |  True                              ||||
||||  Encrypted                    |  False                             ||||
||||  SnapshotId                   |  snap-077085afe6b3ee68d            ||||
||||  VolumeSize                   |  8                                 ||||
||||  VolumeType                   |  gp2                               ||||
|||+-------------------------------+------------------------------------+|||

  • Use the aws ec2 help to show options
NAME
ec2 -

DESCRIPTION
Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable
computing capacity in the AWS cloud. Using Amazon  EC2  eliminates  the
need  to  invest  in  hardware  up front, so you can develop and deploy
applications faster.

To learn more about Amazon EC2, Amazon EBS, and  Amazon  VPC,  see  the
following resources:

o Amazon EC2 product page
o Amazon EC2 documentation
o Amazon EBS product page
o Amazon VPC product page
o Amazon VPC documentation

AVAILABLE COMMANDS
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment