Ansible Lint -> 쓰지 않은 내가 곰탱이다

Ansible-lint로 쿠버네티스 플레이북 개선하기: 편안한 개발 환경 설정 🚀

안녕하세요, 여러분! 오늘은 Ansible 플레이북 개발 시 만나게 되는 수많은 린트 오류들과 효과적으로 대처하는 방법에 대해 이야기해볼게요. 특히 쿠버네티스 환경 구성처럼 복잡한 플레이북을 작성할 때는 이런 기술이 정말 유용합니다! ✨

왜 어려운 길로 갈까요? 편한 길이 있는데! 🤔

Ansible 플레이북을 작성하다 보면 이런 경험 있으신가요?

❌ Use FQCN for builtin module actions (file). ansible-lint(fqcn[action-core])
❌ Trailing spaces ansible-lint(yaml[trailing-spaces])
❌ Use shell only when shell functionality is required. ansible-lint(command-instead-of-shell)

이런 빨간색 오류 메시지들이 화면에 가득하면 정말 스트레스 받고 집중력도 흐트러지죠. 모든 오류를 하나하나 수정하는 것도 가능하지만, 린트 설정을 조정해서 더 편안한 개발 환경을 만드는 방법도 있습니다!

Ansible-lint는 무엇인가요? 🧐

Ansible-lint는 Ansible 플레이북을 검사하고 모범 사례에 맞게 작성되었는지 확인하는 도구입니다. 이 도구가 하는 일은:

  • YAML 문법 검사
  • Ansible 모듈 사용법 검사
  • 잠재적 보안 문제 감지
  • 스타일 가이드 준수 여부 확인
  • 모범 사례 권장

설치 방법 📦

운영체제에 따라 다양한 방법으로 설치할 수 있습니다:

macOS (Homebrew 사용):

brew install ansible-lint

pip 사용 (모든 운영체제):

pip install ansible-lint

VSCode에서 Ansible-lint 설정하기 💻

1. 필요한 확장 프로그램 설치

  • Red Hat의 “Ansible” 확장
  • Red Hat의 “YAML” 확장

2. VSCode 설정

VSCode의 settings.json에 다음 항목을 추가합니다 (Cmd+, 또는 Ctrl+,로 열 수 있습니다):

{
  "editor.formatOnSave": true,
  "[yaml]": {
    "editor.defaultFormatter": "redhat.vscode-yaml",
    "editor.formatOnSave": true,
    "editor.tabSize": 2,
    "editor.insertSpaces": true
  },
  "yaml.format.enable": true,
  "yaml.validate": true,
  "ansible.validation.enabled": true,
  "ansible.ansible.path": "ansible"
}

.ansible-lint 파일로 규칙 맞춤설정하기 ⚙️

프로젝트의 루트 디렉토리에 .ansible-lint 파일을 생성하면 린트 규칙을 맞춤설정할 수 있습니다. 이 파일을 사용하면 특정 규칙을 비활성화하거나, 특정 파일을 검사에서 제외할 수 있습니다.

물뮤(MoolMeow) 프로젝트에 사용한 .ansible-lint 파일의 예시입니다:

# .ansible-lint 파일

# 특정 규칙 비활성화
skip_list:
  # 모듈 관련 규칙
  - command-instead-of-module  # curl 대신 get_url 사용 등의 경고
  - command-instead-of-shell   # command 대신 shell 모듈 사용 경고
  - fqcn[action-core]          # 정규화된 컬렉션 이름 사용 경고
  
  # 셸 스크립트 관련 규칙
  - risky-shell-pipe           # 셸 파이프 사용 시 pipefail 옵션 경고
  
  # 일반적인 모범 사례 규칙
  - no-handler                 # 핸들러 사용 권장 경고
  - no-changed-when            # changed_when 사용 권장 경고
  
  # YAML 형식 관련 규칙
  - yaml[truthy]               # True/False 표현 방식 경고
  - yaml[trailing-spaces]      # 후행 공백 경고
  - yaml[line-length]          # 줄 길이 제한 경고

# 문법 파싱 중 무시할 파일/디렉토리
exclude_paths:
  - .git/
  - .vscode/
  - .ansible-lint
  
# 린트시 경고만 표시할 규칙
warn_list:
  - experimental               # 실험적 기능 경고만 표시

자주 발생하는 린트 오류와 해결 방법 🛠️

1. FQCN 관련 오류

오류메시지:

Use FQCN for builtin module actions (file). ansible-lint(fqcn[action-core])

해결방법: 정규화된 컬렉션 이름(FQCN)을 사용하거나, 규칙을 비활성화합니다.

# 비정규화된 방식 (경고 발생)
- file:
    path: /path/to/file
    state: touch

# 정규화된 방식 (권장사항)
- ansible.builtin.file:
    path: /path/to/file
    state: touch

