What are the injection risks in Ansible, and how do you mitigate them?
AdvancedProductionSecurity and Secrets
Answer
Two classes. Template injection happens when untrusted text (an EC2 tag, a hostname, command output, an API response) is rendered as Jinja2 and contains {{ ... }}. Ansible marks facts, registered results and lookup outputs as unsafe by default so they are not re-templated. Do not defeat that with | from_json on untrusted input and then template it, or by allow_unsafe.
Shell injection happens when variables go into shell: strings. Mitigate by using modules or command with argv, and quoting with quote where a shell is unavoidable.
- ansible.builtin.command:
argv: ["/usr/bin/grep", "-r", "{{ term }}", "/var/log/app"]
- ansible.builtin.shell: "grep -r {{ term | quote }} /var/log/app"
More on Security and Secrets
How do you set up a secure automation user and SSH access?BeginnerHow do you give the automation user sudo with least privilege?IntermediateWhat are the alternatives to Ansible Vault for secrets, and when do you use them?IntermediateHow do you read AWS Secrets Manager and SSM parameters in a playbook?IntermediateHow do you integrate HashiCorp Vault with Ansible?AdvancedHow do you stop secrets from leaking into logs and output?Beginner