본문 바로가기

study/Ansible101 1기

Ansible101 1기 실습환경 구성

안녕하세요, 덴고입니다.

CloudNet@에서 주관하는 Ansible101 스터디에 참여하게 되었습니다.

스터디 내용을 공유하고자 블로그에 작성합니다.

 

스터디 교재는 아래와 같습니다.

 

실습 환경은 AWS에서 구성했으며 

인스턴스 정보는 아래 표과 같습니다.

 

실습환경을 스터디장인 '가시다'님이 CloudFormation으로 제공해주셔서 쉽게 실습환경을 구성할 수 있었습니다.

VPC, 서브넷, 인스턴스 등 자세한 정보은 아래와 같습니다.

AWSTemplateFormatVersion: '2010-09-09'

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: "<<<<< Deploy EC2 >>>>>"
        Parameters:
          - KeyName
          - SgIngressSshCidr
          - MyInstanceType
          - LatestAmiId

      - Label:
          default: "<<<<< Region AZ >>>>>"
        Parameters:
          - TargetRegion
          - AvailabilityZone1
          - AvailabilityZone2

      - Label:
          default: "<<<<< VPC Subnet >>>>>"
        Parameters:
          - VpcBlock
          - PublicSubnet1Block
          - PublicSubnet2Block

Parameters:
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instances.
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
  SgIngressSshCidr:
    Description: The IP address range that can be used to communicate to the EC2 instances.
    Type: String
    MinLength: '9'
    MaxLength: '18'
    Default: 0.0.0.0/0
    AllowedPattern: (\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})
    ConstraintDescription: must be a valid IP CIDR range of the form x.x.x.x/x.
  MyInstanceType:
    Description: Enter EC2 Type(Spec) Ex) t2.micro.
    Type: String
    Default: t3.medium
  LatestAmiId:
    Description: (DO NOT CHANGE)
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/canonical/ubuntu/server/22.04/stable/current/amd64/hvm/ebs-gp2/ami-id'
    AllowedValues:
      - /aws/service/canonical/ubuntu/server/22.04/stable/current/amd64/hvm/ebs-gp2/ami-id

  TargetRegion:
    Type: String
    Default: ap-northeast-2
  AvailabilityZone1:
    Type: String
    Default: ap-northeast-2a
  AvailabilityZone2:
    Type: String
    Default: ap-northeast-2c

  VpcBlock:
    Type: String
    Default: 10.10.0.0/16
  PublicSubnet1Block:
    Type: String
    Default: 10.10.1.0/24
  PublicSubnet2Block:
    Type: String
    Default: 10.10.2.0/24

Resources:
# VPC
  AnsibleVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcBlock
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: Ansible-VPC

# PublicSubnets
  PublicSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: !Ref AvailabilityZone1
      CidrBlock: !Ref PublicSubnet1Block
      VpcId: !Ref AnsibleVPC
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: Ansible-PublicSubnet1
  PublicSubnet2:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: !Ref AvailabilityZone2
      CidrBlock: !Ref PublicSubnet2Block
      VpcId: !Ref AnsibleVPC
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: Ansible-PublicSubnet2

  InternetGateway:
    Type: AWS::EC2::InternetGateway
  VPCGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref InternetGateway
      VpcId: !Ref AnsibleVPC

  PublicSubnetRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref AnsibleVPC
      Tags:
        - Key: Name
          Value: Ansible-PublicSubnetRouteTable
  PublicSubnetRoute:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PublicSubnetRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
  PublicSubnet1RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet1
      RouteTableId: !Ref PublicSubnetRouteTable
  PublicSubnet2RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet2
      RouteTableId: !Ref PublicSubnetRouteTable


# EC2 Hosts
  EC2SG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Ansible EC2 Security Group
      VpcId: !Ref AnsibleVPC
      Tags:
        - Key: Name
          Value: Ansible-SG
      SecurityGroupIngress:
      - IpProtocol: '-1'
        CidrIp: !Ref SgIngressSshCidr
      - IpProtocol: '-1'
        CidrIp: 10.10.0.0/16

 

 

 

