DEV Community

Cover image for Important Settings of Amazon Linux 2 Which Can Be Done Using Ansible
Nurul Ramadhona for AWS Community Builders

Posted on • Updated on

 

Important Settings of Amazon Linux 2 Which Can Be Done Using Ansible

Amazon Linux 2 is Linux OS provided by AWS. Then, what’s the different with other OS? The one that we all know about it is we don’t need to install AWS CLI when we need to perform any AWS command through this OS. I think that’s the most “striking part” that we don’t get it on other OS.

More about Amazon Linux 2, click here!

Amazon Linux 2

Then, have you tried to setup "important settings" for Amazon Linux 2? Here I mean the basic configurations to do before you "really" use the server for production maybe or any purposes such as host web server or anything. I've summarized it into 5 things:

  1. Doing update
  2. Install any package (should be done after update). This is optional or can be executed at the last step but I placed it on number two since I'll install simple web server and will be executed after update.
  3. Management user
  4. Set timezone (I'll skip NTP client configuration since Amazon already provided Time Sync by default).
  5. Set hostname

Alright, as I mentioned on the title. All those 5 things can be done with ansible. As we all know, ansible is a configuration management tool too.

Prerequisites:

  1. AWS CLI and setup at least one credential;
  2. Ansible;
  3. Ansible collection for AWS by running ansible-galaxy collection install community.aws.

Before that, I'm going to launch an instance to configure it later.

Inventory: hosts.yml

---

localhost:
  hosts:
    127.0.0.1:
Enter fullscreen mode Exit fullscreen mode

Playbook: ec2.yml

    - name: launch new instance
      amazon.aws.ec2_instance:
        name: amazonlinux2
        region: ap-southeast-3
        key_name: ec2-user
        instance_type: t3.micro
        security_group: ssh-web
        vpc_subnet_id: subnet-0276d466994fa3087
        network:
          assign_public_ip: true
          delete_on_termination: true
        image_id: ami-0de34ee5744189c60 
        volumes: 
          - device_name: /dev/xvda
            ebs: 
              volume_size: 8
              volume_type: gp2
              delete_on_termination: true
      tags:
        - ec2_new
Enter fullscreen mode Exit fullscreen mode

Run the playbook!

$ ansible-playbook -i host.yml ec2.yml -t ec2_new

PLAY [ec2] **************************************************************************************************************************************************************

TASK [launch new instance] **********************************************************************************************************************************************
changed: [127.0.0.1]

PLAY RECAP **************************************************************************************************************************************************************
127.0.0.1                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
Enter fullscreen mode Exit fullscreen mode
$ aws ec2 describe-instances --query 'Reservations[].Instances[].{ID:InstanceId, PrivateIP:PrivateIpAddress, PublicIP:PublicIpAddress, Name:Tags[?Key==`Name`].Value}'
[
    {
        "ID": "i-0187e4bb5d2f2007c",
        "PrivateIP": "10.0.1.7",
        "PublicIP": "108.136.226.235",
        "Name": [
            "amazonlinux2a"
        ]
    },
    {
        "ID": "i-050cfb6ee36a57131",
        "PrivateIP": "10.0.1.5",
        "PublicIP": "108.136.225.50",
        "Name": [
            "amazonlinux2"
        ]
    },
    {
        "ID": "i-09c46dba004ed7bd8",
        "PrivateIP": "10.0.2.8",
        "PublicIP": "108.136.235.232",
        "Name": [
            "amazonlinux2b"
        ]
    },
    {
        "ID": "i-02c7573fff1215e65",
        "PrivateIP": "10.0.3.11",
        "PublicIP": "108.136.150.180",
        "Name": [
            "amazonlinux2c"
        ]
    }
]
Enter fullscreen mode Exit fullscreen mode

From the instances listed above, I'll use the amazonlinux2 instance with IP 108.136.225.50.

1. Update
By using * as the name, it'll be turned as yum -y update.

- name: al2
  hosts: new
  become: true
  gather_facts: no
  tasks:
    - name: update
      yum:
        name: "*"
        state: latest
Enter fullscreen mode Exit fullscreen mode

2. Install any package
Here I'll only install latest httpd for simple web server.

    - name: install web server
      yum:
        name: httpd
        state: latest

    - name: install web server
      service:
        name: httpd
        enabled: yes

    - name: modify home page
      shell: 'echo "Hello World!" >> /var/www/html/index.html'
Enter fullscreen mode Exit fullscreen mode

3. Management user
ec2-user is the default user of Amazon Linux 2. Then, how if we have some people that accessing the server. They can make any changes and we'll in difficult to identify who have done it cause anyone use the same username which is ec2-user. So, we need to provide different user based on their name. We also may need to let them act as sudoers since we use ssh key to connect to our EC2 instance and let's say they're sysadmin that will have all access level on the server with no password needed when they switch as sudo.

    - name: create user
      user:
        name: nurulramadhona
        shell: /bin/bash

    - name: copy pubkey
      authorized_key:
        user: nurulramadhona
        state: present
        key: "{{ lookup('file', '/home/nurulramadhona/.ssh/id_rsa.pub') }}"

    - name: set user as sudoers
      lineinfile: 
        path: /etc/sudoers.d/90-cloud-init-users
        line: 'nurulramadhona ALL=(ALL) NOPASSWD:ALL'
        insertafter: EOF
Enter fullscreen mode Exit fullscreen mode

4. Set timezone
(Please change to your zone)

    - name: set timezone
      community.general.timezone:
        name: Asia/Jakarta
Enter fullscreen mode Exit fullscreen mode

5. Set hostname
(Here I use to set hostname for localdomain only, you can change to your public domain if you already have and want to use it)

    - name: preserve hostname
      lineinfile: 
        path: /etc/cloud/cloud.cfg
        line: 'preserve_hostname: true'
        insertafter: EOF

    - name: set hostname
      command: hostnamectl set-hostname {{ hostname }}.localdomain

    - name: replace localhost entry
      lineinfile: 
        path: /etc/hosts
        regexp: '^127\.0\.0\.1'
        line: '127.0.0.1   {{ hostname }}.localdomain {{ hostname }} localhost4 localhost4.localdomain4'
        owner: root
        group: root 
        mode: "0644"
Enter fullscreen mode Exit fullscreen mode

Finally, when all tasks are ready. We have to add this to our inventory:

new:
  hosts:
    108.136.225.50:
  vars:
    hostname: amazonlinux2
Enter fullscreen mode Exit fullscreen mode

Now, let's run the playbook!

$ ansible-playbook -i host.yml al2.yml -u ec2-user

PLAY [al2] **************************************************************************************************************************************************************

TASK [update] ***********************************************************************************************************************************************************
changed: [108.136.225.50]

TASK [install web server] ***********************************************************************************************************************************************
changed: [108.136.225.50]

TASK [install web server] ***********************************************************************************************************************************************
changed: [108.136.225.50]

TASK [modify home page] *************************************************************************************************************************************************
changed: [108.136.225.50]

TASK [create user] ******************************************************************************************************************************************************
changed: [108.136.225.50]

TASK [copy pubkey] ******************************************************************************************************************************************************
changed: [108.136.225.50]

TASK [set user as sudoers] **********************************************************************************************************************************************
changed: [108.136.225.50]

TASK [set timezone] *****************************************************************************************************************************************************
changed: [108.136.225.50]

TASK [preserve hostname] ************************************************************************************************************************************************
changed: [108.136.225.50]

TASK [set hostname] *****************************************************************************************************************************************************
changed: [108.136.225.50]

TASK [replace localhost entry] ******************************************************************************************************************************************
changed: [108.136.225.50]

PLAY RECAP **************************************************************************************************************************************************************
108.136.225.50             : ok=11   changed=11   unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
Enter fullscreen mode Exit fullscreen mode

Let's check to remote the server again without specify the default user. Cause we already changed the hostname, we'll also do reboot.

$ ssh 108.136.225.50

       __|  __|_  )
       _|  (     /   Amazon Linux 2 AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-2/
[nurulramadhona@amazonlinux2 ~]$ sudo reboot
Connection to 108.136.225.50 closed by remote host.
Connection to 108.136.225.50 closed.
Enter fullscreen mode Exit fullscreen mode

Let's verify the settings by checking the hostname and timezone using ansible ad-hoc!

$ ansible -i host.yml new -m shell -a "hostname && date"
108.136.225.50 | CHANGED | rc=0 >>
amazonlinux2.localdomain
Sun Apr 24 15:35:24 WIB 2022
Enter fullscreen mode Exit fullscreen mode

That's it for Amazon Linux 2! For the next part, I'll do deletion of what we've created if you already followed all the posts since from VPC till here. Let's move to the next post!

References:
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Instances.html

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.