Interview Prep/Ansible/Ad-hoc Commands, Modules and Idempotency

When do you use `copy`, `template`, `lineinfile` and `blockinfile`?

IntermediateConceptAd-hoc Commands, Modules and Idempotency
Answer
  • copy — place a static file or inline content: as-is.
  • template — render a Jinja2 .j2 file with variables, then place it. Default for config files.
  • lineinfile — ensure one line is present/absent, optionally replacing a regex match.
  • blockinfile — manage a marked multi-line block inside a file you do not fully own.

If you own the whole file, use template. Editing files in place with lineinfile becomes hard to reason about once a file has more than a few managed lines.

All Ansible questions Roadmap: Ansible

More on Ad-hoc Commands, Modules and Idempotency