I need to express an in terms of f(x). I did it but I'm not sure if it is right.
Consider \begin{cases} -u_{xx}+u=f(x), &0<x<\ell\\[0.5em] u_x(0)=0,\;u_x(l)=0& \end{cases} Suppose that [a solution can be expressed as] $u(x)=\sum_{n=1}^\infty a_n\,\cos\left(\frac{n\pi\,x}{\ell}\right)$. Find $a_n$ in terms of $f$.

Your last equation is wrong, the sums cover all terms containing $n$, i.e., $$ \sum_{n=0}^\infty a_n\left(\left(\frac{n\pi}{\ell}\right)^2+1\right)\cos\left(\frac{n\pi\,x}{\ell}\right)=f(x) $$ Use that the functions $\cos\left(\frac{n\pi\,x}{\ell}\right)$ form an orthogonal sequence over the interval $(0,\ell)$. Or more directly, find the representation of $f$ as a cosine series.