Site cover image

Site icon image OSKA’s BLOG

記事にするまでもないアウトプット置き場

Terraformでファイル単位でtarget指定して実行

ファイル単位でtarget指定

コマンド

# 変数に格納
target=`cat alb.tf | grep 'resource ' | tr -d '"' | awk '{printf("%s.%s,",$2,$3);}'`

# コマンド実行
eval "terraform plan -target={${target%,}}"

実行例

$ target=`cat alb.tf | grep 'resource ' | tr -d '"' | awk '{printf("%s.%s,",$2,$3);}'`
$ echo "terraform plan -target={${target%,}}"
terraform plan -target={aws_lb.example,aws_lb_listener.http,aws_lb_listener.https,aws_lb_listener.redirect_http_to_https,aws_lb_target_group.example,aws_lb_listener_rule.example}

複数ファイルをまとめてtarget指定

コマンド

# 変数に格納
target=`ls -1 \
| grep -E ".*(.tf)+" \
| xargs -n1 -I{} cat {} | grep 'resource ' | tr -d '"' | awk '{printf("%s.%s,",$2,$3);}'`

# コマンド実行
eval "terraform plan -no-color -target={${target%,}}" | tee plan-`date "+%Y%m%d-%H%M%S"`.txt

実行例

$ target=`ls -1 \
| grep -E ".*(.tf)+" \
| xargs -n1 -I{} cat {} | grep 'resource ' | tr -d '"' | awk '{printf("%s.%s,",$2,$3);}'`
$ echo "terraform plan -target={${target%,}}"
terraform plan -target={aws_lb.example,aws_lb_listener.http,aws_lb_listener.https,aws_lb_listener.redirect_http_to_https,aws_lb_target_group.example,aws_lb_listener_rule.example,aws_cloudwatch_log_group.for_ecs_scheduled_tasks,aws_ecs_task_definition.example_batch,aws_cloudwatch_event_rule.example_batch,aws_cloudwatch_event_target.example_batch,aws_ecs_cluster.example,aws_cloudwatch_log_group.for_ecs,aws_ecs_task_definition.example,aws_ecs_service.example,aws_iam_policy.example,aws_route53_zone.example,aws_route53_record.example,aws_route53_record.delegate_ns,aws_acm_certificate.example,aws_route53_record.example_certificate,aws_acm_certificate_validation.example,aws_s3_bucket.private,aws_s3_bucket_public_access_block.private,aws_s3_bucket.public,aws_s3_bucket.alb_log,aws_s3_bucket_policy.alb_log,aws_s3_bucket.force_destroy,aws_vpc.example,aws_subnet.public_0,aws_subnet.public_1,aws_internet_gateway.example,aws_route_table.public,aws_route.public,aws_route_table_association.public_0,aws_route_table_association.public_1,aws_subnet.private_0,aws_subnet.private_1,aws_route_table.private_0,aws_route_table.private_1,aws_route.private_0,aws_route.private_1,aws_route_table_association.private_0,aws_route_table_association.private_1,aws_eip.nat_gateway_0,aws_eip.nat_gateway_1,aws_nat_gateway.nat_gateway_0,aws_nat_gateway.nat_gateway_1}