如何使用啟動範本,在執行 Amazon Linux 或 Ubuntu 的 Amazon EC2 執行個體上自動安裝 CodeDeploy 代理程式?

2 分的閱讀內容
0

如何在執行 Linux 或 Ubuntu 的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體上自動安裝 AWS CodeDeploy 代理程式?

解決方式

在您建立啟動範本時,您可使用 User data (使用者資料) 欄位,新增在執行個體啟動時執行的組態指令碼。此 Shell 指令碼會為所有 AWS 區域和支援的 Amazon Linux 和 Ubuntu 發行版安裝 CodeDeploy 代理程式。

**注意:**您可透過將 AUTOUPDATE 變數設定為 true,以將 CodeDeploy 設定為在啟動時自動更新。

例如,您可在 Amazon EC2 User data (使用者資料) 欄位中新增下列組態指令碼:

**重要事項:**下列指令碼僅適用於 Linux 的 EC2 中。在視窗環境中,指令碼會失敗。

#!/bin/bash -xe

## Code Deploy Agent Bootstrap Script##


exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
AUTOUPDATE=false

function installdep(){

if [ ${PLAT} = "ubuntu" ]; then

  apt-get -y update
  # Satisfying even ubuntu older versions.
  apt-get -y install jq awscli ruby2.0 || apt-get -y install jq awscli ruby



elif [ ${PLAT} = "amz" ]; then
  yum -y update
  yum install -y aws-cli ruby jq

fi

}

function platformize(){

#Linux OS detection#
 if hash lsb_release; then
   echo "Ubuntu server OS detected"
   export PLAT="ubuntu"


elif hash yum; then
  echo "Amazon Linux detected"
  export PLAT="amz"

 else
   echo "Unsupported release"
   exit 1

 fi
}


function execute(){

if [ ${PLAT} = "ubuntu" ]; then

  cd /tmp/
  wget https://aws-codedeploy-${REGION}.s3.amazonaws.com/latest/install
  chmod +x ./install

  if ./install auto; then
    echo "Installation completed"
      if ! ${AUTOUPDATE}; then
            echo "Disabling Auto Update"
            sed -i '/@reboot/d' /etc/cron.d/codedeploy-agent-update
            chattr +i /etc/cron.d/codedeploy-agent-update
            rm -f /tmp/install
      fi
    exit 0
  else
    echo "Installation script failed, please investigate"
    rm -f /tmp/install
    exit 1
  fi

elif [ ${PLAT} = "amz" ]; then

  cd /tmp/
  wget https://aws-codedeploy-${REGION}.s3.amazonaws.com/latest/install
  chmod +x ./install

    if ./install auto; then
      echo "Installation completed"
        if ! ${AUTOUPDATE}; then
            echo "Disabling auto update"
            sed -i '/@reboot/d' /etc/cron.d/codedeploy-agent-update
            chattr +i /etc/cron.d/codedeploy-agent-update
            rm -f /tmp/install
        fi
      exit 0
    else
      echo "Installation script failed, please investigate"
      rm -f /tmp/install
      exit 1
    fi

else
  echo "Unsupported platform ''${PLAT}''"
fi

}

platformize
installdep
REGION=$(curl -s 169.254.169.254/latest/dynamic/instance-identity/document | jq -r ".region")
execute

相關資訊

為 Auto Scaling 群組建立啟動範本

AWS 官方
AWS 官方已更新 1 年前