|
| 1 | +# OpenTofu remote state |
| 2 | + |
| 3 | +Generally, using [remote state](https://opentofu.org/docs/language/state/remote/) |
| 4 | +is recommended. |
| 5 | + |
| 6 | +This can be configured by adding additional files into the |
| 7 | +`environments/{production,staging,...}/tofu` directories. Some guidance for |
| 8 | +different backends is given here. |
| 9 | + |
| 10 | + |
| 11 | +## GitLab |
| 12 | + |
| 13 | +The following creates a state per environment. |
| 14 | + |
| 15 | +1. Create a backend file and commit it: |
| 16 | + |
| 17 | + ```terraform |
| 18 | + # environments/$ENV/tofu/backend.tf: |
| 19 | + terraform { |
| 20 | + backend "http" {} |
| 21 | + } |
| 22 | + ``` |
| 23 | +
|
| 24 | +2. Create a personal access token with API access (note Project tokens do not |
| 25 | + appear to work): |
| 26 | + - In GitLab, click on your user button at top left and select 'Preferences'. |
| 27 | + - Select 'Access tokens', 'Add new token'. |
| 28 | + - Optionally set an expiry date, select 'API' scope and click 'Create token'. |
| 29 | + - Copy the generated secret and set an environment variable in your terminal: |
| 30 | + |
| 31 | + ```shell |
| 32 | + export TF_PASSWORD=$SECRET |
| 33 | + ``` |
| 34 | +
|
| 35 | +3. Create this script and commit it: |
| 36 | + it: |
| 37 | +
|
| 38 | + ```shell |
| 39 | + # environments/$ENV/tofu/init-gitlab-backend.sh |
| 40 | + PROJECT_ID="<gitlab-project-id>" |
| 41 | + TF_USERNAME="<gitlab-username>" |
| 42 | + TF_STATE_NAME="$(basename $APPLIANCES_ENVIRONMENT_ROOT)" |
| 43 | + TF_ADDRESS="https://gitlab.com/api/v4/projects/${PROJECT_ID}/terraform/state/${TF_STATE_NAME}" |
| 44 | +
|
| 45 | + tofu init \ |
| 46 | + -backend-config=address=${TF_ADDRESS} \ |
| 47 | + -backend-config=lock_address=${TF_ADDRESS}/lock \ |
| 48 | + -backend-config=unlock_address=${TF_ADDRESS}/lock \ |
| 49 | + -backend-config=username=${TF_USERNAME} \ |
| 50 | + -backend-config=password=${TF_PASSWORD} \ |
| 51 | + -backend-config=lock_method=POST \ |
| 52 | + -backend-config=unlock_method=DELETE \ |
| 53 | + -backend-config=retry_wait_min=5 |
| 54 | + ``` |
| 55 | +
|
| 56 | + The project id can be found by clicking the 3-dot menu at the top right of |
| 57 | + the GitLab project page. |
| 58 | +
|
| 59 | +4. With the environment activated, run the script: |
| 60 | +
|
| 61 | + ```shell |
| 62 | + cd environments/$ENV/tofu/ |
| 63 | + source init-gitlab-backend.sh |
| 64 | + ``` |
| 65 | + |
| 66 | + OpenTofu is now configured to use GitLab to store state for this environment. |
| 67 | +
|
| 68 | +Repeat for each environment needing remote state. Generally, `dev` environments |
| 69 | +will be personal so should not need this. |
| 70 | +
|
| 71 | +If the project token expires, follow the above again by add an option `-reconfigure` |
| 72 | +to the script. |
| 73 | +
|
| 74 | +## S3 |
| 75 | +
|
| 76 | +TODO. |
0 commit comments