2. Given the function
$$
f(x)=\cos ^{2} x-a \sin x+2
$$

has a maximum value of 5. Then the value of the real number $a$ is $\qquad$ .
2. $\pm 3$.

Notice,
$$
f(x)=-\left(\sin x+\frac{a}{2}\right)^{2}+3+\frac{a^{2}}{4} \text {. }
$$

When $-1 \leqslant \frac{a}{2} \leqslant 1$,
$$
f(x)_{\max }=3+\frac{a^{2}}{4}=5
$$
$\Rightarrow a= \pm 2 \sqrt{2} \notin[-2,2]$ (discard);
When $\frac{a}{2} \geqslant 1$,
$$
f(x)_{\max }=2+a=5 \Rightarrow a=3 ;
$$

When $\frac{a}{2} \leqslant-1$,
$$
f(x)_{\max }=2-a=5 \Rightarrow a=-3 .
$$

In summary, $a= \pm 3$.