0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

jenkins で aws コマンド実行

Last updated at Posted at 2022-08-27

大枠

node {
    stage('check instance') {
        def resultArray = getInstanceInfoList()
        for (instance in resultArray) {
            if (instance.Status == "running") {
                // なにかする
            }
        }
    }
}

インスタンス情報取得

指定環境のフィルターとインスタンスID、稼働状況、OS情報、ip、タグ名を取得するクエリ設定

def getInstanceInfoList(String env = "")
{
    String filter = ""
    if (env.isEmpty()) {
        filter = "Name=tag-key,Values=envName"
    } else {
        filter = "Name=tag:envName,Values=${env}"    
    }
    
    String query = "Reservations[*].Instances[].{InstanceID:InstanceId, Status:State.Name, PlatformDetails: PlatformDetails, PublicIpAddress:PublicIpAddress,Tags:Tags[?Key==`envName`].Value|[0]}"
    GString cmd = """
        aws ec2 describe-instances \
            --filters ${filter} \
            --query '${query}' \
            --output json
    """
    return exeAwsCmd(cmd)
}

Platform だと windows しか取れなかったので、 PlatformDetails を使いました
linux は Linux/UNIX が返ってくるので、 PlatformDetails.toLowerCase().contains("windows") で判定して使ってます

aws コマンド実行

プラグインを利用
returnStdout を true にし標準入力を受け取る

def exeAwsCmd(GString cmd)
{
    withAWS(credentials:'XXXXX', region:'ap-northeast-1') {
        def resultJson = sh (
                script: cmd,
                returnStdout: true
        )
        resultArray = readJSON text: resultJson
    }
    return resultArray
}

その他

インスタンスの起動と停止

exeAwsCmd("aws ec2 start-instances --instance-ids ${instanceID}")
exeAwsCmd("aws ec2 stop-instances --instance-ids ${instanceID}")

パラメータを渡して他のジョブを実行
型string の env にタグ名を設定

build job: 'hogeJob', parameters: [
    [$class: 'StringParameterValue', name: 'env', value: instance.Tags]
]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?