brunch
매거진 테라폼 AWS

19탄-16. 테라폼-AWS-반복문 & if문

by Master Seo

다음은 주말 CloudNet 테라폼 스터디 내용 참고하여 정리한 부분입니다.

https://gasidaseo.notion.site/gasidaseo/CloudNet-Blog-c9dfa44a27ff431dafdd2edacc8a1863


<1> 함수 참고 사이트

<2> 반복문 count 매개변수 사용 - iam 사용자 생성

<3> 입력 변수로 IAM 만들기

<4> 제약사항

<5> 반복문 for_each 표현식 을 사용 - 제약 사항 해결 법



<1> 함수 참고 사이트


함수

https://developer.hashicorp.com/terraform/language/functions


표현식

https://developer.hashicorp.com/terraform/language/expressions


함수 활용

https://terraform101.inflearn.devopsart.dev/advanced/function/





<2> 반복문 count 매개변수 사용 - iam 사용자 생성


mkdir test

cd test



1

IAM 1명 계정을 생성 하는 코드 ?


provider "aws" {

region = "us-east-2"

}


resource "aws_iam_user" "example" {

name = "neo"

}


2

3명 생성


resource "aws_iam_user" "example" {

count = 3

name = "neo"

}


// 이름이 중복되어 오류!!!


3

해결?

count.index 사용하기


NICKNAME=<각자 닉네임>

NICKNAME=masterseo


cat <<EOT > iam.tf

provider "aws" {

region = "ap-northeast-2"

}


resource "aws_iam_user" "myiam" {

count = 3

name = "$NICKNAME.\${count.index}"

}

EOT


4

terraform init && terraform plan && terraform apply -auto-approve



5

aws iam list-users | jq


{

"UserName": "masterseo.0",

"Path": "/",

"CreateDate": "2022-11-15T00:03:36Z",

"UserId": "AIDAWSA5ESYZ7ODIMSWYA",

"Arn": "arn:aws:iam::451032684083:user/masterseo.0"

},

{

"UserName": "masterseo.1",

"Path": "/",

"CreateDate": "2022-11-15T00:03:36Z",

"UserId": "AIDAWSA5ESYZUSCK5WKGL",

"Arn": "arn:aws:iam::451032684083:user/masterseo.1"

},

{

"UserName": "masterseo.2",

"Path": "/",

"CreateDate": "2022-11-15T00:03:36Z",

"UserId": "AIDAWSA5ESYZ4YYFMWCNT",

"Arn": "arn:aws:iam::451032684083:user/masterseo.2"

}

]



6

콘솔에서 확인하기


7

유저 삭제

terraform destroy -auto-approve

aws iam list-users | jq




<3> 반복문 count 매개변수 사용 - 입력 변수로 IAM 만들기


따로 입력 변수를 입력해서 해당 이름으로 계정을 만들어 보자~


1

cat <<EOT > variables.tf

variable "user_names" {

description = "Create IAM users with these names"

type = list(string)

default = ["gasida", "akbun", "fullmoon"]

}

EOT



2

내장함수 , 배열 조회 구문을 사용하자!

length

user_names

count.index


cat <<EOT > iam.tf

provider "aws" {

region = "ap-northeast-2"

}

resource "aws_iam_user" "myiam" {

count = length(var.user_names)

name = var.user_names[count.index]

}

EOT


3

terraform init


4

플랜에서 결과값을 예측할수 있다.


terraform plan

[root@ip-172-31-61-209 test]# terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:

+ create

Terraform will perform the following actions:

# aws_iam_user.myiam[0] will be created

+ resource "aws_iam_user" "myiam" {

+ arn = (known after apply)

+ force_destroy = false

+ id = (known after apply)

+ name = "gasida"

+ path = "/"

+ tags_all = (known after apply)

+ unique_id = (known after apply)

}

# aws_iam_user.myiam[1] will be created

+ resource "aws_iam_user" "myiam" {

+ arn = (known after apply)

+ force_destroy = false

+ id = (known after apply)

+ name = "akbun"

+ path = "/"

+ tags_all = (known after apply)

+ unique_id = (known after apply)

}

# aws_iam_user.myiam[2] will be created

+ resource "aws_iam_user" "myiam" {

+ arn = (known after apply)

+ force_destroy = false

+ id = (known after apply)

+ name = "fullmoon"

+ path = "/"

+ tags_all = (known after apply)

+ unique_id = (known after apply)

}

Plan: 3 to add, 0 to change, 0 to destroy.



5

iam arn 출력하기?

첫번째 계정 , 전체 계정 ARN 을 출력해보자.


cat <<EOT > outputs.tf

output "first_arn" {

value = aws_iam_user.myiam[0].arn

description = "The ARN for the first user"

}


output "all_arns" {

value = aws_iam_user.myiam[*].arn

description = "The ARNs for all users"

}

EOT



5

terraform apply -auto-approve

Outputs:

