Introduction to Ansible Transcripts
Chapter: Data
Lecture: Environment Variables

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Now that we know how to set variables in separate files from our roles we also need to know how to read environment variables.
0:08 Those are variables set on the system that wouldn't be hard-coded in any files. What do we mean by an environment variable?
0:14 Let's say you're in your shell and you want to set a variable that you can read across the system.
0:18 You'd use the export command and then a variable name and then followed by a value. Now we can read to this environment variable
0:30 and using the echo command print it out to the command line. So we set the value of ansible.out to the key filename.
0:37 Let's set another environment variable. This time it'll be more useful. In our first playbook we upload a public SSH key as our authorized key
0:45 and that allows us to log in with our private key but we hard-coded where that key was stored which really should be set as a variable
0:51 Whether stored in a file or as an environment variable. Let's set it as an environment variable. We'll read it into our Ansible playbook
0:56 and use it as a part of our task. So we'll say authorized key and we'll give it the same authorized key that we used in the last chapter.
1:13 So now that authorized key is set we can read it into our Ansible playbook. Open up group_vars/all and set a new authorized key variable name.
1:26 Now we're going to use the lookup template tag to look up environment variable named authorized key.
1:38 And let's actually call this authorized key filename to differentiate it from the contents of an authorized key file.
1:47 So now that we have authorized key filename we can go back into our roles common tasks modify new user. Go down to the key and we'll change lookup file
1:59 instead of setting this through a string we're going to have our variable name here. Save that, go back up to the top project directory
2:12 now we're in our playbook. Awesome, so Ansible was able to get the environment variable that we had set as authorized key
2:21 read it in as the variable authorized key filename and we were able to use it in one of our tasks as part of our playbook.

Talk Python's Mastodon Michael Kennedy's Mastodon