아래 인스턴스 설정 정보를 자세히 보면 호스트 이름 설정, hosts파일에 node1,2,3의 ip정보를 입력한 것을 볼 수 있습니다.

  EC21:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref MyInstanceType
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: Ansible-Server
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref PublicSubnet1
          GroupSet:
          - !Ref EC2SG
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.10.1.10
      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            VolumeType: gp3
            VolumeSize: 30
            DeleteOnTermination: true
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            hostnamectl --static set-hostname server

            # Config root account
            echo 'root:qwe123' | chpasswd
            sed -i "s/^PasswordAuthentication no/PasswordAuthentication yes/g" /etc/ssh/sshd_config
            sed -i "s/^#PermitRootLogin prohibit-password/PermitRootLogin yes/g" /etc/ssh/sshd_config
            systemctl restart sshd
            rm -rf /root/.ssh/authorized_keys

            # Config convenience
            echo 'alias vi=vim' >> /etc/profile
            systemctl stop ufw && systemctl disable ufw
            systemctl stop apparmor && systemctl disable apparmor
            ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

            # Setting Local DNS Using Hosts file
            echo "10.10.1.10 server" >> /etc/hosts
            for (( i=1; i<=3; i++  )); do echo "10.10.1.1$i tnode$i" >> /etc/hosts; done

            # Install packages
            apt update -qq && apt install tree jq -y

            # Git Clone
            mkdir /root/my-ansible
            git clone https://github.com/naleejang/Easy-Ansible.git /root/my-ansible/Easy-Ansible

  EC22:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref MyInstanceType
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: tnode1
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref PublicSubnet1
          GroupSet:
          - !Ref EC2SG
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.10.1.11
      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            VolumeType: gp3
            VolumeSize: 30
            DeleteOnTermination: true
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            hostnamectl --static set-hostname tnode1

            # Config root account
            echo 'root:qwe123' | chpasswd
            sed -i "s/^PasswordAuthentication no/PasswordAuthentication yes/g" /etc/ssh/sshd_config
            sed -i "s/^#PermitRootLogin prohibit-password/PermitRootLogin yes/g" /etc/ssh/sshd_config
            systemctl restart sshd
            rm -rf /root/.ssh/authorized_keys

            # Config convenience
            echo 'alias vi=vim' >> /etc/profile
            systemctl stop ufw && systemctl disable ufw
            systemctl stop apparmor && systemctl disable apparmor
            ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

            # Install packages
            apt update -qq && apt install tree jq -y

  EC23:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref MyInstanceType
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: tnode2
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref PublicSubnet1
          GroupSet:
          - !Ref EC2SG
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.10.1.12
      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            VolumeType: gp3
            VolumeSize: 30
            DeleteOnTermination: true
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            hostnamectl --static set-hostname tnode2

            # Config root account
            echo 'root:qwe123' | chpasswd
            sed -i "s/^PasswordAuthentication no/PasswordAuthentication yes/g" /etc/ssh/sshd_config
            sed -i "s/^#PermitRootLogin prohibit-password/PermitRootLogin yes/g" /etc/ssh/sshd_config
            systemctl restart sshd
            rm -rf /root/.ssh/authorized_keys

            # Config convenience
            echo 'alias vi=vim' >> /etc/profile
            systemctl stop ufw && systemctl disable ufw
            systemctl stop apparmor && systemctl disable apparmor
            ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

            # Install packages
            apt update -qq && apt install tree jq -y

  EC24:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref MyInstanceType
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: tnode3
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref PublicSubnet1
          GroupSet:
          - !Ref EC2SG
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.10.1.13
      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            VolumeType: gp3
            VolumeSize: 30
            DeleteOnTermination: true
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            hostnamectl --static set-hostname tnode3

            # Config root account
            echo 'root:qwe123' | chpasswd
            sed -i "s/^PasswordAuthentication no/PasswordAuthentication yes/g" /etc/ssh/sshd_config
            sed -i "s/^#PermitRootLogin prohibit-password/PermitRootLogin yes/g" /etc/ssh/sshd_config
            systemctl restart sshd
            rm -rf /root/.ssh/authorized_keys

            # Config convenience
            echo 'alias vi=vim' >> /etc/profile
            systemctl stop ufw && systemctl disable ufw
            systemctl stop apparmor && systemctl disable apparmor
            ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

            # Install packages
            apt update -qq && apt install tree jq -y

 

 

 

 

 

설치 후 기본 환경을 확인해봅니다.

# 계정 정보 확인
whoami
id

# CPU, Mem, Disk 확인
htop
free -h
df -hT /

# /etc/hosts 확인
cat /etc/hosts

# 노드간 통신 확인
for i in {1..3}; do ping -c 1 tnode$i; done

 

 

그후 VSCODE를 사용합니다.

스터디를 통해서 VSCODE로 SSH접속을 처음 해봤습니다.

일단

Remote-SSH 플러그인(?)을 설치해야 합니다.

 

그리고

 

커맨드창(Ctrl + Shift + P) 입력 후 “Remote-SSH: Open Config…” 선택 후 자신의 SSH Config 파일을 열어야 합니다.

 

 

그리고 아래와 같이 AWS 인스턴스 정보 입력

# Read more about SSH config files: https://linux.die.net/man/5/ssh_config
Host ansible-server
    HostName 50.1.1.1 <- 각자 자신의 ansible-server 의 유동 공인 IP
    User root

 

 

 

그리고 호스트에 연결 클릭합니다.

 

그리고 아래 창에서 비밀번호 입력합니다.

 

 

연결 완료

 

 

 

----

이렇게 실습 환경을 구축해봤습니다.

회차마다 실습환경이 변경되기 때문에 실습 환경 구축은 이 포스팅으로 마무리하겠습니다.

그리고

아쉽지만 로컬에서 구축하는 게 쉽지는 않아 보이네요.

 

하지만, vscode를 통해 ssh접속 등 많은 것을 배우는 기회였습니다.

약 5주간의 스터디를 통해  더 성장하는 엔지니어가 되겠습니다.

 

 

##참고

https://www.youtube.com/watch?v=s5SGdlwdbpw

악분님이 유투브에서 docker-compose로 실습환경을 구성해주셨습니다.

'study > Ansible101 1기' 카테고리의 다른 글

Ansible101 1기 3주차 두번째  (0) 2024.01.28
Ansible101 1기 3주차 첫번째  (0) 2024.01.28
Ansible101 1기 2주차 두번째  (0) 2024.01.14
Ansible101 1기 2주차 첫번째  (0) 2024.01.14
Ansible101 1기 1주차  (0) 2024.01.07