Introduction to Ansible Transcripts
Lecture: Ansible Variables
0:00 We're going to modify our existing playbook to use variables instead of hardcoding values and tasks. This will make our playbooks more maintainable
0:08 and much easier to read. Flip back over into your development environment. We should be in the same directory where we have our first playbook.
0:16 Create a new directory named group_vars. Within group_vars, create a file named all. In all, we're going to have a bunch of key value pairs
0:26 and a couple of good ones to start with are the values for our deployer user and the name of the group we have for the deployer user.
0:32 So instead of hardcoding deployer or deployers in our task we'll pull that from a variable. Your first variable, deploy_user.
0:39 deploy_user will be named deployer. A deploy_group as a second key the deployers as the value. Save the file
0:51 go back to the route directory of our playbook and into roles/common/tasks and modify the new_user file. Instead of having hardcoded name deployers
1:02 we'll use the variable here. And here where we create our non-root user we use the deploy_user variable and again, deploy_group as our variable.
1:18 Keep going down and then under our user of deploy user then we'll save that. And there's a couple other places where we could use variables.
1:26 For example, which shell we would want and this hardcoded path for where our public key is. But let's give this a try for now
1:32 just with these two new variables and see how this works. Head back into the top level directory and let's re-run our playbook. Same command as before.
1:49 Okay, and we ran into an issue and this will often come up if you have hardcoded values and you're placing them with variables.
1:55 The spaces are throwing off Ansible. It can't parse what's happening here so we need to make sure that we have double quotes
2:01 around our variable names when they're used as values. So just head back into roles/common/tasks, modify the user
2:10 and then down here, name, deploy_group make sure to put all these in double quotes. Cool. Let's re-run this. Okay, so I got us past the first error
2:26 and this is a really good time to take a look at a common error that will come up when you make a typo. So we had a variable defined deploy_user
2:33 but in this case, I typed in deployer_user and of course, there is no deployer_user variable. So let's fix this one error where we said deployer
2:45 and re-run one more time. Awesome. Everything was successful and now as you can see, under group_vars when we take a look at our variables file
2:55 we now have two variables: deploy_user, deploy_group and their values which we can change whenever we want.
3:01 So if I wanted my deploye_user to be named matt do that instead and that would then affect every place
3:06 that we've used this variable across our entire playbook. Much more maintainable than hardcoding deployer everywhere.