all_arns = [

"arn:aws:iam::451032684083:user/gasida",

"arn:aws:iam::451032684083:user/akbun",

"arn:aws:iam::451032684083:user/fullmoon",



terraform state list

aws_iam_user.myiam[0]

aws_iam_user.myiam[1]

aws_iam_user.myiam[2]



terraform output

[root@ip-172-31-61-209 test]# terraform output

all_arns = [

"arn:aws:iam::451032684083:user/gasida",

"arn:aws:iam::451032684083:user/akbun",

"arn:aws:iam::451032684083:user/fullmoon",

]

first_arn = "arn:aws:iam::451032684083:user/gasida"






<4> 제약사항


1

전체 리소스를 반복할 수는 있지만 리소스 내에서 '인라인 블록'을 반복할 수는 없습니다.


2

중간 인덱스를 삭제할수도 없습니다.

akbun을 삭제하고 계획을 보자~


확인?

vi variables.tf

variable "user_names" {

description = "Create IAM users with these names"

type = list(string)

default = ["gasida", "fullmoon"]

}


4

akbun 삭제하고 계획보기

# plan : 출력 내용 확인!


terraform plan

...

~ update in-place

- destroy


Terraform will perform the following actions:


# aws_iam_user.myiam[1] will be updated in-place

~ resource "aws_iam_user" "myiam" {

id = "akbun"

~ name = "akbun" -> "fullmoon"

tags = {}

# (5 unchanged attributes hidden)

}


# aws_iam_user.myiam[2] will be destroyed

# (because index [2] is out of range for count)

- resource "aws_iam_user" "myiam" {

- arn = "arn:aws:iam::911283464785:user/fullmoon" -> null

- force_destroy = false -> null

- id = "fullmoon" -> null

- name = "fullmoon" -> null

- path = "/" -> null

- tags = {} -> null

- tags_all = {} -> null

- unique_id = "AIDA5ILF2FJI2ELMQRCZV" -> null

}


Plan: 0 to add, 1 to change, 1 to destroy.


Changes to Outputs:

~ all_arns = [

# (1 unchanged element hidden)

"arn:aws:iam::911283464785:user/akbun",

- "arn:aws:iam::911283464785:user/fullmoon",

]


생각한 데로 적용이 안됨.

akbun 제거인데 이상하게 동작함.



5

terraform apply -auto-approve

aws_iam_user.myiam[2]: Refreshing state... [id=fullmoon]

aws_iam_user.myiam[1]: Refreshing state... [id=akbun]

aws_iam_user.myiam[0]: Refreshing state... [id=gasida]


Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:

~ update in-place

- destroy


Terraform will perform the following actions:


# aws_iam_user.myiam[1] will be updated in-place

~ resource "aws_iam_user" "myiam" {

id = "akbun"

~ name = "akbun" -> "fullmoon"

tags = {}

# (5 unchanged attributes hidden)

}


# aws_iam_user.myiam[2] will be destroyed

# (because index [2] is out of range for count)

- resource "aws_iam_user" "myiam" {

- arn = "arn:aws:iam::911283464785:user/fullmoon" -> null

- force_destroy = false -> null

- id = "fullmoon" -> null

- name = "fullmoon" -> null

- path = "/" -> null

- tags = {} -> null

- tags_all = {} -> null

- unique_id = "AIDA5ILF2FJI2ELMQRCZV" -> null

}


Plan: 0 to add, 1 to change, 1 to destroy.


Changes to Outputs:

~ all_arns = [

# (1 unchanged element hidden)

"arn:aws:iam::911283464785:user/akbun",

- "arn:aws:iam::911283464785:user/fullmoon",

]

aws_iam_user.myiam[2]: Destroying... [id=fullmoon]

aws_iam_user.myiam[1]: Modifying... [id=akbun]

aws_iam_user.myiam[2]: Destruction complete after 1s


// fullmoon이 지워지고, akbun 삭제되고 이상해짐~



6

유저 삭제

terraform destroy -auto-approve

aws iam list-users | jq




<5> 반복문 for_each 표현식 을 사용 - 제약 사항 해결 법


1

for_each 표현식 을 사용하여 해결.

인라인 블록에서도 여러 복사본, 모듈의 복사본을 생성 가능하다.


2

형식?

resource "<PROVIDER>_<TYPE>" "<NAME>" {

for_each = <COLLECTION>


[CONFIG ...]

}


3

cat <<EOT > iam.tf

provider "aws" {

region = "ap-northeast-2"

}


resource "aws_iam_user" "myiam" {

for_each = toset(var.user_names)

name = each.value

}

EOT


// toset(리스트)로 리스트를 딕셔너리 형태의 값(키:값)으로 변환해서 사용



4

cat <<EOT > variables.tf

variable "user_names" {

description = "Create IAM users with these names"

type = list(string)

default = ["gasida", "akbun", "fullmoon"]

}

EOT



5

출력 변수로 지정해서 출력을 보자~~


cat <<EOT > outputs.tf

output "all_users" {

value = aws_iam_user.myiam

}

EOT



6

terraform plan && terraform apply -auto-approve



7

terraform state list

// 이름이 나온다.

aws_iam_user.myiam["akbun"]

aws_iam_user.myiam["fullmoon"]

aws_iam_user.myiam["gasida"]



8

terraform output

// 출력에 iam 사용자의 모든 정보가 나온다.



9

arn만 가져 오고 싶다면?


cat <<EOT > outputs.tf

output "all_users" {

value = values(aws_iam_user.myiam)[*].arn

}

EOT


terraform apply -auto-approve


terraform output



10

리스트 중간값을 제외하는 부분을 다시 테스트 해보자~

akbun 삭제



cat <<EOT > variables.tf

variable "user_names" {

description = "Create IAM users with these names"

type = list(string)

default = ["gasida", "fullmoon"]

}

EOT



11

terraform plan

# aws_iam_user.myiam["akbun"] will be destroyed


12

삭제

terraform destroy -auto-approve

aws iam list-users | jq




https://brunch.co.kr/@topasvga/2810





https://brunch.co.kr/@topasvga/2421

terraform.png


감사합니다.

매거진의 이전글19탄-15. 테라폼-AWS-모듈 실습