# 또는 .ansible-lint에 규칙 비활성화:
# skip_list:
#   - fqcn[action-core]

2. shell 대신 command 모듈 사용 권장

오류메시지:

Use shell only when shell functionality is required. ansible-lint(command-instead-of-shell)

해결방법: 쉘 기능(파이프, 리다이렉션 등)이 필요하지 않으면 command 모듈을 사용하거나, 규칙을 비활성화합니다.

# 규칙 비활성화 (.ansible-lint)
skip_list:
  - command-instead-of-shell

3. 파이프라인 사용 시 pipefail 옵션 권장

오류메시지:

Shells that use pipes should set the pipefail option. ansible-lint(risky-shell-pipe)

해결방법: pipefail 옵션을 설정하거나, 규칙을 비활성화합니다.

- name: Command with pipe
  shell: command1 | command2
  args:
    executable: /bin/bash
    pipefail: true

# 또는 규칙 비활성화 (.ansible-lint)
skip_list:
  - risky-shell-pipe

4. 서비스 재시작 작업은 핸들러로 분리 권장

오류메시지:

Tasks that run when changed should likely be handlers. ansible-lint(no-handler)

해결방법: 핸들러를 사용하거나, 규칙을 비활성화합니다.

# 규칙 비활성화 (.ansible-lint)
skip_list:
  - no-handler

다양한 프로젝트 상황에 맞는 .ansible-lint 예시 📋

1. 엄격한 규칙 적용 (초보자/정식 프로젝트)

skip_list: []  # 모든 규칙 적용
warn_list:
  - experimental  # 실험적 기능은 경고만

2. 중간 수준 (진행 중인 개발)

skip_list:
  - fqcn[action-core]
  - yaml[trailing-spaces]
  - yaml[line-length]

3. 유연한 설정 (빠른 프로토타이핑)

skip_list:
  - command-instead-of-module
  - command-instead-of-shell
  - fqcn[action-core]
  - risky-shell-pipe
  - no-handler
  - no-changed-when
  - yaml[truthy]
  - yaml[trailing-spaces]
  - yaml[line-length]

결론: 편안한 길을 선택하세요 🌈

복잡한 Ansible 플레이북을 작성할 때는 처음부터 모든 모범 사례를 완벽하게 따르기보다, 점진적으로 개선해나가는 접근 방식이 더 효율적일 수 있습니다. .ansible-lint 파일을 활용하면 당장 중요하지 않은 린트 경고는 무시하고, 핵심 기능 개발에 집중할 수 있습니다.

개발이 어느 정도 진행된 후에는 .ansible-lint 파일을 점진적으로 엄격하게 수정하여 코드 품질을 향상시킬 수 있습니다. 중요한 것은 균형 잡힌 접근법! 너무 엄격한 규칙으로 개발 속도를 늦추지 말고, 너무 느슨한 규칙으로 나쁜 습관을 키우지도 말아야 합니다. 😊

어떤 규칙이 프로젝트에 적합한지 팀과 논의하고, 모두가 편안하게 작업할 수 있는 환경을 만들어보세요. 불필요한 스트레스 없이 생산성 높은 Ansible 개발을 즐기시길 바랍니다! 🚀

#Ansible #Kubernetes #DevOps #AnsibleLint #MoolMeow

Improving Kubernetes Playbooks with Ansible-lint: Setting Up a Comfortable Development Environment 🚀

Hello everyone! Today, I’d like to talk about effectively dealing with the numerous lint errors you encounter when developing Ansible playbooks. This technique is particularly useful when creating complex playbooks, such as those for configuring Kubernetes environments! ✨

Why Take the Hard Road When There’s an Easy One? 🤔

Have you ever experienced this while writing Ansible playbooks?

❌ Use FQCN for builtin module actions (file). ansible-lint(fqcn[action-core])
❌ Trailing spaces ansible-lint(yaml[trailing-spaces])
❌ Use shell only when shell functionality is required. ansible-lint(command-instead-of-shell)

When these red error messages fill your screen, it’s really stressful and breaks your concentration. While it’s possible to fix each error one by one, you can also adjust your lint settings to create a more comfortable development environment!

What is Ansible-lint? 🧐

Ansible-lint is a tool that checks Ansible playbooks and verifies they’re written according to best practices. This tool:

  • Checks YAML syntax
  • Verifies Ansible module usage
  • Detects potential security issues
  • Ensures style guide compliance
  • Recommends best practices

Installation Methods 📦

You can install it in various ways depending on your operating system:

macOS (using Homebrew):

brew install ansible-lint

Using pip (all operating systems):

pip install ansible-lint

Setting Up Ansible-lint in VSCode 💻

1. Install Required Extensions

  • “Ansible” extension by Red Hat
  • “YAML” extension by Red Hat

