카테고리 없음

Scripting with gcloud: Create a new command that automatically executes the 'gcloud init' command

chaenii 2022. 3. 31. 17:08

gcloud init 명령어를 사용자 입력없이 자동으로 실행시키고자함.

GCP 명령어 실행 결과를 다음 명령어에 바로 적용시킴으로써 일련의 GCP 작업들을 자동화할 수 있다는 걸 알았다.

shell script를 이용해 gcloud init 명령어를 자동화해서 실행할 수 있도록 만들어보았다.

 


For completeness gcloud init essentially runs the following steps:

  1. Select configuration (one of the following)
    • gcloud config configurations create my_configuration
    • gcloud config configurations activate my_configuration
  2. Set up credentials (one of the following)
    • (Interactive) gcloud auth login
    • gcloud config set account my_existing_credentials
    • gcloud auth activate-service-account
  3. Set project
    • gcloud config set project my_project
      • List of accessible projects for set credentials can be seen via gcloud projects list
  4. (Optional) Set default GCE zone (Compute API must be enabled)
    • gcloud config set compute/zone my_default_gce_zone
      • List of zones can be obtained via gcloud compute zones list
  5. (Optional) Set default GCE region (Compute API must be enabled)
    • gcloud config set compute/region my_default_gce_region
      • List of regions can be obtained via gcloud compute regions list
  6. (Optional) Create default config file for gsutil
    • gsutil config -n -o ~/.boto

[step 1] configuraion 선택하기

gcloud config configuration list --format= "value(name)" 

명령어의 출력을 읽어들여, configuration의 목록에 사용자가 입력한 configuration이 있는지 확인한다.

만약 없다면, configuration을 새로 만든다.

만약 있다면, configuration을 activate 한다.

 

[step 2] credential 설정하기

기존의 명령어를 실행한다.

 

[step 3] project 설정하기

기존 gcloud 명령어를 실행한다.

 

[step 4] default GCE Zone 설정하기

[step 5] default GCE Region 설정하기

필수 수행 명령어가 아니기 때문에 사용자가 입력한 경우에만 gcloud 명령어를 실행시킨다.

 

 

#!/bin/bash

# 1. select configuration

# Create a new configuration
# $1 - CONFIGURATION_NAME
EXIST=0
for instance in $(gcloud config configurations list --format="value(name)")
do
    INSTANCE_NO_WHITESPACE="$(echo ${instance} | tr -d ' ')"
    echo $INSTANCE_NO_WHITESPACE
    if [ $1 == $INSTANCE_NO_WHITESPACE ]; then
        EXIST=1
    fi
done


if [ ! $EXIST ]
then
   echo "[step 1] create a new configuration"
   gcloud config configurations create $1
else
   echo "[step 1] Switch to and re-initialize existing configuration: [$1]"
   gcloud config configurations activate $1
fi


# 2. set up credentials 
# $2 - KEY_FILE
echo "[step 2] set up credentials"
gcloud auth activate-service-account --key-file="/root/hcp-key.json"

# 3. set project
# $3 - PROJECT_ID
echo "[step 3] set project"
gcloud config set project $2

# [optional] 4. set default GCE Zone
# $4 - ZONE
if [ ! -z $3]
then 
    echo "[step 4] set default zone"
    gcloud config set compute/zone $3
fi

# [optional] 5. set default GCE region
# $5 - REGION
if [ ! -z $4]
then 
    echo "[step 5] set default region"
    gcloud config set compute/region $4
fi


# # Reference : https://stackoverflow.com/questions/42379685/can-i-automate-google-cloud-sdk-gcloud-init-interactive-command

추가로 cobra를 이용해 새로운 명령어 형식으로 만들어보았다.

 

exec 패키지를 이용해 위의 셀스크립트에 인자를 전달하고 명령어를 실행시켰다.

var GKEInitCmd = &cobra.Command{
	Use:   "init",
	Short: "initialize or reinitialize gcloud",
	Long: `hybridctl gke init
	
	[REQUIRED]    --configuration : configuration name
					1) if exist, just activate configuration
					2) if no exist, create a new configuration

	[REQUIRED]    --project-id : projectID

	[NO REQUIRED] --zone : default zone

	[NO REQUIRED] --region : default region
	`,
	Run: func(cmd *cobra.Command, args []string) {

		var arguments []string
		arguments = append(arguments, "gcloud", cobrautil.CONFIGURATION, cobrautil.PROJECT_ID)

		if cobrautil.ZONE != "" {
			arguments = append(arguments, cobrautil.ZONE)
		}

		if cobrautil.REGION != "" {
			arguments = append(arguments, cobrautil.REGION)
		}

		command := &exec.Cmd{
			Path:   "./gcloud-init.sh",
			Args:   arguments,
			Stdout: os.Stdout,
			Stderr: os.Stderr,
		}
		err := command.Start()
		if err != nil {
			fmt.Println(err)
		}
		err = command.Wait()
		if err != nil {
			fmt.Println(err)
		}
	},
}

 

https://stackoverflow.com/questions/42379685/can-i-automate-google-cloud-sdk-gcloud-init-interactive-command

 

Can I automate Google Cloud SDK gcloud init - interactive command

Documentation on Google Cloud SDK https://cloud.google.com/sdk/docs/ directs one to run gcloud init after installing it. Is there a way to automate this step given that gcloud init is an interactive

stackoverflow.com

https://cloud.google.com/blog/products/management-tools/scripting-with-gcloud-a-beginners-guide-to-automating-gcp-tasks

 

Google Cloud Blog | News, Features and Announcements

Official news, features and announcements for all Google Cloud products including Google Cloud Platform, Workspace, and much more.

cloud.google.com

https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php

 

If Statements - Bash Scripting Tutorial

Bash if statements are very useful. In this section of our Bash Scripting Tutorial you will learn the ways you may use if statements in your Bash scripts to help automate tasks. If statements (and, closely related, case statements) allow us to make decisio

ryanstutorials.net

 

반응형