2. VSCode Settings

Add these items to your VSCode settings.json (open with Cmd+, or Ctrl+,):

{
  "editor.formatOnSave": true,
  "[yaml]": {
    "editor.defaultFormatter": "redhat.vscode-yaml",
    "editor.formatOnSave": true,
    "editor.tabSize": 2,
    "editor.insertSpaces": true
  },
  "yaml.format.enable": true,
  "yaml.validate": true,
  "ansible.validation.enabled": true,
  "ansible.ansible.path": "ansible"
}

Customizing Rules with a .ansible-lint File ⚙️

By creating a .ansible-lint file in your project’s root directory, you can customize lint rules. This file allows you to disable specific rules or exclude certain files from inspection.

Here’s an example .ansible-lint file used in the MoolMeow project:

# .ansible-lint file

# Disable specific rules
skip_list:
  # Module related rules
  - command-instead-of-module  # Warnings about using get_url instead of curl, etc.
  - command-instead-of-shell   # Warnings about using shell module instead of command
  - fqcn[action-core]          # Warnings about using fully qualified collection names
  
  # Shell script related rules
  - risky-shell-pipe           # Warnings about pipefail option when using shell pipes
  
  # General best practice rules
  - no-handler                 # Warnings recommending handlers
  - no-changed-when            # Warnings recommending changed_when
  
  # YAML format related rules
  - yaml[truthy]               # Warnings about True/False expression methods
  - yaml[trailing-spaces]      # Warnings about trailing spaces
  - yaml[line-length]          # Warnings about line length limits

# Files/directories to ignore during syntax parsing
exclude_paths:
  - .git/
  - .vscode/
  - .ansible-lint
  
# Rules to only show warnings for
warn_list:
  - experimental               # Only display warnings for experimental features

Common Lint Errors and Solutions 🛠️

1. FQCN Related Errors

Error message:

Use FQCN for builtin module actions (file). ansible-lint(fqcn[action-core])

Solution: Use Fully Qualified Collection Names (FQCN) or disable the rule.

# Non-FQCN method (generates warnings)
- file:
    path: /path/to/file
    state: touch

# FQCN method (recommended)
- ansible.builtin.file:
    path: /path/to/file
    state: touch

# Or disable the rule in .ansible-lint:
# skip_list:
#   - fqcn[action-core]

2. Recommendation to Use Command Module Instead of Shell

Error message:

Use shell only when shell functionality is required. ansible-lint(command-instead-of-shell)

Solution: Use the command module if shell features (pipes, redirections, etc.) aren’t needed, or disable the rule.

# Disable rule (.ansible-lint)
skip_list:
  - command-instead-of-shell

3. Recommendation for Pipefail Option When Using Pipelines

Error message:

Shells that use pipes should set the pipefail option. ansible-lint(risky-shell-pipe)

Solution: Set the pipefail option or disable the rule.

- name: Command with pipe
  shell: command1 | command2
  args:
    executable: /bin/bash
    pipefail: true

# Or disable the rule (.ansible-lint)
skip_list:
  - risky-shell-pipe

4. Recommendation to Separate Service Restart Actions as Handlers

Error message:

Tasks that run when changed should likely be handlers. ansible-lint(no-handler)

Solution: Use handlers or disable the rule.

# Disable rule (.ansible-lint)
skip_list:
  - no-handler

.ansible-lint Examples for Various Project Situations 📋

1. Strict Rule Application (Beginners/Official Projects)

skip_list: []  # Apply all rules
warn_list:
  - experimental  # Only warn for experimental features

2. Medium Level (Ongoing Development)

skip_list:
  - fqcn[action-core]
  - yaml[trailing-spaces]
  - yaml[line-length]

3. Flexible Settings (Quick Prototyping)

skip_list:
  - command-instead-of-module
  - command-instead-of-shell
  - fqcn[action-core]
  - risky-shell-pipe
  - no-handler
  - no-changed-when
  - yaml[truthy]
  - yaml[trailing-spaces]
  - yaml[line-length]

Conclusion: Choose the Comfortable Path 🌈

When writing complex Ansible playbooks, a gradual improvement approach can be more efficient than perfectly following all best practices from the start. Using a .ansible-lint file lets you ignore lint warnings that aren’t immediately important, allowing you to focus on developing core functionality.

After development has progressed to a certain point, you can gradually make your .ansible-lint file stricter to improve code quality. The key is a balanced approach! Don’t slow down development speed with overly strict rules, but also don’t foster bad habits with rules that are too relaxed. 😊

Discuss which rules are appropriate for your project with your team, and create an environment where everyone can work comfortably. Enjoy productive Ansible development without unnecessary stress! 🚀

#Ansible #Kubernetes #DevOps #AnsibleLint #MoolMeow

답글 남기기